Similar Problems

Similar Problems not available

Max Consecutive Ones - Leetcode Solution

Companies:

LeetCode:  Max Consecutive Ones Leetcode Solution

Difficulty: Easy

Topics: array  

Problem Statement:

Given a binary array nums, return the maximum number of consecutive 1's in the array.

Example 1:

Input: nums = [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.

Example 2:

Input: nums = [1,0,1,1,0,1] Output: 2

Constraints:

1 <= nums.length <= 105 nums[i] is either 0 or 1.

Solution:

We can solve this problem by traversing the array and keeping track of the current length of the consecutive 1's sequence and the maximum length of consecutive 1's sequence seen so far.

We start with a variable to keep track of the current length of consecutive 1's sequence and a variable to keep track of the maximum length of consecutive 1's sequence seen so far.

Then, we iterate through the array and if we encounter a 1, we increase the current length of consecutive 1's sequence by 1. If we encounter a 0, we reset the current length of consecutive 1's sequence to 0. Finally, on each iteration, we update the maximum length of consecutive 1's sequence seen so far if the current length is greater than the maximum length.

Here's the Python code to implement the above algorithm:

def findMaxConsecutiveOnes(nums): max_ones = 0 cur_ones = 0

for num in nums:
    if num == 1:
        cur_ones += 1
    else:
        cur_ones = 0
    max_ones = max(max_ones, cur_ones)

return max_ones

nums = [1,1,0,1,1,1] print(findMaxConsecutiveOnes(nums)) # Output: 3

nums = [1,0,1,1,0,1] print(findMaxConsecutiveOnes(nums)) # Output: 2

Complexity Analysis:

Time Complexity: O(n), where n is the length of the array nums. We traverse the entire array once.

Space Complexity: O(1). We use constant extra space to store the variable max_ones and cur_ones.

Max Consecutive Ones Solution Code

1