Best Time to Buy and Sell Stock III

来源:互联网 发布:青年网络公开课全集 编辑:程序博客网 时间:2024/05/16 19:53

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 = 0;        for (int i = 0; i < n; i++) {            value = value > left[i] + right[i] ? value : left[i] + right[i];        }        return value;    }}

0 0
原创粉丝点击