返回介绍

solution / 0400-0499 / 0485.Max Consecutive Ones / README_EN

发布于 2024-06-17 01:04:00 字数 3745 浏览 0 评论 0 收藏 0

485. Max Consecutive Ones

中文文档

Description

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 either 0 or 1.

Solutions

Solution 1

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)
}
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)
  }
}
/**
 * @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);
};
class Solution {
  /**
   * @param Integer[] $nums
   * @return Integer
   */
  function findMaxConsecutiveOnes($nums) {
    $tmp = $max = 0;
    for ($i = 0; $i < count($nums); $i++) {
      if ($nums[$i] == 1) {
        $tmp++;
      } else {
        $max = max($tmp, $max);
        $tmp = 0;
      }
    }
    return max($tmp, $max);
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文