-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path714-best-time-to-buy-and-sell-stock-with-transaction-fee.cpp
71 lines (66 loc) · 2.01 KB
/
714-best-time-to-buy-and-sell-stock-with-transaction-fee.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
//给定一个整数数组 prices,其中 prices[i]表示第 i 天的股票价格 ;整数 fee 代表了交易股票的手续费用。
//
// 你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
//
// 返回获得利润的最大值。
//
// 注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
//
//
//
// 示例 1:
//
//
//输入:prices = [1, 3, 2, 8, 4, 9], fee = 2
//输出:8
//解释:能够达到的最大利润:
//在此处买入 prices[0] = 1
//在此处卖出 prices[3] = 8
//在此处买入 prices[4] = 4
//在此处卖出 prices[5] = 9
//总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8
//
// 示例 2:
//
//
//输入:prices = [1,3,7,5,10,3], fee = 3
//输出:6
//
//
//
//
// 提示:
//
//
// 1 <= prices.length <= 5 * 10⁴
// 1 <= prices[i] < 5 * 10⁴
// 0 <= fee < 5 * 10⁴
//
//
// Related Topics 贪心 数组 👍 935 👎 0
#include "headers.h"
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
int maxProfit(vector<int> &prices, int fee) {
int n = prices.size();
vector<vector<int>> dp(n, vector<int>(2, 0));
// 1. dp[i][j]: 第 i 天, j=0: 未持有股票, j=1: 持有股票
// 2. dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i] - fee) // 前一天已经未持有,或者前一天持有,今天卖出
// dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
// 3. 初始化
dp[0][1] = -prices[0];
for (int i = 1; i < n; ++i) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[n - 1][0];
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main() {
Solution s;
vector<int> arr{7, 1, 5, 3, 6, 4};
auto res = s.twoSum(arr, 11);
showVector(res);
}