485. Max Consecutive Ones
Problem Description
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⁵nums[i]is either0or1.
Solution
Python Solution
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
max_count = 0
current_count = 0
for num in nums:
if num == 1:
current_count += 1
max_count = max(max_count, current_count)
else:
current_count = 0
return max_count
Time Complexity: O(n)
Where n is the length of the input array.
Space Complexity: O(1)
Only constant extra space is used.
Java Solution
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int maxCount = 0;
int currentCount = 0;
for (int num : nums) {
if (num == 1) {
currentCount++;
maxCount = Math.max(maxCount, currentCount);
} else {
currentCount = 0;
}
}
return maxCount;
}
}
Time Complexity: O(n)
Where n is the length of the input array.
Space Complexity: O(1)
Only constant extra space is used.
C++ Solution
class Solution {
public:
int findMaxConsecutiveOnes(vector& nums) {
int maxCount = 0;
int currentCount = 0;
for (int num : nums) {
if (num == 1) {
currentCount++;
maxCount = max(maxCount, currentCount);
} else {
currentCount = 0;
}
}
return maxCount;
}
};
Time Complexity: O(n)
Where n is the length of the input array.
Space Complexity: O(1)
Only constant extra space is used.
JavaScript Solution
/**
* @param {number[]} nums
* @return {number}
*/
var findMaxConsecutiveOnes = function(nums) {
let maxCount = 0;
let currentCount = 0;
for (const num of nums) {
if (num === 1) {
currentCount++;
maxCount = Math.max(maxCount, currentCount);
} else {
currentCount = 0;
}
}
return maxCount;
};
Time Complexity: O(n)
Where n is the length of the input array.
Space Complexity: O(1)
Only constant extra space is used.
C# Solution
public class Solution {
public int FindMaxConsecutiveOnes(int[] nums) {
int maxCount = 0;
int currentCount = 0;
foreach (int num in nums) {
if (num == 1) {
currentCount++;
maxCount = Math.Max(maxCount, currentCount);
} else {
currentCount = 0;
}
}
return maxCount;
}
}
Time Complexity: O(n)
Where n is the length of the input array.
Space Complexity: O(1)
Only constant extra space is used.
Approach Explanation
The solution uses a single pass counting approach:
- Key Insights:
- Counter tracking
- Maximum tracking
- Reset condition
- Single pass
- Algorithm Steps:
- Initialize counters
- Iterate array
- Update counts
- Track maximum
Implementation Details:
- Counter variables
- Linear traversal
- Maximum update
- Reset logic
Optimization Insights:
- Single pass
- Constant space
- No extra storage
- Direct counting
Edge Cases:
- Empty array
- All zeros
- All ones
- Single element