Longest Alternating Subarray After Removing At Most One Element Problem
Description
LeetCode Problem 3830.
You are given an integer array nums.
A subarray nums[l..r] is alternating if one of the following holds:
nums[l] < nums[l + 1] > nums[l + 2] < nums[l + 3] > ...nums[l] > nums[l + 1] < nums[l + 2] > nums[l + 3] < ...
In other words, if we compare adjacent elements in the subarray, then the comparisons alternate between strictly greater and strictly smaller.
You can remove at most one element from nums. Then, you select an alternating subarray from nums.
Return an integer denoting the maximum length of the alternating subarray you can select.
A subarray of length 1 is considered alternating.
Example 1:
Input: nums = [2,1,3,2]
Output: 4
Explanation:
- Choose not to remove elements.
- Select the entire array [2, 1, 3, 2], which is alternating because 2 > 1 < 3 > 2.
Example 2:
Input: nums = [3,2,1,2,3,2,1]
Output: 4
Explanation:
- Choose to remove nums[3] i.e., [3, 2, 1, 2, 3, 2, 1]. The array becomes [3, 2, 1, 3, 2, 1].
- Select the subarray [3, 2, 1, 3, 2, 1].
Example 3:
Input: nums = [100000,100000]
Output: 1
Explanation:
- Choose not to remove elements.
- Select the subarray [100000, 100000].
Constraints:
2 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Prefix-Suffix Decomposition + Enumeration
Define four arrays. l1[i] and l2[i] are the lengths of the longest alternating subarray that ends at i and whose last comparison is < and > respectively. r1[i] and r2[i] are the lengths of the longest alternating subarray that starts at i and whose first comparison is < and > respectively. One left-to-right pass fills l1 and l2, and one right-to-left pass fills r1 and r2.
Without removing anything, the answer is the largest value in l1 and l2.
Then try removing each position i. After the removal, i - 1 and i + 1 become neighbors. If nums[i - 1] < nums[i + 1], the left part must end with > and the right part must start with >, so the candidate is l2[i - 1] + r2[i + 1]. If nums[i - 1] > nums[i + 1], the candidate is l1[i - 1] + r1[i + 1]. If they are equal, the two parts cannot be joined. Take the maximum over all candidates.
Complexity:
- Time:
O(n). - Space:
O(n).
class Solution:
def longestAlternating(self, nums: List[int]) -> int:
n = len(nums)
l1 = [1] * n
l2 = [1] * n
r1 = [1] * n
r2 = [1] * n
ans = 0
for i in range(1, n):
if nums[i - 1] < nums[i]:
l1[i] = l2[i - 1] + 1
elif nums[i - 1] > nums[i]:
l2[i] = l1[i - 1] + 1
ans = max(ans, l1[i], l2[i])
for i in range(n - 2, -1, -1):
if nums[i + 1] > nums[i]:
r1[i] = r2[i + 1] + 1
elif nums[i + 1] < nums[i]:
r2[i] = r1[i + 1] + 1
for i in range(1, n - 1):
if nums[i - 1] < nums[i + 1]:
ans = max(ans, l2[i - 1] + r2[i + 1])
elif nums[i - 1] > nums[i + 1]:
ans = max(ans, l1[i - 1] + r1[i + 1])
return ans