714. 买卖股票的最佳时机含手续费

image.png

动态规划

  1. class Solution {
  2. public int maxProfit(int[] prices, int fee) {
  3. // 0 买入股票
  4. // 1 不持有股票
  5. int size = prices.length;
  6. if(size < 2 ) return 0;
  7. int dp[][] = new int [size][2];
  8. dp[0][0] = -prices[0];
  9. for(int i = 1; i < size; i++ ) {
  10. dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
  11. dp[i][1] = Math.max(dp[i - 1][1],dp[i - 1][0] + prices[i] - fee);
  12. }
  13. return Math.max(dp[size - 1][0],dp[size - 1][1]);
  14. }
  15. }

滚动数组

class Solution {
    public int maxProfit(int[] prices, int fee) {
        // 0 买入股票
        // 1 不持有股票
        int size = prices.length;

        if(size < 2 ) return 0;

        int dp[] = new int[2];

        dp[0] = -prices[0];

        for(int i = 1; i < size; i++ ) {
            dp[0] = Math.max(dp[0], dp[1] - prices[i]);

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

        return Math.max(dp[0],dp[1]);
    }
}