美文网首页
[123]best time to buy stock iii

[123]best time to buy stock iii

作者: 秋_轩 | 来源:发表于2017-01-01 06:53 被阅读0次

leetcode

For this kind of problem, it is easy to get the idea that we can cut the whole space into several interval, and each interval is responsible for a new transaction.

Then we go forward and backward to calculated the two transaction.

public class Solution {
    public int maxProfit(int[] prices) {

        int len = prices.length;
        if(len == 0)return 0;

        int[] forward = forward(prices);
        int[] backward = backward(prices);

        int res = 0;



        for(int i = 0; i < len; i++){
            //System.out.println(i + " " + forward[i] + " " + backward[i]);

            int cur = forward[i] + backward[i];
            res = Math.max(res,cur);

        }
        return res;





    }

    public int[] forward(int[] prices){
        int[] res = new int[prices.length];
        int min = prices[0];

        for(int i = 1; i < prices.length; i++){
            res[i] = Math.max(prices[i] - min,res[i - 1]);
            min = Math.min(min,prices[i]);
        }

        return res;
    }

    public int[] backward(int[] prices){

        int len = prices.length;
        int[] res = new int[len];
        int max = prices[len - 1];

        for(int i = len - 2; i >= 0; i--){
            res[i] = Math.max(max - prices[i],res[i + 1]);
            max = Math.max(max,prices[i]);
        }
        return res;
    }

    public static void main(String[] args){
        Solution s = new Solution();
        int[] tester = new int[]{1,3,4,5,2,4,5,6};
        int res = s.maxProfit(tester);
        System.out.println(res);
    }
}

相关文章

网友评论

      本文标题:[123]best time to buy stock iii

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