LC 485. Max Consecutive Ones

Nilanjan Deb · April 1, 2020

This is a very simple problem. I use a int variable to count continuously, and a mx variable to store maximum value of this continuously changed variable. First I traversing the array and when got 1 then add one to “cnt” variable and when I got 0 then store it to mx variable if it’s current value greater than mx. I hope remaings are self-understandable. Don’t Forgot about Corner Cases.

This is my CPP solution.

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int n = nums.size();
        int cnt = 0;
        int mx = 0;
        for(int i=0;i<n;i++){
            if(nums[i]==1){
                cnt ++;
            }
            else{
                mx = max(cnt,mx);
                cnt = 0;
            }
        }
        if(cnt!=0){
            mx = max(cnt,mx);
        }
        return mx;
    }
};

Time Complexity O(n); Space Complexity O(1);



Dicussion Forum