-
Notifications
You must be signed in to change notification settings - Fork 257
/
best-time-to-buy-and-sell-stock-ii.cpp
75 lines (64 loc) · 2.26 KB
/
best-time-to-buy-and-sell-stock-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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Time: O(n)
// Space: O(1)
// DP Solution
class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
int profit = 0;
for (int i = 0; i < static_cast<int>(prices.size()) - 1; ++i) {
profit += max(0, prices[i + 1] - prices[i]);
}
return profit;
}
};
// Generic Solution
class Solution2 {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
const int k = prices.size();
// Optimized solution for unlimited transactions.
if (k >= prices.size() / 2) {
return maxUnlimitedTransactionsProfit(prices);
}
// Get max profit at most k transactions.
return maxAtMostKTransactionsProfit(prices, k);
}
int maxUnlimitedTransactionsProfit(const vector<int>& prices) {
int profit = 0;
for (int i = 0; i < static_cast<int>(prices.size()) - 1; ++i) {
profit += max(0, prices[i + 1] - prices[i]);
}
return profit;
}
int maxAtMostKTransactionsProfit(const vector<int>& prices, const int k) {
// max_sell[j] short for max_sell[i][j]
// denotes as max profit at most j - 1 buy and sell transactions
// and buy the ith prices in the first i prices.
vector<int> max_sell(k + 1, INT_MIN);
// max_buy[j] short for max_buy[i][j]
// denotes as max profit at most j buy and sell transactions
// and sell the ith prices in the first i prices.
vector<int> max_buy(k + 1, INT_MIN);
max_sell[0] = max_buy[0] = 0;
for (int i = 0; i < prices.size(); ++i) {
// Update max profix in [i / 2] + 1 transactions.
for (int j = 1; j <= min(k, i / 2 + 1); ++j) {
// Update max profit of j-th buy
// by (j-1)-th sell - prices[i].
max_buy[j] = max(max_buy[j], max_sell[j - 1] - prices[i]);
// Update max profit of jth sell
// by max(j-th buy + prices[i], (j-1)-th sell]).
max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]);
}
}
return max_sell[k];
}
};