5

LeetCode-1004-最大连续1的个数III

 2 years ago
source link: https://blog.kuangjux.top/2021/02/19/LeetCode-1004/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
KuangjuX(狂且)

LeetCode-1004-最大连续1的个数III

Created2021-02-19|Updated2021-02-20|技术
Post View:4

Description:

给定一个由若干 01 组成的数组 A,我们最多可以将 K 个值从 0 变成 1 。

返回仅包含 1 的最长(连续)子数组的长度。

Examples:

输入:A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
输出:6
解释:
[1,1,1,0,0,1,1,1,1,1,1]
粗体数字从 0 翻转到 1,最长的子数组长度为 6。
输入:A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
输出:10
解释:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
粗体数字从 0 翻转到 1,最长的子数组长度为 10。

Solution:

func longestOnes(A []int, K int) int {
size := len(A)
left, right := 0, 0
res, sum := 0, 0
for right < size {
sum += A[right] ^ 1
for sum > K {
sum -= (A[left] ^ 1)
left += 1
}

res = max(res, right-left+1)
right += 1
}
return res
}

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK