Find Max Consecutive Ones
Problem Link:
Problem Statement:
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.
Approach:? We maintain a variable count that keeps a track of the number of consecutive 1’s while traversing the array. The other variable max_count maintains the maximum number of 1’s, in other words, it maintains the answer.
We start traversing from the beginning of the array. Since we can encounter either a 1 or 0 there can be two situations:-
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int min=0;
int maxi=0;
for (int num : nums) {
if (num == 1) {
min++;
} else {
min = 0;
}
maxi= Math.max(min, maxi);
}
return maxi;
}
}
Mobile ApplicationDeveloper | Flutter Developer | Dart
3 个月Great ??