美文网首页工作生活
BestTimeToBuyAndSellStock with c

BestTimeToBuyAndSellStock with c

作者: nafoahnaw | 来源:发表于2019-06-30 01:19 被阅读0次

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

    相关文章

      网友评论

        本文标题:BestTimeToBuyAndSellStock with c

        本文链接:https://www.haomeiwen.com/subject/djcvcctx.html