Intuitive:
For each data center, can upgrade 1, 2, 3,... up to K servers, using O(N) loop over all the server to calculate each's profit.
But we can do it using bin search
Solution
- For each data center, set up a binary search,
-
- low = 0, high = count[i] - for a data center, the minimum servers to upgrade is 0, and the maximum number is all servers, which is count[i]
-
- Use the common mid = (low + high) // 2 which will function as the number of servers to upgrade. Calculate net money
-
- That net money metric drives which half of the space to search. If net money < 0, the test number of servers needs to be reduced, so set high = mid - 1. Otherwise, set low = mid + 1.
-
class Solution {
public int[] maxUpgrades(int[] count, int[] upgrade, int[] sell, int[] money) {
int[] res = new int[count.length];
// loop over all data centers
for (int i = 0; i < res.length; i++) {
int low = 0, high = count[i];
while (low <= high) {
int mid = low + (high - low) / 2;
// if int, might be overflow!
long cost = (long) upgrade[i] * mid; // cost of upgrade [mid] servers
long profit = (long) sell[i] * (count[i] - mid); // profit by selling rest servers
// net revenue by doing so(upgrading mid servers)
long net = money[i] + profit - cost;
if (net >= 0) {
low = mid + 1; // could upgrade more!
} else {
high = mid - 1; // losing money, cant do so
}
}
res[i] = low - 1;
//When the loop terminates, low is one greater than the last valid (affordable) mid.
}
return res;
}
}