Leetcode - Move Zeroes
Leetcode - Max Consecutive Ones III

Leetcode - Max Consecutive Ones II

violet posted @ 5 年前 in 算法 with tags Algorithm Golang array , 323 阅读

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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