The best time of dynamic programming Leetcode topic (DP) -714. Buying and selling stocks including fees (Best Time to Buy and Sell Stock with Transaction Fee)

The best time of dynamic programming Leetcode topic (DP) -714. Buying and selling stocks including fees (Best Time to Buy and Sell Stock with Transaction Fee)


 Given an array of integers  prices, where the first  i element represents the first  i day of stock prices; non-negative integer  fee representing the stock trading transaction costs.

You can complete the transaction unlimited number of times, but you need to pay the fee for each transaction. If you have purchased a stock, sell it before you can no longer continue to buy stocks.

Returns the maximum of profit.

Example 1:

Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 
Output: 8 
Explanation: to achieve maximum profit:   
where buying prices [0] = 1 
where selling Prices [ 3] = 8 
buy where prices [4] = 4 
here selling prices [5] = 9 
total profit: ((8--1) - 2) + ((9--4) - 2) = 8 .

note:

  • 0 < prices.length <= 50000.
  • 0 < prices[i] < 50000.
  • 0 <= fee < 50000.

 

DP meaning:

dp [i] [0] represents the i-days did not have the greatest profit when the stock because the stock is not likely to be:

  • The first day is not i-1, did not sell on day i
  • The first days of the stock i-1, the first day i sold it

dp [i] [1] indicates the maximum profit when the stock holdings, stock holdings of the reasons may be:

  • I 1-The first day there, did not sell the i-th day
  • The first day did not stock i-1, the first day i bought

Initial conditions:

dp [0] [0] = 0, because no buy day 0, the profit is 0.

dp [0] [1] = - prices [0], day 0 0 bought stocks, profit 0-prices [0]

return value:

dp [prices.length-1] [0], because the required final hand may not hold shares, the maximum profit is returned when not holding the stock.

State transition equation: 

dp[i][0] = Math.max(dp[i-1][0],prices[i]+dp[i-1][1]-fee);
dp[i][1] = Math.max(dp[i-1][1],dp[i-1][0]-prices[i]);

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int[][] dp = new int[prices.length][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i-1][0],prices[i]+dp[i-1][1]-fee);
            dp[i][1] = Math.max(dp[i-1][1],dp[i-1][0]-prices[i]);
        }
        return dp[prices.length-1][0];
    }
}

 

 Simplify it:

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

    }
}

 

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11482086.html