Advertisement

Max Consecutive Ones - LeetCode 485 Solution

Max Consecutive Ones - Complete Solution Guide

Max Consecutive Ones is LeetCode problem 485, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

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 <= 10 5 nums[i] is either 0 or 1 .

Detailed Explanation

The problem asks us to find the maximum number of consecutive 1s in a given binary array (an array containing only 0s and 1s). We need to iterate through the array and keep track of the current consecutive count of 1s. Whenever we encounter a 0, we compare the current count with the maximum count found so far and update the maximum count if necessary. After the loop, we also need to compare the current count with the maximum count, as the array might end with a sequence of 1s.

Solution Approach

The provided solution utilizes a simple iterative approach to find the maximum consecutive ones. It maintains two variables: `max_count` and `current_count`. The algorithm iterates through the array, incrementing `current_count` when it encounters a 1. When it encounters a 0, it updates `max_count` with the maximum of `max_count` and `current_count`, and then resets `current_count` to 0. Finally, after iterating through the entire array, it updates `max_count` one last time to account for the case where the array ends with a sequence of 1s.

Step-by-Step Algorithm

  1. Step 1: Initialize `max_count` and `current_count` to 0.
  2. Step 2: Iterate through the input array `nums`.
  3. Step 3: If the current element is 1, increment `current_count`.
  4. Step 4: If the current element is 0, update `max_count` with the maximum of `max_count` and `current_count`, then reset `current_count` to 0.
  5. Step 5: After the loop, update `max_count` one last time with the maximum of `max_count` and `current_count` to handle cases where the array ends with consecutive 1s.
  6. Step 6: Return `max_count`.

Key Insights

  • Insight 1: The core idea is to maintain a 'current_count' of consecutive 1s and a 'max_count' to store the largest consecutive sequence seen so far.
  • Insight 2: The algorithm efficiently tracks consecutive 1s by incrementing 'current_count' when a 1 is encountered and resetting it to 0 when a 0 is encountered.
  • Insight 3: It's crucial to update 'max_count' one last time after the loop in case the array ends with a sequence of 1s, which would not have been captured otherwise.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Topics

This problem involves: Array.

Companies

Asked at: Accenture, Deloitte, Yandex.