[LeetCode] 1004. Max Consecutive Ones III Maximum number of consecutive 1s III (Medium) (JAVA)
Subject address: https://leetcode.com/problems/max-consecutive-ones-iii/
Title description:
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [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: A = [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.
Note:
- 1 <= A.length <= 20000
- 0 <= K <= A.length
- A[i] is 0 or 1
General idea
Given an array A consisting of several 0s and 1, we can change up to K values from 0 to 1.
Returns the length of the longest (contiguous) sub-array containing only 1.
Problem-solving method
- Use the prefix and P(i) to denote the sum of the first i elements of [0, i].
- P(right)-P(left) represents the sum in the interval of [left, right], (right-left + 1)-(P(right)-P(left)) represents the number of 0 in the interval
- As long as the number of 0s in the interval is less than or equal to K, this interval is a continuous sub-array
- So adopt the idea of sliding window, keep finding left and right, and then calculate the length of the window
class Solution {
public int longestOnes(int[] A, int K) {
int left = 0;
int right = 0;
int lSum = 0;
int rSum = 0;
int res = 0;
for (right = 0; right < A.length; right++) {
rSum += 1 - A[right];
while (rSum - lSum > K) {
lSum += 1 - A[left];
left++;
}
res = Math.max(res, right - left + 1);
}
return res;
}
}
Execution time: 4 ms, defeating 47.01% of Java users
Memory consumption: 40 MB, defeating 11.37% of Java users