forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminimum-speed-to-arrive-on-time.cpp
39 lines (35 loc) · 1.05 KB
/
minimum-speed-to-arrive-on-time.cpp
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
// Time: O(nlogr), r is the range of speed
// Space: O(1)
class Solution {
public:
int minSpeedOnTime(vector<int>& dist, double hour) {
static const double MAX_SPEED = 1e7;
if (!check(dist, hour, MAX_SPEED)) {
return -1;
}
int left = 1, right = MAX_SPEED;
while (left <= right) {
int mid = left + (right - left) / 2;
if (check(dist, hour, mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
private:
int ceil(int a, int b) {
return (a + b - 1) / b;
}
double total_time(const vector<int>& dist, int x) {
return accumulate(cbegin(dist), prev(cend(dist)), 0,
[this, &x](int total, int i) {
return total + ceil(i, x);
}) +
double(dist.back()) / x;
}
bool check(const vector<int>& dist, double hour, int x) {
return total_time(dist, x) <= hour;
}
};