Input: count =[4,3], upgrade =[3,5], sell =[4,2], money =[8,9]Output: [3,2]Explanation:
For the first data center,if we sell one server, we'll have `8 + 4 = 12`units of money and we can upgrade the remaining 3 servers.For the second data center,if we sell one server, we'll have `9 + 2 = 11`units of money and we can upgrade the remaining 2 servers.
For each data center, we want to maximize the number of servers we can upgrade, possibly by selling some servers to get more money. For a given number of upgrades k, we can sell up to count - k servers. We check if the money after selling is enough to upgrade k servers. We use binary search to find the maximum k for each data center.
classSolution {
public: vector<int> maxUpgrade(vector<int>& count, vector<int>& upgrade, vector<int>& sell, vector<int>& money) {
int n = count.size();
vector<int> ans(n);
for (int i =0; i < n; ++i) {
int l =0, r = count[i], res =0;
while (l <= r) {
int k = (l + r) /2;
longlong have =1LL* money[i] +1LL* sell[i] * (count[i] - k);
longlong need =1LL* upgrade[i] * k;
if (have >= need) { res = k; l = k +1; }
else r = k -1;
}
ans[i] = res;
}
return ans;
}
};
classSolution {
publicint[]maxUpgrade(int[] count, int[] upgrade, int[] sell, int[] money) {
int n = count.length;
int[] ans =newint[n];
for (int i = 0; i < n; i++) {
int l = 0, r = count[i], res = 0;
while (l <= r) {
int k = (l + r) / 2;
long have = (long)money[i]+ (long)sell[i]* (count[i]- k);
long need = (long)upgrade[i]* k;
if (have >= need) { res = k; l = k + 1; }
else r = k - 1;
}
ans[i]= res;
}
return ans;
}
}
classSolution {
funmaxUpgrade(count: IntArray, upgrade: IntArray, sell: IntArray, money: IntArray): IntArray {
val n = count.size
val ans = IntArray(n)
for (i in0 until n) {
var l = 0var r = count[i]
var res = 0while (l <= r) {
val k = (l + r) / 2val have = money[i].toLong() + sell[i].toLong() * (count[i] - k)
val need = upgrade[i].toLong() * k
if (have >= need) {
res = k
l = k + 1 } else {
r = k - 1 }
}
ans[i] = res
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defmaxUpgrade(self, count: list[int], upgrade: list[int], sell: list[int], money: list[int]) -> list[int]:
n = len(count)
ans = []
for i in range(n):
l, r, res =0, count[i], 0while l <= r:
k = (l + r) //2 have = money[i] + sell[i] * (count[i] - k)
need = upgrade[i] * k
if have >= need:
res = k
l = k +1else:
r = k -1 ans.append(res)
return ans
impl Solution {
pubfnmax_upgrade(count: Vec<i32>, upgrade: Vec<i32>, sell: Vec<i32>, money: Vec<i32>) -> Vec<i32> {
let n = count.len();
letmut ans =vec![0; n];
for i in0..n {
let (mut l, mut r, mut res) = (0, count[i], 0);
while l <= r {
let k = (l + r) /2;
let have = money[i] asi64+ sell[i] asi64* (count[i] asi64- k asi64);
let need = upgrade[i] asi64* k asi64;
if have >= need {
res = k;
l = k +1;
} else {
r = k -1;
}
}
ans[i] = res;
}
ans
}
}