Leetcode之动态规划(DP)专题-714. 买卖股票的最佳时机含手续费(Best Time to Buy and Sell Stock with Transaction Fee)

匿名 (未验证) 提交于 2019-12-02 23:59:01

Leetcode之动态规划(DP)专题-714. 买卖股票的最佳时机含手续费(Best Time to Buy and Sell Stock with Transaction Fee)


 给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。

你可以无限次地完成交易,但是你每次交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。

返回获得利润的最大值。

示例 1:

输入: prices = [1, 3, 2, 8, 4, 9], fee = 2 输出: 8 解释: 能够达到的最大利润:   在此处买入 prices[0] = 1 在此处卖出 prices[3] = 8 在此处买入 prices[4] = 4 在此处卖出 prices[5] = 9 总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

注意:

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

 

DP含义:

dp[i][0]表示第i天没有股票时的最大利润,没有股票的原因可能是:

  • 第i-1天就没有,第i天没有买入
  • 第i-1天有股票,第i天把它卖了

dp[i][1]表示持有股票时的最大利润,持有股票的原因可能有:

  • 第i-1天就有,第i天没有卖出
  • 第i-1天没股票,第i天买入了

初始条件:

dp[0][0]=0,因为第0天没有买入,所以利润为0.

dp[0][1]=-prices[0],第0天买入了第0支股票,利润为0-prices[0]

返回值:

dp[prices.length-1][0],因为要求最后手里不得持有股票,所以返回不持有股票时的利润最大值。

状态转移方程: 

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];     } }

 

 简化一下:

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;      } }

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!