Leetcode - Max Consecutive Ones II
Leetcode - Longest Repeating Character Replacement

Leetcode - Max Consecutive Ones III

violet posted @ Apr 06, 2020 04:31:20 AM in 算法 with tags Algorithm Golang array , 191 阅读

https://leetcode.com/problems/max-consecutive-ones-iii/

Given an array A of 0s and 1s, we may change up to K values from 0 to 1.

Return the length of the longest (contiguous) subarray that contains only 1s. 

 

Example 1:

Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation: 
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.

 

func longestOnes(A []int, K int) int {
    maxNum := 0
    zero := 0
    left := 0
    right := 0
    for right < len(A) {
        if A[right] == 0 {
            zero++
        }
        for zero > K {
            if A[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