Skip to content

Commit 2193492

Browse files
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 112.2 MB (47.28%)
1 parent 0fb00ad commit 2193492

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<p>You are given a binary array <code>nums</code> and an integer <code>k</code>.</p>
2+
3+
<p>A <strong>k-bit flip</strong> is choosing a <strong>subarray</strong> of length <code>k</code> from <code>nums</code> and simultaneously changing every <code>0</code> in the subarray to <code>1</code>, and every <code>1</code> in the subarray to <code>0</code>.</p>
4+
5+
<p>Return <em>the minimum number of <strong>k-bit flips</strong> required so that there is no </em><code>0</code><em> in the array</em>. If it is not possible, return <code>-1</code>.</p>
6+
7+
<p>A <strong>subarray</strong> is a <strong>contiguous</strong> part of an array.</p>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
12+
<pre>
13+
<strong>Input:</strong> nums = [0,1,0], k = 1
14+
<strong>Output:</strong> 2
15+
<strong>Explanation:</strong> Flip nums[0], then flip nums[2].
16+
</pre>
17+
18+
<p><strong class="example">Example 2:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> nums = [1,1,0], k = 2
22+
<strong>Output:</strong> -1
23+
<strong>Explanation:</strong> No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].
24+
</pre>
25+
26+
<p><strong class="example">Example 3:</strong></p>
27+
28+
<pre>
29+
<strong>Input:</strong> nums = [0,0,0,1,0,1,1,0], k = 3
30+
<strong>Output:</strong> 3
31+
<strong>Explanation:</strong>
32+
Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]
33+
Flip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]
34+
Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]
35+
</pre>
36+
37+
<p>&nbsp;</p>
38+
<p><strong>Constraints:</strong></p>
39+
40+
<ul>
41+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
42+
<li><code>1 &lt;= k &lt;= nums.length</code></li>
43+
</ul>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public:
3+
int minKBitFlips(vector<int>& nums, int k) {
4+
int n = nums.size();
5+
int ans = 0;
6+
int flips = 0;
7+
queue<int> indices;
8+
for (int i=0; i<n; i++) {
9+
while (!indices.empty() && i > indices.front()) {
10+
indices.pop();
11+
flips--;
12+
}
13+
14+
if ((nums[i] & 1) == (flips & 1)) {
15+
if (i + k > n) return -1;
16+
17+
indices.push(i + k - 1);
18+
flips++;
19+
ans++;
20+
}
21+
}
22+
23+
return ans;
24+
}
25+
};

0 commit comments

Comments
 (0)