Skip to content

Commit 62a1819

Browse files
committed
Time: 8 ms (5.33%), Space: 56.2 MB (91.08%) - LeetHub
1 parent d55066f commit 62a1819

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import java.util.Arrays;
2+
3+
class Solution {
4+
5+
public int longestSubarray(int[] nums) {
6+
int n = nums.length;
7+
int left = 0;
8+
int right = 0;
9+
int zeroIndex = -1;
10+
int zeroCount = 0;
11+
int answer = 0;
12+
13+
int sum = Arrays.stream(nums)
14+
.sum();
15+
if (sum == 0) {
16+
return 0;
17+
}
18+
if (sum == nums.length) {
19+
return sum - 1;
20+
}
21+
22+
if (nums[0] == 0) {
23+
zeroCount++;
24+
zeroIndex = 0;
25+
}
26+
//0이 최대 1개 포함되는 slide-window 사용
27+
while (right + 1 < n) {
28+
answer = Math.max(answer, countWindow(answer, left, right, zeroCount));
29+
if (nums[right + 1] == 1) {
30+
right++;
31+
continue;
32+
}
33+
if (nums[right + 1] == 0 && zeroCount == 0) {
34+
zeroIndex = right + 1;
35+
zeroCount++;
36+
right++;
37+
continue;
38+
}
39+
//이미 슬라이딩 윈도우에 0이 있는 경우, 먼저 들어온 0을 제외한다
40+
if (nums[right + 1] == 0 && zeroCount == 1) {
41+
//이전 0의 다음으로 left를 옮긴다
42+
left = zeroIndex + 1;
43+
zeroIndex = right + 1;
44+
right++;
45+
}
46+
}
47+
return Math.max(answer, countWindow(answer, left, right, zeroCount));
48+
}
49+
50+
private int countWindow(int answer, int left, int right, int zeroCount) {
51+
int windowLength = Math.max(answer, right - left + 1);
52+
return zeroCount == 0 ? windowLength : windowLength - 1;
53+
}
54+
}

0 commit comments

Comments
 (0)