Given a binary array nums
, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1
's in the resulting array. Return 0
if there is no such subarray.
Example 1:
Input: nums = [1,1,0,1] Output: 3 Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
Example 2:
Input: nums = [0,1,1,1,0,1,1,0,1] Output: 5 Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
Example 3:
Input: nums = [1,1,1] Output: 2 Explanation: You must delete one element.
Constraints:
1 <= nums.length <= 105
nums[i]
is either0
or1
.
Companies: Yandex
Related Topics:
Array, Dynamic Programming, Sliding Window
prev2
and prev
are the indexes of the non-one values we've seen most recently during scanning.
prev2 prev i
0 1 1 1 0 1 1 1 0
If the array only contains 1, then return N - 1
.
Otherwise, the answer is the maximum of i - prev2 - 2
.
// OJ: https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int longestSubarray(vector<int>& A) {
int N = A.size(), prev2 = -1, prev = -1, ans = 0;
for (int i = 0; i <= N; ++i) {
if (i < N && A[i] == 1) continue;
if (i == N && prev == -1) return N - 1;
if (prev != -1) ans = max(ans, i - prev2 - 2);
prev2 = prev;
prev = i;
}
return ans;
}
};
Check out "C++ Maximum Sliding Window Cheatsheet Template!"
Shrinkable Sliding Window:
// OJ: https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int longestSubarray(vector<int>& A) {
int i = 0, j = 0, N = A.size(), cnt = 0, ans = 0;
for (; j < N; ++j) {
cnt += A[j] == 0;
while (cnt > 1) cnt -= A[i++] == 0;
ans = max(ans, j - i);
}
return ans;
}
};
Non-shrinkable Sliding Window:
// OJ: https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int longestSubarray(vector<int>& A) {
int i = 0, j = 0, N = A.size(), cnt = 0;
for (; j < N; ++j) {
cnt += A[j] == 0;
if (cnt > 1) cnt -= A[i++] == 0;
}
return j - i - 1;
}
};