zoukankan      html  css  js  c++  java
  • 485. Max Consecutive Ones

    Given a binary array, find the maximum number of consecutive 1s in this array.

    Example 1:

    Input: [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.

     

    Note:

    • The input array will only contain 0 and 1.
    • The length of input array is a positive integer and will not exceed 10,000

     

     Solution 1: tranverse the array, use the counter cnt to sum the 1s: if the current number is 0, reset cnt=0; if the number is 1, cnt++. Then update the maximum number res.

     1 class Solution {
     2 public:
     3     int findMaxConsecutiveOnes(vector<int>& nums) {
     4         int max_cnt=0,cnt=0,size=nums.size();
     5         for (auto i:nums){
     6             if (i==1){
     7                 max_cnt=max(++cnt,max_cnt);
     8             }
     9             else cnt=0;
    10         }
    11         return max_cnt;
    12     }
    13 };

    Solution 2: calculate sum(line 6)

     1 class Solution {
     2 public:
     3     int findMaxConsecutiveOnes(vector<int>& nums) {
     4         int res = 0, sum = 0;
     5         for (int num : nums) {
     6             sum = (sum + num) * num;
     7             res = max(res, sum);
     8         }
     9         return res;
    10     }
    11 };

     

  • 相关阅读:
    LUA 协程
    LUA GC 简单测试
    软件重构-笔记
    托管执行过程
    文件夹 加密
    db 文件 查看 打开 工具 db 中文 版 navicat 中文
    qq sid qq sid 是什么 qq sid 怎么用
    windows系统,联系人文件。个性化。
    csdn 音乐 怎么拦截 提交后的程序 csdn 栏目 音乐 csdn 添加 音乐
    CSDN博客栏目设置个性化
  • 原文地址:https://www.cnblogs.com/anghostcici/p/6656893.html
Copyright © 2011-2022 走看看