Best Time to Buy and Sell Stock III

来源:互联网 发布:二代身份证相片 软件 编辑:程序博客网 时间:2024/04/30 22:18

把一个数组拆成两个数组,即处理两个stock I的问题,这样就求解了。

left[0] 和right[length - 1] 都为0,因为这时各自都只剩下一个数组来处理了。

很好的参考:点击打开链接

public class Solution {    public int maxProfit(int[] prices) {        if (prices == null || prices.length == 0) {            return 0;        }        int[] left = new int[prices.length];        int[] right = new int[prices.length];                process(prices, left, right);        int max = 0;        for (int i = 0; i < prices.length; i++) {            max = Math.max(max, left[i] + right[i]);        }        return max;    }        private void process(int[] prices, int[] left, int[] right) {        left[0] = 0;        int min = prices[0];        for (int i = 1; i < prices.length; i++) {            left[i] = Math.max(left[i - 1], prices[i] - min);            min = Math.min(min, prices[i]);        }                right[prices.length - 1] = 0;        int max = prices[prices.length - 1];        for (int i = prices.length - 2; i >= 0; i--) {            right[i] = Math.max(right[i + 1], max - prices[i]);            max = Math.max(max, prices[i]);        }    }}



0 0
原创粉丝点击