Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions cpp/0487-max-consecutive-ones-ii.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int answer = 0;

int secondMostRecentZero = -1;
int mostRecentZero = -1;

for(int i = 0; i < nums.size(); i++) {

if(nums[i] == 0) {
secondMostRecentZero = mostRecentZero;
mostRecentZero = i;
}

// for any i, the longest sequence ending at i is
// the distance from the second most recent zero
// since the most recent can be thought of as flipped
answer = max(answer, i-secondMostRecentZero);
}

return answer;
}
};