[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