LeetCode algorithm_C++ - Maximum number of consecutive 1's III

Given a binary array nums and an integer k, if at most k 0's can be flipped, return the maximum number of consecutive 1's in the array.

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]
The bold numbers flip from 0 to 1, and the longest subarray length is 6.

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]
Bold numbers flipped from 0 to 1, the longest subarray length is 10.

    int longestOnes(vector<int>& nums, int k) {
    
    
        int left = 0 , right = 0;
        int len = 0, maxi = 0;
        int n = nums.size();
        for (right = 0 ; right < n ; ++right){
    
    
            if (nums[right] == 0){
    
    
                if (k > 0) {
    
    
                    k--;
                    len++;
                    maxi = max(len, maxi);
                } else{
    
    
                    while (nums[left] == 1) {
    
    left++;len--;}
                    left++;
                }
            } else {
    
    
                len++;
                maxi = max(maxi, len);
            }
        }
        return maxi;
    }

Guess you like

Origin blog.csdn.net/weixin_43945471/article/details/132724067