[leetcode]714. Best Time to Buy and Sell Stock with Transaction Fee

来源:互联网 发布:淘宝对比价格的软件 编辑:程序博客网 时间:2024/04/30 09:08

dynamic programming

题目:

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 = 2Output: 8Explanation: The maximum profit can be achieved by:Buying at prices[0] = 1Selling at prices[3] = 8Buying at prices[4] = 4Selling at prices[5] = 9The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

思路:

买进股票不需要花钱,但是卖出股票一次就要交一次fee,所以不能像122.Best Time to Buy and Sell Stock II一样,不限制地买进卖出股票。
股票有三种操作:买进、卖出、不买不卖。
cash[i]:卖出第i天的股票的利润
hold[i]:持有第i天的股票时的利润
第i天的股票:
买进
cash[i]有两种情况,一是第i-1天的持有的股票的利润,加上今天卖出的价格,减去fee;二是第i天不卖,手里只有第i-1天卖出的利润。

cash[i] = max(hold[i-1]+prices[i]-fee, cash[i-1])

hold[i]也有两种情况,一是第i-1天卖出的利润,减去今天的股票价格;二是今天不买,手里只有第i-1天持有的利润。

hold[i] = max(cash[i-1]-prices[i], hold[i-1]);

code:

class Solution {public:    int maxProfit(vector<int>& prices, int fee) {        vector<int> cash(prices.size());        vector<int> hold(prices.size());        cash[0] = 0;        hold[0] = -prices[0];        int i;        for (i = 1; i < prices.size(); i++) {            cash[i] = max(hold[i-1]+prices[i]-fee, cash[i-1]);            hold[i] = max(cash[i-1]-prices[i], hold[i-1]);        }        return cash[prices.size()-1];    }};

在代码上可以看到,cash、hold的变化只与前一天的cash、hold的利润有关,因此可以只用两个变量来记录利润变化。

class Solution {public:    int maxProfit(vector<int>& prices, int fee) {        int cash = 0;        int hold  = -prices[0];        for (int i = 1; i < prices.size(); i++) {            cash = max(cash, hold+prices[i]-fee);            hold = max(hold, cash-prices[i]);        }        return cash;    }};
阅读全文
0 0
原创粉丝点击