-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 138.java
More file actions
36 lines (28 loc) · 967 Bytes
/
Day 138.java
File metadata and controls
36 lines (28 loc) · 967 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.*;
class Solution {
public int minCost(int[] heights, int[] cost) {
int n = heights.length;
long[][] towers = new long[n][2];
long totalWeight = 0;
for (int i = 0; i < n; i++) {
towers[i][0] = heights[i];
towers[i][1] = cost[i];
totalWeight += cost[i];
}
Arrays.sort(towers, (a, b) -> Long.compare(a[0], b[0]));
long cumulativeWeight = 0;
long medianHeight = 0;
for (int i = 0; i < n; i++) {
cumulativeWeight += towers[i][1];
if (cumulativeWeight * 2 >= totalWeight) {
medianHeight = towers[i][0];
break;
}
}
long minCost = 0;
for (int i = 0; i < n; i++) {
minCost += Math.abs(towers[i][0] - medianHeight) * towers[i][1];
}
return (int) minCost;
}
}