HardNo. 2448
Minimum Cost to Make Array Equal — LeetCode 2448 Python Solution
- Pattern
- Prefix Sum
- Topics
- Greedy, Array, Binary Search, Prefix Sum, Sorting
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
- Time
- O(n × log n)where n is the length of the array `nums`
- Space · auxiliary
- O(1)
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
| No. | Problem | Difficulty |
|---|---|---|
| 2389 | Longest Subsequence With Limited Sum | Easy |
| 2439 | Minimize Maximum of Array | Medium |
| 0410 | Split Array Largest Sum | Hard |
| 1648 | Sell Diminishing-Valued Colored Balls | Medium |
| 1889 | Minimum Space Wasted From Packaging | Hard |
| 2141 | Maximum Running Time of N Computers | Hard |
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 × 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.