Longest Non-Decreasing Subarray After Replacing at Most One Element Problem
Description
LeetCode Problem 3738.
You are given an integer array nums.
You are allowed to replace at most one element in the array with any other integer value of your choice.
Return the length of the longest non-decreasing subarray that can be obtained after performing at most one replacement.
An array is said to be non-decreasing if each element is greater than or equal to its previous one (if it exists).
Example 1:
Input: nums = [1,2,3,1,2]
Output: 4
Explanation:
Replacing nums[3] = 1 with 3 gives the array [1, 2, 3, 3, 2].
The longest non-decreasing subarray is [1, 2, 3, 3], which has a length of 4.
Example 2:
Input: nums = [2,2,2,2,2]
Output: 5
Explanation:
All elements in nums are equal, so it is already non-decreasing and the entire nums forms a subarray of length 5.
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Prefix and suffix runs
Let left[i] be the length of the longest non-decreasing run ending at i, and right[i] the length of the longest one starting at i. Both come from one pass each.
Without any replacement the answer is the largest left[i]. If we replace nums[i], the run can use left[i-1] elements before it and right[i+1] after it:
- If
nums[i-1] <= nums[i+1](oriis at an end), we can pick a value fornums[i]that joins both sides, givingleft[i-1] + right[i+1] + 1. - Otherwise the two sides cannot be joined, so we keep the longer one:
max(left[i-1], right[i+1]) + 1.
The answer is the maximum over all i.
Complexity: time O(n), space O(n).
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
n = len(nums)
left = [1] * n
right = [1] * n
for i in range(1, n):
if nums[i] >= nums[i - 1]:
left[i] = left[i - 1] + 1
for i in range(n - 2, -1, -1):
if nums[i] <= nums[i + 1]:
right[i] = right[i + 1] + 1
ans = max(left)
for i in range(n):
a = 0 if i - 1 < 0 else left[i - 1]
b = 0 if i + 1 >= n else right[i + 1]
if i - 1 >= 0 and i + 1 < n and nums[i - 1] > nums[i + 1]:
ans = max(ans, a + 1, b + 1)
else:
ans = max(ans, a + b + 1)
return ans