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:
nums
by 1
.The cost of doing one operation on the ith
element is cost[i]
.
Return the minimum total cost such that all the elements of the array nums
become equal.
Example 1:
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:
- Increase the 0th element one time. The cost is 2.
- Decrease the 1st element one time. The cost is 3.
- Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3.
The total cost is 2 + 3 + 3 = 8.
It can be shown that we cannot make the array equal with a smaller cost.
Example 2:
Input: nums = [2,2,2,2,2], cost = [4,2,8,1,3] Output: 0 Explanation: All the elements are already equal, so no operations are needed.
Constraints:
n == nums.length == cost.length
1 <= n <= 105
1 <= nums[i], cost[i] <= 106
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To find the cheapest way to make all numbers in a list equal, we'll try making them equal to every possible number. We'll calculate the total cost for each possibility and then pick the one with the lowest cost.
Here's how the algorithm would work step-by-step:
def min_cost_to_make_array_equal_brute_force(numbers, costs):
minimum_total_cost = float('inf')
# Iterate through each number as a potential target value
for target_value in numbers:
current_total_cost = 0
# Calculate the cost to convert all numbers to target_value
for index in range(len(numbers)):
difference = abs(numbers[index] - target_value)
current_total_cost += difference * costs[index]
# Update min cost if the current cost is lower
minimum_total_cost = min(minimum_total_cost, current_total_cost)
return minimum_total_cost
The goal is to find a target value that, if every element in the array was changed to, would give us the minimum overall cost. Instead of testing every single possible target value, we cleverly look for a specific value that is guaranteed to be the best or close to the best.
Here's how the algorithm would work step-by-step:
def min_cost_to_make_array_equal(numbers, costs):
number_cost_pairs = sorted(zip(numbers, costs))
numbers_sorted = [number for number, _ in number_cost_pairs]
costs_sorted = [cost for _, cost in number_cost_pairs]
total_cost_so_far = 0
total_costs_sum = sum(costs_sorted)
# Find the median by iterating until half of cost is reached
for i, cost in enumerate(costs_sorted):
total_cost_so_far += cost
if total_cost_so_far >= total_costs_sum / 2:
median_index = i
break
median_number = numbers_sorted[median_index]
# Target could be one element before or after the median.
possible_targets = set()
possible_targets.add(median_number)
if median_index > 0:
possible_targets.add(numbers_sorted[median_index - 1])
if median_index < len(numbers) - 1:
possible_targets.add(numbers_sorted[median_index + 1])
minimum_cost = float('inf')
# Check the cost for each of the possible target values.
for target_value in possible_targets:
current_cost = 0
for i, number in enumerate(numbers):
current_cost += abs(number - target_value) * costs[i]
minimum_cost = min(minimum_cost, current_cost)
return minimum_cost
Case | How to Handle |
---|---|
Empty or null input array | Return 0 immediately as there's no cost to make an empty array equal. |
Array with a single element | Return 0 immediately, as a single-element array is already equal. |
Large array size potentially causing integer overflow during cost calculation | Use 64-bit integers (long in Java/C++) to store intermediate cost values to prevent overflow. |
Array with all elements identical | Return 0 immediately as the array is already equal. |
Array with negative numbers in values or costs | Ensure the cost function handles negative values correctly or, if the problem statement prohibits them, return an error. |
Array with very large numerical values for elements or costs | Check for potential integer overflow issues during calculations; consider using larger data types or modular arithmetic if applicable and problem constraints allow it. |
Array where the optimal value to equalize to is outside the range of input values | Consider all numbers in the input array as potential target values, or explicitly search for the optimal value within the bounds of possible input values. |
Cases where integer costs cause an overflow during addition, when calculating the cost of each value | Use long type or an arbitrary-precision arithmetic library to avoid integer overflow during cost calculation. |