995. Minimum Number of K Consecutive Bit Flips

Greedy

when meet 0, we flip

T: O(nk)

class Solution {
    public int minKBitFlips(int[] nums, int k) {
        int n = nums.length;
        int result = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] == 0) {
                for (int j = i; j < i+k; j++) {
                    if (j >= n) {
                        return -1;
                    }
                    nums[j] = (nums[j]+1)%2;
                }
                result++;
            }
        }
        return result;
    }
}

/**
T: O(nk)
greedy

when meet 0, we flip k elements
in the end, if flip k is out of boundary, it must -1
(why this greedy ok? if in order to flip some 0, and we flip some 1 before 0, 
it would't be better because we might to handle more flips in the begining, it's a chain reaction!)

0 0 0 1 0 1 1 0
-----     
        1 0 0
          

0 0 0 1 1 2 3 3
but T: O(nk) will be TLE

-> better solution, sweep line

k = 3
0 0 0 1 0 1 1 0
+      
      -
 */

use diff array

T: O(n)

S: O(n)

Last updated

Was this helpful?