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 count
if (nums[right] == 0) {
zeroCount++;
}
// If the number of zeros exceeds k, move the left pointer forward
while (zeroCount > k) {
if (nums[left] == 0) {
zeroCount--;
}
left++;
}
// Update the maximum length
maxLen = (right - left + 1 > maxLen) ? right - left + 1 : maxLen;
}
return maxLen;
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!