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 <= 105nums[i] is either 0 or 1.This approach involves iterating through the array and counting sequences of 1s. If a 0 is encountered, the count is reset to 0. We keep track of the maximum count during the iteration.
The function findMaxConsecutiveOnes iterates over the input array nums. It uses a counter to track consecutive ones. When a one is encountered, the counter is incremented. If a zero is encountered, the counter is reset. Throughout the iteration, the maximum sequence length is updated.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the number of elements in the array, as we make a single pass.
Space Complexity: O(1) since no extra space proportional to input size is used.
This approach uses a variation of the sliding window technique. The idea is to maintain a window of the current sequence of 1s and adjust the window whenever a 0 is encountered.
In this version, two pointers left and right maintain the window of consecutive 1s. When a 0 is found, left is moved to right + 1, effectively 'skipping' the segments with 0s, adjusting the window accordingly.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Simple Iterative Count | Time Complexity: O(n), where n is the number of elements in the array, as we make a single pass. |
| Sliding Window Technique | Time Complexity: O(n) |
L4. Max Consecutive Ones III | 2 Pointers and Sliding Window Playlist • take U forward • 166,953 views views
Watch 9 more video solutions →Practice Max Consecutive Ones with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor