Minimum Replacements to Sort the Array - Problem

You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it.

For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7].

Return the minimum number of operations to make an array that is sorted in non-decreasing order.

Input & Output

Example 1 — Basic Split Case
$ Input: nums = [3,9,4]
Output: 2
💡 Note: 9 > 4, so we need to split 9. Optimal split: 9 → 3+3+3 (2 operations). Array becomes [3,3,3,3,4] which is sorted.
Example 2 — Already Sorted
$ Input: nums = [1,2,3,4,5]
Output: 0
💡 Note: Array is already in non-decreasing order, no operations needed.
Example 3 — Multiple Splits
$ Input: nums = [2,10,20]
Output: 6
💡 Note: 20→5+5+5+5 (3 ops), then 10→3+3+4 (2 ops), then 2→1+1 (1 op). Total: 6 operations.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Replacements to Sort ArrayInput Array3949 > 4 ✗Split 9 → 3+3+3 (2 operations)Final Sorted Array33334Sorted! ✓
Understanding the Visualization
1
Input
Unsorted array [3,9,4] where 9 > 4 violates order
2
Process
Split 9 into 3 equal parts: 3+3+3 (2 operations)
3
Output
Sorted array [3,3,3,3,4] with 2 operations
Key Takeaway
🎯 Key Insight: Work backwards and split each violating element into the minimum number of equal parts
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~35 min Avg. Time
850 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