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

来源:互联网 发布:js div展开收缩 编辑:程序博客网 时间:2024/05/16 05:28
  • descrption
    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.Note:0 < prices.length <= 50000.0 < prices[i] < 50000.0 <= fee < 50000.
  • 解题思路
    利用动态规划算法。每天的交易有三种情况:买、卖、或不买也不卖。用money[i]假设第i天卖掉股票能获得的最多的钱,用hold[i]假设第i天保留股票持有股票的最大利润。在第i天,如果我们卖掉手中的股票,那么获得的最多的钱是前一天手里持有股票的利润加上卖出价格减去交易费,或者是前一天卖出的利润,如果前一天卖出能获得的钱更多,那么肯定就前一天卖出股票;如果我们没有卖掉股票,那么第i天持有股票的利润就是前一天卖出股票得到的最多的钱减去今天买股票的价格,或者是前一天保留股票的利润比今天大,那么就继续保留。
money[i] = max(sold[i - 1], hold[i - 1] + prices[i] - fee);hold[i] = max(hold[i - 1], sold[i - 1] - prices[i]);
  • 代码如下
class Solution {public:    int maxProfit(vector<int>& prices, int fee) {        int money = 0;         int hold = -prices[0];        for(int d : prices){            int temp = money;            money = max(money, hold + d - fee);            hold = max(hold, temp - d);        }        return money;    }};

原题地址

如有错误请指出,谢谢!

阅读全文
0 0