工作生活

BestTimeToBuyAndSellStock with c

2019-06-30  本文已影响0人  nafoahnaw

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];
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读