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 mostk0'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.
// windows sum的publicintlongestOnes(int[] nums,int k) {if (nums ==null||nums.length==0|| k <0) {return0; }int max =0;int left =0;int sum =0;for (int right =0; right <nums.length; right++) { sum = sum + nums[right];int diff = right - left +1- sum;if (diff <= k) { max =Math.max(max, right - left +1);continue; } // if or while都okif (diff > k && left < right) { sum = sum - nums[left]; left++; diff = right - left +1- sum; } }return max;}// prefix sum的publicintlongestOnes(int[] nums,int k) {if (nums ==null||nums.length==0|| k <0) {return0; }// calculate prefixSumint[] prefixSum =newint[nums.length+1];for (int i =1; i <nums.length+1; i++) { prefixSum[i] = prefixSum[i -1] + nums[i -1]; }// sliding windows on prefixSumint max =0;int left =0;for (int right =1; right <nums.length+1; right++) {int diff = right - left - (prefixSum[right] - prefixSum[left]);if (diff <= k) { max =Math.max(max, right - left);continue; } // if or while都okif (diff > k && left < right) { left++; diff = right - left - (prefixSum[right] - prefixSum[left]); } }return max;}