Input: nums =[1,1,0,1,1,1]Output: 3Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is3.
We want to find the longest sequence of consecutive 1s in the array. By scanning the array once and counting the current streak of 1s, we can keep track of the maximum streak found so far.
classSolution {
public:int findMaxConsecutiveOnes(vector<int>& nums) {
int ans =0, cnt =0;
for (int x : nums) {
if (x ==1) cnt++;
else cnt =0;
ans = max(ans, cnt);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
funcfindMaxConsecutiveOnes(nums []int) int {
ans, cnt:=0, 0for_, x:=rangenums {
ifx==1 {
cnt++ifcnt > ans {
ans = cnt }
} else {
cnt = 0 }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintfindMaxConsecutiveOnes(int[] nums) {
int ans = 0, cnt = 0;
for (int x : nums) {
if (x == 1) cnt++;
else cnt = 0;
ans = Math.max(ans, cnt);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funfindMaxConsecutiveOnes(nums: IntArray): Int {
var ans = 0var cnt = 0for (x in nums) {
if (x ==1) cnt++else cnt = 0 ans = maxOf(ans, cnt)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
deffindMaxConsecutiveOnes(self, nums: list[int]) -> int:
ans = cnt =0for x in nums:
if x ==1:
cnt +=1 ans = max(ans, cnt)
else:
cnt =0return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnfind_max_consecutive_ones(nums: Vec<i32>) -> i32 {
letmut ans =0;
letmut cnt =0;
for x in nums {
if x ==1 {
cnt +=1;
if cnt > ans {
ans = cnt;
}
} else {
cnt =0;
}
}
ans
}
}