MaxConsecutiveOnes

来源:互联网 发布:一维数组杨辉三角java 编辑:程序博客网 时间:2024/05/20 22:04

问题描述:

0和1组成的数组,求出最大的连续为1的长度


解决:

一眼看出这是动态规划,时间复杂度o(n)。类似的题目maximum subarray,也是用的动态规划,意思差不多。


/* * Given a binary array, find the maximum number of consecutive 1s in this array.Example 1:Input: [1,1,0,1,1,1]Output: 3Explanation: 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 * */public class MaxConsecutiveOnes {    public int findMaxConsecutiveOnes(int[] nums) {        int local = 0;        int global = 0;        for(int i=0; i<nums.length; i++) {        local = nums[i] == 0?0:local+1;        global = Math.max(global, local);        }        return global;    }}




原创粉丝点击