#3738
Longest Non-Decreasing Subarray After Replacing at Most One Element
MediumArrayDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can use two pointers to find the longest non-decreasing subarray while allowing one replacement. This approach efficiently checks the conditions without redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Create two arrays, prefix and suffix, to store the lengths of non-decreasing subarrays ending and starting at each index.
- 2Step 2: Iterate through the array to fill the prefix and suffix arrays.
- 3Step 3: Calculate the maximum length by checking the combination of prefix and suffix lengths around each index.
solution.py14 lines
1def longestNonDecreasing(nums):
2 n = len(nums)
3 if n == 1: return 1
4 prefix = [1] * n
5 suffix = [1] * n
6 for i in range(1, n):
7 if nums[i] >= nums[i - 1]: prefix[i] = prefix[i - 1] + 1
8 for i in range(n - 2, -1, -1):
9 if nums[i] <= nums[i + 1]: suffix[i] = suffix[i + 1] + 1
10 max_length = max(prefix)
11 for i in range(1, n - 1):
12 if nums[i - 1] <= nums[i + 1]:
13 max_length = max(max_length, prefix[i - 1] + suffix[i + 1])
14 return max_lengthℹ
Complexity note: This solution runs in linear time due to single passes for prefix and suffix arrays, leading to efficient performance.
- 1Replacing an element can connect two non-decreasing segments.
- 2Maintaining prefix and suffix arrays allows efficient length calculation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.