[LeetCode] Maximum Number of Upgradable Servers

3151. Maximum Number of Upgradable Servers

You have n data centers and need to upgrade their servers.

You are given four arrays count, upgrade, sell, and money of length n, which show:

  • The number of servers
  • The cost of upgrading a single server
  • The money you get by selling a server
  • The money you initially have

for each data center respectively.

Return an array answer, where for each data center, the corresponding element in answer represents the maximum number of servers that can be upgraded.

Note that the money from one data center cannot be used for another data center.

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
class Solution {
bool helper(long long c, long long u, long long s, long long m, long long k) {
m += (c - k) * s;
return m >= u * k;
}
int helper(int c, int u, int s, int m) {
int l = 0, r = c, res = l;
while(l <= r) {
int mid = l + (r - l) / 2;
bool ok = helper(c,u,s,m,mid);
if(ok) {
res = mid;
l = mid + 1;
} else r = mid - 1;
}
return res;
}
public:
vector<int> maxUpgrades(vector<int>& count, vector<int>& upgrade, vector<int>& sell, vector<int>& money) {
vector<int> res;
int n = count.size();
for(int i = 0; i < n; i++) {
res.push_back(helper(count[i], upgrade[i], sell[i], money[i]));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/16/PS/LeetCode/maximum-number-of-upgradable-servers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.