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

 

 

posted @ 2017-04-01 17:27  anghostcici  阅读(104)  评论(0编辑  收藏  举报