#3830

Longest Alternating Subarray After Removing At Most One Element

Hard
ArrayDynamic ProgrammingEnumerationDynamic ProgrammingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use dynamic programming to track lengths of alternating subarrays from both ends, allowing for one removal.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create two arrays, left and right, to store lengths of alternating sequences ending and starting at each index.
  2. 2Step 2: Fill the left array from left to right and the right array from right to left.
  3. 3Step 3: Calculate the maximum length considering one removal by checking adjacent elements.
solution.py19 lines
1def longestAlternating(nums):
2    n = len(nums)
3    left = [1] * n
4    right = [1] * n
5    for i in range(1, n):
6        if (nums[i - 1] < nums[i]):
7            left[i] = left[i - 1] + 1
8        elif (nums[i - 1] > nums[i]):
9            left[i] = left[i - 1] + 1
10    for i in range(n - 2, -1, -1):
11        if (nums[i] < nums[i + 1]):
12            right[i] = right[i + 1] + 1
13        elif (nums[i] > nums[i + 1]):
14            right[i] = right[i + 1] + 1
15    max_len = max(left)
16    for i in range(1, n - 1):
17        if (nums[i - 1] < nums[i + 1]):
18            max_len = max(max_len, left[i - 1] + right[i + 1])
19    return max_len

Complexity note: Filling the left and right arrays takes linear time, leading to O(n) complexity.

  • 1Identifying alternating patterns is crucial.
  • 2Removing one element can bridge two alternating sequences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.