- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_3192.java
31 lines (30 loc) · 1.38 KB
/
_3192.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
packagecom.fishercoder.solutions.fourththousand;
publicclass_3192 {
publicstaticclassSolution1 {
/*
* 1. Go from left to right;
* 2. The only way to flip the entire array to be 1s is to change each nums[i] = 0 to nums[i] = 1 whenever we encounter a 0;
* 3. if we flip each number twice, it's back to its original number, so we only need to keep track of how many times each number is flipped instead of actually flipping the number;
* 4. keep the original array intact, check two conditions:
* nums[i] is 0 or 1
* ops is odd or even
*/
publicintminOperations(int[] nums) {
intops = 0;
for (inti = 0; i < nums.length; i++) {
if (nums[i] == 0 && ops % 2 == 0) {
// this means after an even number of flipping, this number is (originally) a
// zero, so we need to flip it and all the numbers to its right
ops++;
}
if (nums[i] == 1 && ops % 2 == 1) {
// this means after an odd number of flipping prior to reaching this number and
// this number is a one, so it should have been flipped to become a zero, so we
// need to flip it
ops++;
}
}
returnops;
}
}
}