-->

Sunday, January 15, 2017

486. Max Consecutive Ones II

https://leetcode.com/problems/max-consecutive-ones ii/
This is the following question of 485. If for most one 0 can be flipped to 1, then what is the max consecutive 1s?

Solution:
Nee two variables. One for the previous length of 1s, which may be used when there is only one 0 existing between 1s. The other is the count of 1s after 0.

Code:
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int res = 0, l = nums.size(), c1 = 0, pre = 0;//c1 is the counting of 1s.
        for(int i=0; i<l; ++i){
            ++pre;// the counting for previous 1s.
            ++c1;
            if(nums[i] == 0){
                c1 = pre;
                pre = 0;
            } 
            res = max(res, c1);
        }
        return res;
    }
};

No comments :

Post a Comment