Skip to content

Commit c64f9cd

Browse files
authored
Create 2448-minimum-cost-to-make-array-equal.js
1 parent acf792a commit c64f9cd

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number[]} cost
4+
* @return {number}
5+
*/
6+
const minCost = function (nums, cost) {
7+
const n = nums.length
8+
let l = Math.min(...nums)
9+
let r = Math.max(...nums)
10+
11+
let res = calc(l)
12+
while(l < r) {
13+
const mid = Math.floor((l + r) / 2)
14+
const v1 = calc(mid)
15+
const v2 = calc(mid + 1)
16+
res = Math.min(res, v1, v2)
17+
if(v1 < v2) {
18+
r = mid
19+
} else {
20+
l = mid + 1
21+
}
22+
}
23+
24+
return res
25+
26+
function calc(v) {
27+
let res = 0
28+
for (let i = 0; i < n; i++) {
29+
res += Math.abs(nums[i] - v) * cost[i]
30+
}
31+
return res
32+
}
33+
}

0 commit comments

Comments
 (0)