-
Notifications
You must be signed in to change notification settings - Fork 0
/
16-1004.ts
41 lines (33 loc) · 1.02 KB
/
16-1004.ts
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
32
33
34
35
36
37
38
39
40
41
// https://leetcode.com/problems/max-consecutive-ones-iii/description/?envType=study-plan-v2&envId=leetcode-75
const longestOnes = (nums: number[], k: number): number => {
// NOSONAR
if (nums.length <= k) return nums.length;
let firstIdx = 0,
lastIdx = 0,
flippedZerosCount = 0,
longest = 0;
// O(N) SOLUTION
while (flippedZerosCount !== k && lastIdx < nums.length) {
if (!nums[lastIdx]) flippedZerosCount++;
lastIdx++;
}
// lastIdx IS AT: LAST SUBARRAY IDX + 1
// USE lastIdx AND firstIdx TO CALCULATE SUBARRAY LENGTH
longest = lastIdx - firstIdx;
while (lastIdx < nums.length) {
if (!nums[lastIdx]) {
if (!nums[firstIdx]) flippedZerosCount++;
flippedZerosCount--;
firstIdx++;
} else if (flippedZerosCount !== k) {
if (nums[firstIdx]) flippedZerosCount--;
flippedZerosCount++;
firstIdx++;
} else {
const tempLongest = lastIdx - firstIdx + 1;
if (tempLongest > longest) longest = tempLongest;
}
lastIdx++;
}
return longest;
};