Problem Statement
This problem is from Leetcode – Max Consecutive Ones. The problem statement is as below:
Given a binary array nums, return the length of the longest run of consecutive 1's in the array.
Solution
Initialize variables
max– It keeps track of maximum number of consecutive 1’s in the array. This is our answer.count– It keep track of number of consecutive 1s until a 0 is encountered.
Iterate Though the Array
- If 1 is encountered, increment
count. - If 0 is encountered, reset
count. - If
maxis less thancount, then updatemax.
public int findMaxConsecutiveOnes(int[] nums) {
int max = 0;
int count = 0;
for(int i=0; i<nums.length; i++) {
// keep count of consecutive 1s
if(nums[i] == 1) {
count = count+1;
}
// reset count if 0 is encountered
if(nums[i] == 0) {
count = 0;
}
// update max
max = Math.max(max, count);
}
return max;
}
You can checkout the code from Github here: Max Consecutive Ones. See the performance of this approach below:
PERFORMANCE ANALYSIS:
| RUNTIME | 4 ms | Beats 49.10 % |
| MEMORY | 49.63 MB | Beats 93.71 % |
| TIME COMPLEXITY | O (N) |