📚188. Best Time to Buy and Sell Stock IV

挺难的题。recursive需要好好想。

public class Solution {
    public int maxProfit(int k, int[] prices) {
        if(k<=0 || prices == null || prices.length==0)
            return 0;
        int len = prices.length;
        
        if(k >= len/2) {
            int max_prof = 0;
            for(int j=1; j<len; j++) {
                if(prices[j] > prices[j-1])
                    max_prof += prices[j]-prices[j-1];
            }
            return max_prof;
        }
        
        int dp[][] = new int[k+1][len];
        
        for(int i=1; i<=k; i++) {
            int max_tmp = dp[i-1][0] - prices[0];
            for(int j=1; j<len; j++) {
                dp[i][j] = Math.max(dp[i][j-1], max_tmp + prices[j]);
                max_tmp = Math.max(max_tmp, dp[i-1][j] - prices[j]);
            }
        }
        
        return dp[k][len-1];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容