LeetCode之Max Consecutive Ones

简介: LeetCode之Max Consecutive Ones

1、题目

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


2、代码实现

public class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        if (nums == null) {
            return 0;
        }
        int zero = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                ++zero;
            }
        }
        if (zero == nums.length) {
            return 0;
        }
        int count = 0;
        int maxValue = 0;
        int maxLength = 0;
        for (int i = 0; i < nums.length; ++i) {
            if (nums[i] > maxValue) {
                maxValue = nums[i];
            }
        }
        for (int i = 0; i < nums.length; ++i) {
            if (nums[i] == maxValue) {
                for (int j = i; j < nums.length; ++j) {
                    if (nums[j] == maxValue) {
                        count++;
                    } else {
                        break;
                    }
                }
                if (maxLength < count) {
                    maxLength = count;
                }
                count = 0;
            }
        }
        return maxLength;
    }
}


相关文章
|
算法
LeetCode 363. Max Sum of Rect No Larger Than K
给定一个非空二维矩阵 matrix 和一个整数 k,找到这个矩阵内部不大于 k 的最大矩形和。
77 0
LeetCode 363. Max Sum of Rect No Larger Than K
LeetCode 149. Max Points on a Line
给定一个二维平面,平面上有 n 个点,求最多有多少个点在同一条直线上。
79 0
LeetCode 149. Max Points on a Line
|
算法
LeetCode 128. Longest Consecutive Sequence
给定一个未排序的整数数组,找出最长连续序列的长度。 要求算法的时间复杂度为 O(n)。
66 0
LeetCode 128. Longest Consecutive Sequence
|
Java Python
LeetCode 485:连续最大1的个数 Max Consecutive Ones(python java)
公众号:爱写bug 给定一个二进制数组, 计算其中最大连续1的个数。 Given a binary array, find the maximum number of consecutive 1s in this array. 示例 1: 输入: [1,1,0,1,1,1] 输出: 3 解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3. 注意: 输入的数组只包含 0 和1。
827 0
|
Java
[LeetCode]Max Area of Island 岛屿的最大面积
链接:https://leetcode.com/problems/max-area-of-island/description/难度:Easy题目:695.
852 0
|
3天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
7 0
|
3天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
8 0