Skip to content

Commit 07038ac

Browse files
committed
Update 1151_Minimum_Swaps_to_Group_All_1's_Together.java
1 parent 2827379 commit 07038ac

File tree

1 file changed

+10
-15
lines changed

1 file changed

+10
-15
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,27 @@
11
class Solution {
22
public int minSwaps(int[] data) {
3-
if (data == null || data.length == 0) {
4-
return 0;
5-
}
6-
7-
int windowSize = 0;
3+
int onesCount = 0;
84

95
for (int d : data) {
10-
if (d == 1) {
11-
++windowSize;
12-
}
6+
onesCount += d;
137
}
148

15-
int result = 0, onesCount = 0;
16-
int left = 0, right = 0;
9+
int left = 0, right = 0, maxOnesWindow = 0, result = 0;
1710

1811
while (right < data.length) {
19-
onesCount += data[right];
12+
maxOnesWindow += data[right];
2013
++right;
2114

22-
if (right - left > windowSize) {
23-
onesCount -= data[left];
15+
if (right - left > onesCount) {
16+
maxOnesWindow -= data[left];
2417
++left;
2518
}
2619

27-
result = Math.max(result, onesCount);
20+
if (right - left == onesCount) {
21+
result = Math.max(result, maxOnesWindow);
22+
}
2823
}
2924

30-
return windowSize - result;
25+
return onesCount - result;
3126
}
3227
}

0 commit comments

Comments
 (0)