Given a binary array nums, return the maximum number of consecutive 1’s in the array.
1 <= nums.length <= 10^5nums[i] is either 0 or 1Use a sliding window approach with two counters:
freq - tracks the current count of consecutive 1’scount - tracks the maximum count seen so farFor each element in the array:
1, increment freq0, reset freq to 0count with the maximum of count and freqThis approach works because we only need to track the current streak of consecutive 1’s and the maximum streak encountered. When we encounter a 0, the current streak breaks and we start counting from 0 again.
Example Input: nums = [1,1,0,1,1,1]
Step-by-step execution:
Final Answer = 3
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count=0;
int freq=0;
for(int i=0; i<nums.length; i++){
if(nums[i]==1) freq++;
else freq=0;
count=Math.max(count, freq);
}
return count;
}
}