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).

Input & Output

Example 1 — Basic Unsorted Array
$ Input: nums = [3,4,2,1]
Output: 2
💡 Note: First merge (2,1)→3 giving [3,4,3], then merge (3,4)→7 giving [7,3]. Finally merge (7,3)→10 giving [10] (sorted). Total: 3 operations. Wait, let me recalculate: [3,4,2,1] → merge (2,1) → [3,4,3] → merge (3,3) → [3,7] (sorted). Total: 2 operations.
Example 2 — Already Sorted
$ Input: nums = [1,2,3,4]
Output: 0
💡 Note: Array is already non-decreasing (1≤2≤3≤4), so no operations needed.
Example 3 — Single Element
$ Input: nums = [5]
Output: 0
💡 Note: Single element array is trivially non-decreasing, no operations needed.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Minimum Pair Removal to Sort ArrayInput:3421Step 1:343Merge (2,1)→3Step 2:10Merge (3,4)→7, then (7,3)→10Output: 2 operations needed
Understanding the Visualization
1
Input
Unsorted array [3,4,2,1] needs to become non-decreasing
2
Process
Repeatedly merge adjacent pairs with minimum sum
3
Output
Count of operations needed to sort array
Key Takeaway
🎯 Key Insight: Always merge the adjacent pair with smallest sum to minimize total operations
Asked in
Google 25 Microsoft 18 Amazon 15
23.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen