forked from Kyrylo-Ktl/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimum Cost to Make Array Equal.java
More file actions
40 lines (31 loc) · 1009 Bytes
/
Minimum Cost to Make Array Equal.java
File metadata and controls
40 lines (31 loc) · 1009 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
37
38
39
40
public class Solution {
/**
* Time: O(n*log(m))
* Memory: O(1)
* where m - range of values, i.e. maximum - minimum
*/
public long minCost(int[] nums, int[] cost) {
long left = Long.MAX_VALUE, right = Long.MIN_VALUE;
for (int num : nums) {
left = Math.min(left, num);
right = Math.max(right, num);
}
long minCost = getCost(nums, cost, left);
while (left < right) {
long mid = (left + right) / 2;
long a = getCost(nums, cost, mid), b = getCost(nums, cost, mid + 1);
minCost = Math.min(a, b);
if (a < b)
right = mid;
else
left = mid + 1;
}
return minCost;
}
private static long getCost(int[] nums, int[] cost, long num) {
long changeCost = 0;
for (int i = 0; i < nums.length; ++i)
changeCost += Math.abs(nums[i] - num) * cost[i];
return changeCost;
}
}