您的位置:首页 > Web前端

LeetCode题解系列--714. Best Time to Buy and Sell Stock with Transaction Fee

2017-12-13 16:39 387 查看

描述

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

Return the maximum profit you can make.

Example 1:

Input: prices = [1, 3, 2, 8, 4, 9], fee = 2

Output: 8

Explanation: The maximum profit can be achieved by:

Buying at prices[0] = 1

Selling at prices[3] = 8

Buying at prices[4] = 4

Selling at prices[5] = 9

The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Note:

0 < prices.length <= 50000.

0 < prices[i] < 50000.

0 <= fee < 50000.

思路

首先,这是一道DP的题目。

那么首先就是要确定需要保存的状态,题目所求为这么多天后能获得的最大收益,那么我们直接令 A[i] 为第i天所能取得的最大收益。但是我们很快发现,某一天其实会有两种可能性,就是持有一股、或者持有零股,所以我们令 A[i] 为第i天持有一股时的最大收益,而 B[i] 为持有零股时的最大收益。

状态转移方程

A[i]

其实这里的状态转移方程我个人认为不是很好理解,我现在也不是太理解。首先分为两种情况,第i天买入和第i天继续持仓。

第i天买入的情况:收益为 B[i−1]−prices[i]

第i天继续持仓的情况:收益为A[i−1]

以上两个方程乍看都很好理解,但是 A[i] 要在这两个的较大值中选择,这点就不是很好理解了,有点奇怪。

我提供这样一种解释,在买入一股以后,状态由B转向A,他当前手上的资产为 现金+一股,如果我们想要知道这个决定是否比较优,那么就与相同资产状况的时候做比较,即第i天之前的现金+一股时的资产总额。

如果第i天买入要优于第i-1天手上有一股,我们就选择第i天买入,反之我们就认为 A[i−1] 更优,即保持手中有一股的状态。

ps. 这里的解释语言组织的并不是太好

B[i]

这里的状态转移方程比较好理解,因为要满足第i天手上没有持有股票的情况的话,只有两种情况,第i天卖出或者继续不买入。

对于第i天卖出的情况,算上每笔交易的手续费,此时收益为A[i−1]+prices[i]−fee

对于继续不买入的情况,其收益与前一天空持的收益相同,为B[i−1]

综合以上,总的状态转移方程为:

A[i]=max(A[i−1],B[i−1]−prices[i])

B[i]=max(B[i−1],A[i−1]+prices[i]−fee)

根据题意:最后结果为最后一天手上没有股票时的最大收益,即返回B[prices.size()−1];

解答

class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
// have one stock on hand
vector<int> A(prices.size(), 0);
// no stock on hand
vector<int> B(prices.size(), 0);
A[0] = A[0] - prices[0];
for (int i = 1; i < prices.size(); ++i) {
A[i] = max(A[i - 1], B[i - 1] - prices[i]);
B[i] = max(B[i - 1], A[i - 1] + prices[i] - fee);
}
return B[prices.size() - 1];
}
};


内存优化

观察以上的程序,我们很容易看出其实每次迭代只依赖于i-1时的状态,所以我们不需要保存每一天的状态。

// space optimized
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
// have one stock on hand
int A = 0 - prices[0];
// no stock on hand
int B = 0;
int B_temp;
int A_temp;
for (int i = 1; i < prices.size(); ++i) {
A_temp = A;
B_temp = B;

A = max(A_temp, B_temp - prices[i]);

B = max(B_temp, A_temp + prices[i] - fee);
}
return B;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode