Skip to content

Commit cceb20a

Browse files
committed
added minimum-number-of-k-consecutive-bit-flips.java code
1 parent c805e41 commit cceb20a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//Question : https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips/description/
2+
3+
//Question exp : convert alll 0 -> 1 by doing k bit flip
4+
5+
//Ans approach : greedy approach
6+
class Solution {
7+
public int minKBitFlips(int[] nums, int k) {
8+
int n=nums.length;
9+
int flipCount=0; // range [cur - (k-1)elem] will be flipped this much times
10+
int totalFlips=0 ; //final ans
11+
12+
//true will be marked for all range's(cur indx - k-1th indx) end elem.
13+
//While traversing, if visited[cur elem]=true,
14+
//then we reduce the flipCount of cur_range ,as we move towards nxt range
15+
boolean[] visited=new boolean[n];
16+
17+
for(int i=0;i<n;i++)
18+
{
19+
//only works if, (which is flipped flipCount no of times) cur_elem's value = 0
20+
// 0 flipped even times = 0
21+
//1 flipped odd times = 0
22+
if( (nums[i]==0 && flipCount%2==0) || (nums[i]==1 && flipCount%2!=0) )
23+
{
24+
flipCount++;
25+
totalFlips++;
26+
27+
if( i+(k-1) < n )
28+
{
29+
//mark end of cur range as true
30+
//so, we can rmv the flipCount of this range, after reaching this endPoint.
31+
visited[i+(k-1)]=true;
32+
}
33+
else
34+
{
35+
//if end elem goes out of range
36+
//hence, all of arr elems cannot be flipped to 1
37+
return -1;
38+
}
39+
}
40+
41+
if(visited[i]==true)
42+
{
43+
//end point of cur_range is reached.
44+
//so reduce the flipCount of cur_range
45+
flipCount--;
46+
}
47+
48+
}
49+
50+
return totalFlips;
51+
}
52+
}

0 commit comments

Comments
 (0)