Minimum Replacements to Sort the Array — LeetCode 2366 Python Solution

HardGreedyArrayMath
Problem
#2366
Pattern
Greedy
Reading time
3 min

The 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.

Example

Input
nums = [3,9,3]
Output
2
Explanation
Here are the steps to sort the array in non-decreasing order:

Python solution

Python
class Solution:
    def minimumReplacement(self, nums: List[int]) -> int:
        ans = 0
        n = len(nums)
        mx = nums[-1]
        for i in range(n - 2, -1, -1):
            if nums[i] <= mx:
                mx = nums[i]
                continue
            k = (nums[i] + mx - 1) // mx
            ans += k - 1
            mx = nums[i] // k
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2366. Minimum Replacements to Sort the Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2366. Minimum Replacements to Sort the Array?
LeetCode 2366. Minimum Replacements to Sort the Array is rated Hard on LeetCode.
What is the time complexity of LeetCode 2366. Minimum Replacements to Sort the Array?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 2366. Minimum Replacements to Sort the Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2366. Minimum Replacements to Sort the Array cover?
LeetCode 2366. Minimum Replacements to Sort the Array is tagged Greedy, Array and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview