Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Max Consecutive Ones II

$
0
0

题目描述:

LeetCode 487. Max Consecutive Ones II

Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0.

Example 1:

Input: [1,0,1,1,0]Output: 4Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
    After flipping, the maximum number of consecutive 1s is 4.

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

题目大意:

给定一个二进制数组,如果允许将至多一个0翻转成1,求最大连续1的个数。

注意:

  • 输入数组只包含0和1
  • 数组长度是正整数并且不会超过10000

解题思路:

线性遍历+计数器

统计恰好相隔1个'0'的两个连续1子数组的最大长度之和

Python代码:

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == sum(nums): return sum(nums)
        a = b = c = 0
        for n in nums:
            if n == 1:
                c += 1
            else:
                b, c = c, 0
            a = max(a, b + c + 1)
        return a

 


Viewing all articles
Browse latest Browse all 559

Trending Articles