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.
Example 2:
Input: nums = [1,0,1,1,0,1] Output: 2
Constraints:
1 <= nums.length <= 105
nums[i]
is either0
or1
.
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
cnt = ans = 0
for v in nums:
if v == 1:
cnt += 1
else:
ans = max(ans, cnt)
cnt = 0
return max(ans, cnt)
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int cnt = 0, ans = 0;
for (int v : nums) {
if (v == 1) {
++cnt;
} else {
ans = Math.max(ans, cnt);
cnt = 0;
}
}
return Math.max(cnt, ans);
}
}
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int cnt = 0, ans = 0;
for (int v : nums) {
if (v == 1) {
++cnt;
} else {
ans = max(ans, cnt);
cnt = 0;
}
}
return max(ans, cnt);
}
};
func findMaxConsecutiveOnes(nums []int) int {
ans, cnt := 0, 0
for _, v := range nums {
if v == 1 {
cnt++
} else {
ans = max(ans, cnt)
cnt = 0
}
}
return max(ans, cnt)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
/**
* @param {number[]} nums
* @return {number}
*/
var findMaxConsecutiveOnes = function (nums) {
let res = 0,
t = 0;
for (let num of nums) {
if (num == 1) {
++t;
} else {
res = Math.max(res, t);
t = 0;
}
}
return Math.max(res, t);
};
function findMaxConsecutiveOnes(nums: number[]): number {
let res = 0;
let count = 0;
for (const num of nums) {
if (num === 0) {
res = Math.max(res, count);
count = 0;
} else {
count++;
}
}
return Math.max(res, count);
}
impl Solution {
pub fn find_max_consecutive_ones(nums: Vec<i32>) -> i32 {
let mut res = 0;
let mut count = 0;
for num in nums {
if num == 0 {
res = res.max(count);
count = 0;
} else {
count += 1;
}
}
res.max(count)
}
}