Minimum Operations to Flip Exactly K Bits
Problem statement
You are given a binary array bits and an integer k.
In one operation, choose exactly k distinct indices in any positions of the array and flip their values:
0becomes1.1becomes0.
Return the minimum number of operations needed to make every array element equal to 1. If this is impossible, return -1.
Function
minExactKBitFlips(bits: int[], k: int) → intExamples
Example 1
bits = [0,0,1]k = 2return = 1Flip the two zero-valued positions. The array becomes [1,1,1] in one operation.
Example 2
bits = [0,1,1]k = 2return = -1Every operation flips an even number of bits, so the parity of the zero count cannot change from odd to zero.
Example 3
bits = [0,0,0,0]k = 3return = 4Four operations suffice by omitting a different index each time. Every index is then flipped exactly three times. Fewer operations cannot satisfy both the required parity and the number of selected positions.
Example 4
bits = [1,1,1]k = 1return = 0The array already contains only ones, so no operation is needed.
Constraints
1 <= bits.length <= 10^5.bits[i]is either0or1.1 <= k <= bits.length.