




Sponsored
Sponsored
This approach involves treating the problem as a minimization problem where the minimum total cost is calculated by iterating over potential target values using binary search. At each step, the cost to make all elements equal to a proposed target is calculated, and the goal is to find the target that results in the minimal cost. By narrowing the range of potential target values using binary search, this approach efficiently finds the optimal target.
Time Complexity: O(n log(MAX_DIFF)), where MAX_DIFF is the range of possible numbers.
Space Complexity: O(1) since it only uses a fixed amount of extra space.
1function calculateCost(nums, cost, target) {
2    let totalCost = 0;
3    for (let i = 0; i < nums.length; i++) {
4        totalCost += Math.abs(nums[i] - target) * cost[i];
5    }
6    return totalCost;
7}
8
9function minCost(nums, cost) {
10    let minNum = Math.min(...nums);
11    let maxNum = Math.max(...nums);
12    let result = Number.MAX_SAFE_INTEGER;
13    
14    while (minNum <= maxNum) {
15        let midNum = Math.floor((minNum + maxNum) / 2);
16        let costMid = calculateCost(nums, cost, midNum);
17        let costMidPlusOne = calculateCost(nums, cost, midNum + 1);
18        result = Math.min(costMid, costMidPlusOne);
19        if (costMid < costMidPlusOne) {
20            maxNum = midNum - 1;
21        } else {
22            minNum = midNum + 1;
23        }
24    }
25    return result;
26}
27
28let nums = [1, 3, 5, 2];
29let cost = [2, 3, 1, 14];
30console.log("Minimum cost:", minCost(nums, cost));This JavaScript solution finds the minimum and maximum values of the nums array using the spread operator and Math.min/max functions. It then conducts binary search among potential target values to determine the target that offers the minimal total cost of equalizing the nums array.
The main idea is to use the concept of a weighted median to find the optimal target, a value to which all elements should be equalized to minimize cost. The weighted median is the best choice for minimizing the cost because it balances out the costs by taking into account where the bulk of weights lie. By considering each element's weight (cost), the weighted median is a statistically optimal choice that minimizes the total cost for the adjustment.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for auxiliary space used in sorting.
1def min_cost(nums, cost):
2    zipped_pairs = sorted(zip(    
This Python solution involves sorting an array of pairs [num, cost], aiming to identify the weighted median. We accumulate the weights and find a point where the accumulated weight is equal to or exceeds half the total weight, signifying the median. That value is used as the target, minimizing the total cost of modification via a single pass.