Leetcode 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.

import java.util.HashMap;

/**
 * Longest Subarray with Ones after Replacement
 *
 * @author gaoqiuqi on 4/7/22
 * @date 4/7/22 16:25
 */
public class LongestSubarrayWithOnesAfterReplacement {

    public static Integer longestSubarrayWithOnesAfterReplacement(int[] nums, int k){

        int start = 0, end = 0;
        int maxLength = 0;
        int count = 0;
        int TARGET_VALUE = 1;
        for( end = 0; end < nums.length; end++ ){
            if(nums[end] == TARGET_VALUE){
                // 统计目标值出现次数
                // 目标值已知,直接统计频率
                count++;
            }
                //shrink the window from the left

            if(end - start + 1 - count > k){
                if(nums[start] == TARGET_VALUE){
                    count --;
                }
                start ++;

            }
            maxLength = Math.max(end - start + 1, maxLength);

        }
        return maxLength;
    }


    public static void main(String[] args) {
        int[] input = {1,1,1,0,0,0,1,1,1,1,0};
        int k = 2;
        Integer res = longestSubarrayWithOnesAfterReplacement(input, k);
        System.out.println(res);
    }
}

Time Complexity: O(N)

Space Complexity: O(1)

转载请注明出处:http://www.fuqingkongyaji.com/article/20230526/851904.html