forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-number-of-coins-for-fruits-ii.cpp
46 lines (44 loc) · 1.29 KB
/
minimum-number-of-coins-for-fruits-ii.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
// Time: O(n)
// Space: O(n)
// dp, mono deque
class Solution {
public:
int minimumCoins(vector<int>& prices) {
vector<int> dp(size(prices) + 1, numeric_limits<int>::max());
dp[0] = 0;
deque<int> dq;
for (int i = 0, j = 0; i < size(prices); ++i) {
while (!empty(dq) && dp[dq.back()] + prices[dq.back()] >= dp[i] + prices[i]) {
dq.pop_back();
}
dq.emplace_back(i);
for (; j + (j + 1) < i; ++j) {
assert(!empty(dq));
if (dq.front() == j) {
dq.pop_front();
}
}
dp[i + 1] = dp[dq.front()] + prices[dq.front()];
}
return dp.back();
}
};
// Time: O(nlogn)
// Space: O(n)
// dp, bst
class Solution2 {
public:
int minimumCoins(vector<int>& prices) {
vector<int> dp(size(prices) + 1, numeric_limits<int>::max());
dp[0] = 0;
set<pair<int, int>> bst;
for (int i = 0, j = 0; i < size(prices); ++i) {
bst.emplace(dp[i] + prices[i], i);
for (; j + (j + 1) < i; ++j) {
bst.erase(pair(dp[j] + prices[j], j));
}
dp[i + 1] = dp[cbegin(bst)->second] + prices[cbegin(bst)->second];
}
return dp.back();
}
};