Max Consecutive Ones LeetCode
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Input 1: nums = [1,1,0,1,1,1]
Output 1: 3
Explanation 1: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Input 2: nums = [1,0,1,1,0,1]
Output 2: 2
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int maxCount = 0;
int currentCount = 0;
for (int num : nums) {
if (num == 1) {
currentCount++; // Keep counting 1s
maxCount = Math.max(maxCount, currentCount); // Update max
} else {
currentCount = 0; // Reset count on 0
}
}
return maxCount;
}
}
💡 Time Complexity:
O(n) → where
n
is the length of the array
💡 Space Complexity:
O(1) → no extra space used
🔍 Key Idea:
Keep a
currentCount
of consecutive 1sWhen you hit
0
, resetcurrentCount
to 0Always update
maxCount
ifcurrentCount
is higher
Comments
Post a Comment