forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-number-of-robots-within-budget.cpp
54 lines (52 loc) · 1.69 KB
/
maximum-number-of-robots-within-budget.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Time: O(n)
// Space: O(n)
// sliding window, two pointers, mono deque
class Solution {
public:
int maximumRobots(vector<int>& chargeTimes, vector<int>& runningCosts, long long budget) {
int result = 0;
deque<int> dq;
int64_t curr = 0;
int right = 0, left = 0;
for (; right < size(chargeTimes); ++right) {
while (!empty(dq) && chargeTimes[dq.back()] <= chargeTimes[right]) {
dq.pop_back();
}
dq.emplace_back(right);
curr += runningCosts[right];
if (chargeTimes[dq[0]] + (right - left + 1) * curr > budget) {
if (dq[0] == left) {
dq.pop_front();
}
curr -= runningCosts[left++];
}
}
return right - left;
}
};
// Time: O(n)
// Space: O(n)
// sliding window, two pointers, mono deque
class Solution2 {
public:
int maximumRobots(vector<int>& chargeTimes, vector<int>& runningCosts, long long budget) {
int result = 0;
deque<int> dq;
int64_t curr = 0;
for (int right = 0, left = 0; right < size(chargeTimes); ++right) {
while (!empty(dq) && chargeTimes[dq.back()] <= chargeTimes[right]) {
dq.pop_back();
}
dq.emplace_back(right);
curr += runningCosts[right];
while (!empty(dq) && chargeTimes[dq[0]] + (right - left + 1) * curr > budget) {
if (dq[0] == left) {
dq.pop_front();
}
curr -= runningCosts[left++];
}
result = max(result, right - left + 1);
}
return result;
}
};