485. Max Consecutive Ones

Description

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

因为只包含0和1,可以利用sum来统计个数。

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int maxOnes = 0;
        int sum = 0;
        
        for (int n : nums) {
            if (n == 0) {
                maxOnes = Math.max(maxOnes, sum);
                sum = 0;    // reset sum to 0
            } else {
                ++sum;
            }
        }
        
        maxOnes = Math.max(maxOnes, sum);
        return maxOnes;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 11.08 06:06
    Phmiracle阅读 201评论 0 0
  • 第49周,也就是还有四周,一年就又要过去了。怕了。真舍不得。最后一周的时候翻一翻,这一年变化挺多的。看起来是迈了台...
    筱筱殿下阅读 221评论 0 0
  • 姓名:徐祖德 公司:广东思沃精密机械有限公司 230期_利他1组 272期_乐观2组志工 【日精进打卡第168天】...
    徐祖德阅读 72评论 0 0
  • 翟笃安阅读 125评论 0 0