LC 485. Max Consecutive Ones

Sarthak Sehgal · April 1, 2020

This is a very straightforward problem. Use two variables, currentCount and maxCount and update them as your traverse the array. Whenever you encounter a 0, reset the currentCount to 0 else update it (currentCount = currentCount+1).

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int n = nums.size(), currentCount = 0, maxCount = INT_MIN;

        for (int i=0; i<n; i++) {
            if(nums[i]==1){
                currentCount ++;
            } else {
							currentCount = 0;
						}

						maxCount = max(currentCount, maxCount);
        }

        return maxCount;
    }
};

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

Short code:

int findMaxConsecutiveOnes(vector<int>& nums) {
		int currentCount = 0, maxCount = 0;
		for (int n : nums)
				maxCount = max(maxCount, currentCount = n == 0 ? 0 : currentCount + 1);
		return maxCount;
}

Twitter, Facebook