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: 4
💡 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]. Step 4: Only pair (10,5) with sum 15 → [15]. Total: 4 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 II INPUT Initial Array: nums 4 i=0 2 i=1 1 i=2 3 i=3 5 i=4 Adjacent Pair Sums: 4+2=6 2+1=3 MIN 1+3=4 3+5=8 Goal: Make array non-decreasing using minimum operations Array NOT sorted (4 > 2 > 1) ALGORITHM STEPS 1 Find min sum pair (2,1)=3 [4,2,1,3,5] --> [4,3,3,5] 2 Find min sum pair (3,3)=6 [4,3,3,5] --> [4,6,5] 3 Find min sum pair (4,6)=10 [4,6,5] --> [10,5] 4 Check: Not sorted (10>5) [10,5] --> [15] (sorted!) Simulation Tracking Op 1: [4,2,1,3,5] min=3 Op 2: [4,3,3,5] min=6 Op 3: [4,6,5] min=10 Done: [10,5] min=15 Result: [15] SORTED Total: 3 operations FINAL RESULT Final Sorted Array: [15] Minimum Operations: 3 OK - Verified! - Array is non-decreasing - 3 merge operations used - Minimum possible count Key Insight: The greedy approach works: always merge the adjacent pair with minimum sum first. Track pairs efficiently using a data structure (heap/sorted set) to find minimum sum in O(log n). When multiple pairs have same minimum sum, choose the leftmost one to maintain consistency. TutorialsPoint - Minimum Pair Removal to Sort Array II | Simulation with Tracking
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