Leetcode - Move Zeroes
Leetcode - Max Consecutive Ones III

Leetcode - Max Consecutive Ones II

violet posted @ Apr 06, 2020 04:22:49 AM in 算法 with tags Algorithm Golang array , 302 阅读

https://leetcode.com/problems/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: 4
Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
    After flipping, the maximum number of consecutive 1s is 4.

 

This problem can be finding minimal 0 in a sliding window. Setting a sliding window and then counting number of 0.

func findMaxConsecutiveOnes(nums []int) int {
    maxNum := 0
    zero := 0
    left := 0
    right := 0
    for right < len(nums) {
        if nums[right] == 0 {
            zero++
        }
        for zero > 1 && left < right {
            if nums[left] == 0 {
                zero--
            }
            left++
        }
        maxNum = max(maxNum, right - left + 1)
        right++
    }
    
    return maxNum
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter