image.png

思路

我的妈,我又AC了。。我好像get到了买卖股票

  1. var maxProfit = function(prices, fee) {
  2. let dp =new Array(prices.length).fill(0).map(()=>new Array(3).fill(0))
  3. dp[0][0] =-prices[0] //当天持有股票
  4. dp[0][1] =-fee //当天不持有,因为卖出股票,有手续费
  5. dp[0][2] =0 //当天不持有,因为无操作
  6. for(let i=1;i<prices.length;i++){
  7. dp[i][0] =Math.max(dp[i-1][0],dp[i-1][1]-prices[i],dp[i-1][2]-prices[i])
  8. dp[i][1] =dp[i-1][0]+prices[i]-fee
  9. dp[i][2] =Math.max(dp[i-1][1],dp[i-1][2])
  10. }
  11. return Math.max(dp[prices.length-1][1],dp[prices.length-1][2])
  12. };

呃呃呃不用三种状态也行啊啊啊啊
就是初始化的时候不要想太多罢了,第一天不持有就是不持有,不是买了再卖掉哈。

const maxProfit = (prices,fee) => {
    let dp = Array.from(Array(prices.length), () => Array(2).fill(0));
    dp[0][0] = 0 - prices[0];
    for (let i = 1; i < prices.length; i++) {
        dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
        dp[i][1] = Math.max(dp[i - 1][0] + prices[i] - fee, dp[i - 1][1]);
    }
    return Math.max(dp[prices.length - 1][0], dp[prices.length - 1][1]);
}