Best Time to Buy and Sell Stock III

来源:互联网 发布:淘宝网安卓版 编辑:程序博客网 时间:2024/06/18 10:29

Q:

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.

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


Solution:

The first for loop calculates the maximum profit from day 0 to i, and the second for loop calculates the maximum profit from i to n-1. Return the maximum sum of two values.

public class Solution {    public int maxProfit(int[] prices) {        if (prices.length == 0 || prices.length == 1)            return 0;        int[] forward = new int[prices.length];        forward[0] = 0;        int min = Integer.MAX_VALUE;        for (int i = 0; i < prices.length-1; i++) {            if (prices[i+1] >= prices[i]) {                min = Math.min(min, prices[i]);                forward[i+1] = prices[i+1] - min;            }        }        int max = 0;        // the max price in the reverse order        int reverseMax = prices[prices.length-1];        int ret = 0;        for (int i = prices.length-2; i >= 0; i--) {            max = Math.max(max, reverseMax - prices[i]);            ret = Math.max(ret, forward[i] + max);            reverseMax = Math.max(reverseMax, prices[i]);                    }        return ret;    }}


0 0