188. 买卖股票的最佳时机 IV(leetcode)

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/

class Solution {
    public int maxProfit(int k, int[] prices) {
        // 由于可以交易k次,以多少次持有来划分状态
        // f[i][j] ,j<=k*2+1 , 表示前i天中购买,第j次买与第j次卖获得的最大现金
        // f[i][0] = f[i-1][0];// 即未持有过股票,无操作
        // f[i][1] = max(f[i-1][0]-prices[i],f[i-1][1]);
        // ....
        // f[i][j] = max(f[i-1][j-1]-prices[i],f[i-1][j]); // j % 2 == 1
        // f[i][j] = max(f[i-1][j-1]+prices[i],f[i-1][j]); // j % 2 == 0
        // f[1][1] = 0 - prices[0]; 
        // f[1][2] = 0;
        // f[1][3] = 0 - prices[0];
        // ...
        int[][] f=new int[prices.length+1][210];
        for(int i=1;i<=2*k;i+=2) f[1][i]=-prices[0];
        for(int i=2;i<=prices.length;i++)
        {
            for(int j=1;j<=2*k;j++)
            {
                if(j%2==1)f[i][j]=Math.max(f[i-1][j-1]-prices[i-1],f[i-1][j]);
                else f[i][j]=Math.max(f[i-1][j-1]+prices[i-1],f[i-1][j]);
            }
        }
        return f[prices.length][2*k];
    }
}

 

posted @ 2024-09-07 02:44  风乐  阅读(9)  评论(0)    收藏  举报