-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0714_maxProfit.cc
48 lines (43 loc) · 1.03 KB
/
Problem_0714_maxProfit.cc
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
#include <algorithm>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
int maxProfit(vector<int>& prices, int fee)
{
if (prices.size() == 0)
{
return 0;
}
int n = prices.size();
vector<vector<int>> dp(n, vector<int>(2));
dp[0][0] = 0;
dp[0][1] = -prices[0];
// 如果需要在买入时扣除手续费,则要修改 dp[0][1]
// dp[0][1] = -prices[0] - fee
for (int i = 1; i < n; i++)
{
// 思考:为什么不可以在买入股票时扣除手续费?
dp[i][0] = std::max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);
dp[i][1] = std::max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
// dp[i][1] = std::max(dp[i - 1][1], dp[i - 1][0] - prices[i] - fee);
}
return dp[n - 1][0];
}
};
void test()
{
Solution s;
vector<int> p1 = {1, 3, 2, 8, 4, 9};
vector<int> p2 = {1, 3, 7, 5, 10, 3};
EXPECT_EQ_INT(8, s.maxProfit(p1, 2));
EXPECT_EQ_INT(6, s.maxProfit(p2, 3));
EXPECT_SUMMARY;
}
int main()
{
test();
return 0;
}