diff --git a/cpp/0487-max-consecutive-ones-ii.cpp b/cpp/0487-max-consecutive-ones-ii.cpp new file mode 100644 index 000000000..f3c4d4a37 --- /dev/null +++ b/cpp/0487-max-consecutive-ones-ii.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int findMaxConsecutiveOnes(vector& 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; + } +}; \ No newline at end of file