Description

Say you have an array for which thei_thelement is the price of a given stock on day_i.

Design an algorithm to find themaximumprofit. You may complete at most_two_transactions.

Notice

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example

Given an example[4,4,6,1,1,4,2,5], return6.

Solution

这题其实是对Best Time to Buy and Sell Stock II的一个扩展,求出从左往右遍历的max profit arr和从右往左遍历的max profit arr,然后合起来两个区间不重合也不相邻就好了。

public class Solution {
    /*
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        // write your code here
        if (prices == null || prices.length == 0) {
            return 0;
        }

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

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

        int ret = 0;
        for (int i = 0; i < len; i++) {
            ret = Math.max(ret, left[i] + right[i + 1]);
        }

        return ret;
    }
}

results matching ""

    No results matching ""