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 Array INPUT Original Array: nums 3 idx 0 9 idx 1 4 idx 2 Goal: Sort in non-decreasing order using replacements Operation: Replace element with two elements that sum to original value 9 --> [2, 3, 4] Minimize operations count n = 3 ALGORITHM STEPS 1 Traverse Right to Left Start from last element (4) 2 Check Element at idx 1 nums[1]=9, limit=4 9 > 4, need to split! 3 Split 9 into parts parts = ceil(9/4) = 3 9 --> [3, 3, 3] ops += 3-1 = 2 4 Check Element at idx 0 nums[0]=3, limit=3 3 <= 3, no split needed Final Array (conceptual): [3, 3, 3, 3, 4] FINAL RESULT Before: 3 9 4 After (2 operations): 3 3 3 3 4 Sorted: 3 <= 3 <= 3 <= 3 <= 4 OUTPUT 2 [OK] Minimum operations! Key Insight: Process array from right to left. Each element must not exceed the smallest part of its right neighbor. To minimize operations, split into equal parts. For value V with limit L: parts = ceil(V/L), operations = parts - 1. Greedy approach ensures minimum splits while maintaining sorted order. Time: O(n), Space: O(1). TutorialsPoint - Minimum Replacements to Sort the Array | Greedy (Optimal)
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