|
| 1 | +package com.fishercoder.solutions.fourththousand; |
| 2 | + |
| 3 | +public class _3228 { |
| 4 | + public static class Solution1 { |
| 5 | + /** |
| 6 | + * This is literal simulation and swap the 1s and 0s, but ended up in TLE, so you'll have to do better. |
| 7 | + */ |
| 8 | + public int maxOperations(String s) { |
| 9 | + char[] arr = s.toCharArray(); |
| 10 | + int len = arr.length; |
| 11 | + int maxOps = 0; |
| 12 | + int oneIndex = 0; |
| 13 | + int zeroIndex = 0; |
| 14 | + while (oneIndex < len && arr[oneIndex] == '0') { |
| 15 | + oneIndex++; |
| 16 | + } |
| 17 | + //now we found the first one, then we'll have to find the last one in case there's a consecutive group of 1's |
| 18 | + int firstOneOccurrence = oneIndex; |
| 19 | + while (oneIndex < len && zeroIndex < len) { |
| 20 | + while (oneIndex < len && arr[oneIndex] == '1') { |
| 21 | + oneIndex++; |
| 22 | + } |
| 23 | + oneIndex--; |
| 24 | + |
| 25 | + zeroIndex = oneIndex; |
| 26 | + while (zeroIndex < len && arr[zeroIndex] == '1') { |
| 27 | + zeroIndex++; |
| 28 | + } |
| 29 | + //likewise, we need to find the last occurrence of 0 in case there's a group of consecutive 0's |
| 30 | + while (zeroIndex < len && arr[zeroIndex] == '0') { |
| 31 | + zeroIndex++; |
| 32 | + } |
| 33 | + if (zeroIndex >= len && arr[zeroIndex - 1] == '1') { |
| 34 | + return maxOps; |
| 35 | + } |
| 36 | + int nextBeginOneIndex = zeroIndex; |
| 37 | + zeroIndex--; |
| 38 | + |
| 39 | + int ops = 0; |
| 40 | + do { |
| 41 | + int[] swappedIndex = swap(arr, zeroIndex, oneIndex); |
| 42 | + oneIndex = swappedIndex[0]; |
| 43 | + zeroIndex = swappedIndex[1]; |
| 44 | + ops++; |
| 45 | + } while (oneIndex >= firstOneOccurrence); |
| 46 | + maxOps += ops; |
| 47 | + firstOneOccurrence = zeroIndex + 1; |
| 48 | + oneIndex = nextBeginOneIndex; |
| 49 | + } |
| 50 | + return maxOps; |
| 51 | + } |
| 52 | + |
| 53 | + private int[] swap(char[] arr, int zeroIndex, int oneIndex) { |
| 54 | + char tmp = arr[zeroIndex]; |
| 55 | + arr[zeroIndex] = arr[oneIndex]; |
| 56 | + arr[oneIndex] = tmp; |
| 57 | + return new int[]{oneIndex - 1, zeroIndex - 1}; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + public static class Solution2 { |
| 62 | + /** |
| 63 | + * TODO: finish this. |
| 64 | + */ |
| 65 | + public int maxOperations(String s) { |
| 66 | + int maxOps = 0; |
| 67 | + return maxOps; |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments