Minimum Pair Removal to Sort Array I

Given an array nums, you can perform the following operation any number of times:

  • Select the adjacent pair with the minimum sum in nums. If multiple such pairs exist, choose the leftmost one.
  • Replace the pair with their sum.

Return the minimum number of operations needed to make the array non-decreasing.

An array is said to be non-decreasing if each element is greater than or equal to its previous element, if it exists.

Example 1
Inputnums = [5,2,3,1]
Output2
The pair (3, 1) is replaced first, then (2, 4) is replaced, making nums = [5, 6] non-decreasing after two operations.
Example 2
Inputnums = [1,2,2]
Output0
The array nums is already sorted.

Constraints

  • 1 <= nums.length <= 50
  • -1000 <= nums[i] <= 1000

Asked at 5 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