educative.io

I actually solved it!

Well, at least it passes the test cases given to us.

My problem is that my code is a lot more complicated than the given solution is:

class ReplacingOnes {
  public static int findLength(int[] arr, int k) {

    int zeroCount = 0;
    int oneCount = 0;

    int left = 0;
    int maxLength = 0;

    for(int right = 0; right < arr.length; right++) {
      final int i = arr[right];

      if(i == 0) {
        zeroCount++;
      } else {
        oneCount++;
      }

      if(i == 0 && oneCount > k) {
        final int leftInt = arr[left];
        if(leftInt == 0) zeroCount--;
        else oneCount--;
        left++;
      } else if(i == 1 && zeroCount > k) {
        final int leftInt = arr[left];
        if(leftInt == 0) zeroCount--;
        else oneCount--;
        left++;
      }

      maxLength = Math.max(maxLength, right - left + 1);
    }

    return maxLength;
  }
}

My issue is that should I expend effort to simplify the logic? To me it made sense to keep track of the Zero and One count, but the given solution proves that unnecessary.

As long as it’s working, I don’t think its an issue. It doesn’t majorly impact the space or time complexity either so it’s fine.

1 Like