Leetcode - Max Consecutive Ones III
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 }