Minimum Cost to Make Array Equal — LeetCode 2448 Python Solution

HardGreedyArrayBinary SearchPrefix SumSorting
Problem
#2448
Pattern
Prefix Sum
Reading time
3 min

The problem

You are given two 0-indexed arrays nums and cost consisting each of n positive integers. You can do the following operation any number of times: Increase or decrease any element of the array nums by 1.

Example

Input
nums = [1,3,5,2], cost = [2,3,1,14]
Output
8
Explanation
We can make all the elements equal to 2 in the following way:

Python solution

Python
class Solution:
    def minCost(self, nums: List[int], cost: List[int]) -> int:
        arr = sorted(zip(nums, cost))
        n = len(arr)
        f = [0] * (n + 1)
        g = [0] * (n + 1)
        for i in range(1, n + 1):
            a, b = arr[i - 1]
            f[i] = f[i - 1] + a * b
            g[i] = g[i - 1] + b
        ans = inf
        for i in range(1, n + 1):
            a = arr[i - 1][0]
            l = a * g[i - 1] - f[i - 1]
            r = f[n] - f[i] - a * (g[n] - g[i])
            ans = min(ans, l + r)
        return ans

Complexity

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

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2448. Minimum Cost to Make Array Equal is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2448. Minimum Cost to Make Array Equal?
LeetCode 2448. Minimum Cost to Make Array Equal is rated Hard on LeetCode.
What is the time complexity of LeetCode 2448. Minimum Cost to Make Array Equal?
The Python solution on this page runs in O(n\times \log n), where n is the length of the array `nums`.
What is the space complexity of LeetCode 2448. Minimum Cost to Make Array Equal?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2448. Minimum Cost to Make Array Equal cover?
LeetCode 2448. Minimum Cost to Make Array Equal is tagged Greedy, Array, Binary Search, Prefix Sum and Sorting 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