BestTimeToBuyAndSellStock with cooldown

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
尝试用dp方式解决,多次剪枝之后耗时勉强及格.

public class BestTimeToBuyAndSellStock {
    public int maxProfit(int[] prices) {
        int maxProfit = Integer.MIN_VALUE;
        Map<String, Integer> memo = new HashMap<>();
        for(int i = prices.length - 1; i >= 0; i--){
            int temp = dfs(prices, 0, "buy_"+i, memo);
            memo.put("buy_"+i, temp);
            if(temp > maxProfit){
                maxProfit = temp;
            }
            if(i!=0){
                temp = dfs(prices, 0, "sell_"+i, memo);
                memo.put("sell_"+i, temp);
            }
        }
        return maxProfit < 0 ? 0 : maxProfit;
    }


    private int dfs(int[] prices, int profit, String node, Map<String, Integer> memo){
        if(memo.containsKey(node)){
            return profit + memo.get(node);
        }
        profit += cost(node, prices);
        int maxProfit = profit;
        String type = node.split("_")[0];
        int num = Integer.valueOf(node.split("_")[1]);
        for(int i = num; i < prices.length - 1; i++){
            int temp = Integer.MIN_VALUE;
            if(type.equals("buy")){
                temp = dfs(prices, profit, "sell_" + (i+1), memo);
            }else{
                if(i+2 < prices.length){
                    temp = dfs(prices, profit, "buy_" + (i+2), memo);
                }
            }
            if(temp > maxProfit){
                maxProfit = temp;
            }
        }
        return maxProfit;
    }

    private int cost(String node, int[] prices){
        if(node.startsWith("sell_")){
            int when = Integer.valueOf(node.split("sell_")[1]);
            return prices[when];
        }else{
            int when = Integer.valueOf(node.split("buy_")[1]);
            return -prices[when];
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容