Max Consecutive Ones

easy array

Problem

Given a binary array nums, return the maximum number of consecutive 1s in the array.

Inputnums = [1, 1, 0, 1, 1, 1]
Output3
The longest run of 1s is at the tail.

def find_max_consecutive_ones(nums):
    best = run = 0
    for x in nums:
        run = run + 1 if x == 1 else 0
        if run > best: best = run
    return best
function findMaxConsecutiveOnes(nums) {
  let best = 0, run = 0;
  for (const x of nums) {
    run = x === 1 ? run + 1 : 0;
    if (run > best) best = run;
  }
  return best;
}
class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int best = 0, run = 0;
        for (int x : nums) {
            run = x == 1 ? run + 1 : 0;
            if (run > best) best = run;
        }
        return best;
    }
}
int findMaxConsecutiveOnes(vector<int>& nums) {
    int best = 0, run = 0;
    for (int x : nums) {
        run = x == 1 ? run + 1 : 0;
        if (run > best) best = run;
    }
    return best;
}
Time: O(n) Space: O(1)