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;
}

你可能感兴趣的:(LeetCode,leetcode,c语言,算法)