-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path714.cpp
More file actions
58 lines (48 loc) · 1.35 KB
/
714.cpp
File metadata and controls
58 lines (48 loc) · 1.35 KB
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
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size();
if (n < 2) {
return 0;
}
vector<vector<int>> dp(n, vector<int>(2));
dp[0][0] = 0;
dp[0][1] = -prices[0] - fee;
for (int i = 1; i < n; ++i) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i] - fee);
}
return dp[n - 1][0];
}
// Optimize space complexity
int maxProfitV2(vector<int>& prices, int fee) {
int n = prices.size();
if (n < 2) {
return 0;
}
vector<int> dp(2);
dp[0] = 0;
dp[1] = -prices[0] - fee;
for (int i = 1; i < n; ++i) {
dp[0] = max(dp[0], dp[1] + prices[i]);
dp[1] = max(dp[1], dp[0] - prices[i] - fee);
}
return dp[0];
}
};
int main()
{
Solution s;
vector<int> prices = {1, 3, 2, 8, 4, 9};
int fee = 2;
int ret = s.maxProfit(prices, fee);
std::cout << "expect ret: 8." << std::endl;
std::cout << "ret:" << ret << std::endl;
int ret2 = s.maxProfitV2(prices, fee);
std::cout << "expect ret2: 8." << std::endl;
std::cout << "ret2: " << ret2 << std::endl;
return 0;
}