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

     

  • 相关阅读:
    JavaScript变量存储浅析
    AngularJS学习篇(二十二)
    css目录
    html目录
    javascript目录
    第一篇 dom
    第五篇、css补充二
    第六篇 javascript面向对象
    第三篇 css属性
    jmeter之-图形监控
  • 原文地址:https://www.cnblogs.com/anghostcici/p/6656893.html
Copyright © 2011-2022 走看看