[123]best time to buy stock iii

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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • “滴滴滴…… 钰寒快走了,上课要迟到了,老班可不是好惹的”如你所见,我是个高中生。我喜欢一个男生,他叫许航,是学...
    银铃萤火阅读 320评论 0 0
  • 1上半年的活动印象最深刻的是元旦晚会加梦想清单,因为那次活动自己是作为主持人参与活动,对活动的每一个细节都有详细的...
    文艺小草阅读 193评论 0 0
  • 已经无语了,不知道说什么好
    洁妹儿阅读 260评论 0 0