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: 3
💡 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.
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 Array I INPUT nums = [3, 4, 2, 1] 3 idx 0 4 idx 1 2 idx 2 1 idx 3 Adjacent Pair Sums: 3+4 = 7 4+2 = 6 2+1 = 3 MIN Goal: Make array non-decreasing (each element >= previous) ALGORITHM STEPS 1 Find Min Sum Pair [3,4,2,1] --> 2+1=3 (min) 2 Replace with Sum [3,4,2,1] --> [3,4,3] Operation count: 1 3 4 3 (2+1) 3 Repeat: Find Min [3,4,3] --> 3+4=7, 4+3=7 Leftmost: 3+4=7 4 Replace Again [3,4,3] --> [7,3] Still not sorted! --> [10] [7,3]-->[10] (1 more op) FINAL RESULT Simulation Trace: Start: 3 4 2 1 Op 1: 3 4 3 Op 2: 7 3 OUTPUT 2 Minimum operations: 2 [3,4,2,1] --> [7,3] --> [10] Array is now non-decreasing - OK Key Insight: The optimized simulation repeatedly finds the minimum adjacent pair sum and merges them. When multiple pairs have equal minimum sum, choose the leftmost one. Continue until array is sorted. TutorialsPoint - Minimum Pair Removal to Sort Array I | Optimized Simulation Approach
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