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 };

     

  • 相关阅读:
    Mysql mysql lost connection to server during query 问题解决方法
    【转】程序员必须知道的几个Git代码托管平台
    FIFO存储器
    JUCE_FIFO实现分析
    【转】HashMap实现原理分析
    【转】int && 非常量右值
    【API】注册表编程基础-RegCreateKeyEx、RegSetValueEx
    【API】文件操作编程基础-CreateFile、WriteFile、SetFilePointer
    【逆向知识】裸函数(Naked函数)
    【逆向知识】堆栈图-汇编中的函数
  • 原文地址:https://www.cnblogs.com/anghostcici/p/6656893.html
Copyright © 2011-2022 走看看