Skip to content

Commit a3a343c

Browse files
authored
Update 2448-minimum-cost-to-make-array-equal.js
1 parent bf03657 commit a3a343c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

2448-minimum-cost-to-make-array-equal.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,44 @@ const minCost = function (nums, cost) {
2929
return res
3030
}
3131
}
32+
33+
// another
34+
35+
/**
36+
* @param {number[]} nums
37+
* @param {number[]} cost
38+
* @return {number}
39+
*/
40+
const minCost = function(nums, cost) {
41+
const n = nums.length
42+
const {min, max, abs, floor} = Math
43+
let l = Infinity, r = -Infinity
44+
45+
for(const e of nums) {
46+
l = min(e, l)
47+
r = max(e, r)
48+
}
49+
let res = calcCost(l)
50+
while(l < r) {
51+
const mid = floor((l + r) / 2)
52+
const v1 = calcCost(mid)
53+
const v2 = calcCost(mid + 1)
54+
res = min(res, v1, v2)
55+
if(v1 < v2) {
56+
r = mid
57+
} else {
58+
l = mid + 1
59+
}
60+
}
61+
62+
return res
63+
64+
65+
function calcCost(x) {
66+
let res = 0
67+
for(let i = 0; i < n; i++) {
68+
res += abs(nums[i] - x) * cost[i]
69+
}
70+
return res
71+
}
72+
};

0 commit comments

Comments
 (0)