本文主要是介绍LeetCode //C - 1004. Max Consecutive Ones III,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1004. Max Consecutive Ones III
Given a binary array nums and an integer k, return the maximum number of consecutive 1’s in the array if you can flip at most k 0’s.
Example 1:
Input: nums = [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.
Example 2:
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Constraints:
- 1 < = n u m s . l e n g t h < = 1 0 5 1 <= nums.length <= 10^5 1<=nums.length<=105
- nums[i] is either 0 or 1.
- 0 <= k <= nums.length
From: LeetCode
Link: 1004. Max Consecutive Ones III
Solution:
Ideas:
To solve the “Max Consecutive Ones III” problem in C, you’ll need to implement a function that uses the sliding window technique. The idea is to maintain a window that can include at most k zeros. As you traverse the array, you expand the window to the right by including ones and flipping zeros (up to k times). If you encounter more than k zeros, you shrink the window from the left until the number of zeros in the window is k again. The maximum size of this window at any point gives you the maximum number of consecutive ones after flipping at most k zeros.
Code:
int longestOnes(int* nums, int numsSize, int k) {int left = 0, right = 0;int maxLen = 0;int zeroCount = 0;for (right = 0; right < numsSize; right++) {// If the current element is 0, increment the zero countif (nums[right] == 0) {zeroCount++;}// If the number of zeros exceeds k, move the left pointer forwardwhile (zeroCount > k) {if (nums[left] == 0) {zeroCount--;}left++;}// Update the maximum lengthmaxLen = (right - left + 1 > maxLen) ? right - left + 1 : maxLen;}return maxLen;
}
这篇关于LeetCode //C - 1004. Max Consecutive Ones III的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!