Skip to content

Commit c392b12

Browse files
committed
Add solution #487
1 parent 412d024 commit c392b12

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,7 @@
475475
484|[Find Permutation](./solutions/0484-find-permutation.js)|Medium|
476476
485|[Max Consecutive Ones](./solutions/0485-max-consecutive-ones.js)|Easy|
477477
486|[Predict the Winner](./solutions/0486-predict-the-winner.js)|Medium|
478+
487|[Max Consecutive Ones II](./solutions/0487-max-consecutive-ones-ii.js)|Medium|
478479
488|[Zuma Game](./solutions/0488-zuma-game.js)|Hard|
479480
491|[Non-decreasing Subsequences](./solutions/0491-non-decreasing-subsequences.js)|Medium|
480481
492|[Construct the Rectangle](./solutions/0492-construct-the-rectangle.js)|Easy|
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 487. Max Consecutive Ones II
3+
* https://leetcode.com/problems/max-consecutive-ones-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given a binary array nums, return the maximum number of consecutive 1's in the array
7+
* if you can flip at most one 0.
8+
*/
9+
10+
/**
11+
* @param {number[]} nums
12+
* @return {number}
13+
*/
14+
var findMaxConsecutiveOnes = function(nums) {
15+
let result = 0;
16+
let currentConsecutive = 0;
17+
let zeroCount = 0;
18+
let left = 0;
19+
20+
for (let right = 0; right < nums.length; right++) {
21+
if (nums[right] === 0) {
22+
zeroCount++;
23+
}
24+
25+
while (zeroCount > 1) {
26+
if (nums[left] === 0) {
27+
zeroCount--;
28+
}
29+
currentConsecutive--;
30+
left++;
31+
}
32+
33+
currentConsecutive++;
34+
result = Math.max(result, currentConsecutive);
35+
}
36+
37+
return result;
38+
};

0 commit comments

Comments
 (0)