Longest Non-Decreasing Subarray After Replacing at Most One Element

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
Inputnums = [1,2,3,1,2]
Output4
Replacing nums[3] = 1 with 3 gives [1, 2, 3, 3, 2], whose longest non-decreasing subarray is [1, 2, 3, 3] of length 4.
Example 2
Inputnums = [2,2,2,2,2]
Output5
All elements in nums are equal, so the entire array is already non-decreasing and has length 5.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate