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 Case
$ Input: nums = [4,2,1,3,5]
Output: 3
💡 Note: Step 1: Min pair is (2,1) with sum 3 → [4,3,3,5]. Step 2: Min pair is (3,3) with sum 6 → [4,6,5]. Step 3: Min pair is (4,6) with sum 10 → [10,5]. Now 10 > 5, so we need 1 more: Step 4: Only pair (10,5) → [15]. Total: 3 operations.
Example 2 — Already Sorted
$ Input: nums = [1,2,3,4,5]
Output: 0
💡 Note: Array is already non-decreasing (1 ≤ 2 ≤ 3 ≤ 4 ≤ 5), so no operations needed.
Example 3 — Reverse Order
$ Input: nums = [5,4,3,2,1]
Output: 4
💡 Note: Always merge smallest adjacent sum: (2,1)→3: [5,4,3,3]. Then (3,3)→6: [5,4,6]. Then (4,6)→10: [5,10]. Then (5,10)→15: [15]. Total: 4 operations.

Constraints

  • 1 ≤ nums.length ≤ 103
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Minimum Pair Removal to Sort Array IIInput:42135Operation 1:4335Merge (2,1) → 3Operation 2:465Merge (3,3) → 6Operation 3:105Merge (4,6) → 10Result: 3 operations needed
Understanding the Visualization
1
Input
Unsorted array [4,2,1,3,5]
2
Process
Find minimum adjacent sum pairs and merge them
3
Output
Count of operations needed (3 operations)
Key Takeaway
🎯 Key Insight: Always merge the adjacent pair with minimum sum first to minimize total operations
Asked in
Google 15 Amazon 12 Microsoft 8
8.5K Views
Medium Frequency
~35 min Avg. Time
245 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