首页 > 代码库 > Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock III

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

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).

这个题的原型:http://blog.csdn.net/huruzun/article/details/39429631 利用动态规划思想,因为是最多两次交易,用一个数组记录左边每个位置profit 另外一个右边位置profit

数组l[i]记录了price[0..i]的最大profit,

数组r[i]记录了price[i..n]的最大profit。

已知l[i],求l[i+1]是简单的,同样已知r[i],求r[i-1]也很容易。

最后,我们再用O(n)的时间找出最大的l[i]+r[i],即为题目所求。

    public class Solution {    public int maxProfit(int[] prices) {        if (prices == null || prices.length == 0) {            return 0;        }        int n = prices.length;        int[] left = new int[n];        int[] right = new int[n];        int min = prices[0];        for (int i = 1; i < n; i++) {            left[i] = left[i - 1] > prices[i] - min ? left[i - 1] : prices[i] - min;            min = min < prices[i] ? min : prices[i];        }        int max = prices[n - 1];        for (int i = n - 2; i >= 0; i--) {            right[i] = right[i + 1] > max - prices[i] ? right[i + 1] : max - prices[i];            max = max > prices[i] ? max : prices[i];        }        int value = http://www.mamicode.com/0;>

Best Time to Buy and Sell Stock III