[Leetcode]1004. Max Consecutive Ones III(x)
2024. 7. 31. 10:29ㆍjava/javaAlgorithm
1. problem :
https://leetcode.com/problems/max-consecutive-ones-iii/?envType=study-plan-v2&envId=leetcode-75
2. solution 1 :
class Solution {
public int longestOnes(int[] nums, int k) {
int left = 0, right = 0;
int maxOnes = 0;
int zeroCount = 0;
while (right < nums.length) {
if (nums[right] == 0) {
zeroCount++;
}
while (zeroCount > k) {
if (nums[left] == 0) {
zeroCount -= 1;
}
left++;
}
maxOnes = Math.max(maxOnes,right-left+1);
right++;
}
return maxOnes;
}
}
1. right의 역할은 0을 count 하는 거다. 0을 count 하면서 k이상으로 0의 개수가 많아질 때는 , left를 이동하면서 0의 개수를 줄인다. k와 같아질 때까지, 이때, consecutive 한 1을 count 하는 법은 기존의 maxOnes와 right-left+1을 이용해 구할 수 있다.
'java > javaAlgorithm' 카테고리의 다른 글
[Leetcode]49. Group Anagrams(x) (0) | 2024.07.31 |
---|---|
[Leetcode]15. 3Sum(x) (0) | 2024.07.30 |
[Leetcode]1. Two Sum (0) | 2024.07.30 |
[Leetcode]242. Valid Anagram (0) | 2024.07.30 |
[Leetcode]217. Contains Duplicate (0) | 2024.07.30 |