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

     

  • 相关阅读:
    HTTP状态码及其含义
    c和python解决各种字符串反转问题的不同思路
    Python找出一串字符中出现最多的字符
    3个基本算法的实现技巧
    一种字符串搜索方法
    数据库开发经典总结
    apt、dpkg参数整理
    Python集合(set)类型的操作
    Python和Decorator(装饰器)模式
    Git使用基础
  • 原文地址:https://www.cnblogs.com/anghostcici/p/6656893.html
Copyright © 2011-2022 走看看