[LeetCode] Minimum Number of Seconds to Make Mountain Height Zero

3296. Minimum Number of Seconds to Make Mountain Height Zero

You are given an integer mountainHeight denoting the height of a mountain.
You are also given an integer array workerTimes representing the work time of workers in seconds.
The workers work simultaneously to reduce the height of the mountain. For worker i:

  • To decrease the mountain’s height by x, it takes workerTimes[i] + workerTimes[i] * 2 + ... + workerTimes[i] * xseconds. For example:

  • To reduce the height of the mountain by 1, it takes workerTimes[i] seconds.

  • To reduce the height of the mountain by 2, it takes workerTimes[i] + workerTimes[i] * 2 seconds, and so on.

Return an integer representing the minimum number of seconds required for the workers to make the height of the mountain 0.

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
class Solution {
long long helper(long long n) {
if(n < 1) return 0;
double x = (-1.0 + sqrt(1.0 + 8.0 * n)) / 2.0;
long long res = static_cast<long long>(floor(x));
return max(res,1ll);
}
bool helper(int mountainHeight, long long k, vector<int>& workerTimes) {
for(auto& t : workerTimes) {
mountainHeight -= helper(k / t);
if(mountainHeight <= 0) return true;
}
return false;
}
public:
long long minNumberOfSeconds(int mountainHeight, vector<int>& workerTimes) {
sort(begin(workerTimes), end(workerTimes));
long long l = 0, r = 1e18, res = r;
while(l <= r) {
long long m = l + (r - l) / 2;
bool ok = helper(mountainHeight, m, workerTimes);
if(ok) {
res = m;
r = m - 1;
} else l = m + 1;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/22/PS/LeetCode/minimum-number-of-seconds-to-make-mountain-height-zero/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.