leetcode 123. Best Time to Buy and Sell Stock III

来源:互联网 发布:云计算虚拟化视频监控 编辑:程序博客网 时间:2024/05/28 16:08

Question

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Code

public int maxProfit(int[] prices) {        if (prices == null || prices.length == 0) {            return 0;        }        int ret = 0;        int len = prices.length;        int[] leftProfile = new int[len];        int min = prices[0];        leftProfile[0] = 0;        for (int i = 1; i < len; i++) {            min = Math.min(min, prices[i]);            leftProfile[i] = Math.max(leftProfile[i - 1], prices[i] - min);        }        int max = Integer.MIN_VALUE;        int profile = 0;        for (int i = len - 1; i >= 0; i--) {            max = Math.max(max, prices[i]);            profile = Math.max(profile, max - prices[i]);            ret = Math.max(ret, profile + leftProfile[i]);        }        return ret;    }
0 0
原创粉丝点击