Best Time to Buy and Sell Stock III

来源:互联网 发布:成都java培训班 编辑:程序博客网 时间:2024/06/08 06:05

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

Have you been asked this question in an interview? 
这道题目用了很巧妙的解法。由于有两次transaction,所以在整个数组序列中必定有一个分割点,使分割线前有一次transaction, 分割线后有一次transaction。
那么可以用两个数组left[] 和 right[]: 
left数组用来记录 第i天之前卖stock 可以获得的maximum profit; 
right数组用来记录 第i 天之后买入 stock 可以获得的 maximum profit。
那么 用 left[ i ] + right[ i ] 就可以得到 第i天之前卖出 + 第i天之后再买入 的最大值。
这样子 其实就变成了 Best Time to Buy and Sell Stock I 的题目的应用了。

答案比我的代码要漂亮多了,先把答案贴上吧。
public class Solution {    public int maxProfit(int[] prices) {        if (prices == null || prices.length <= 1) {            return 0;        }        int[] left = new int[prices.length];        int[] right = new int[prices.length];        // DP from left to right;        left[0] = 0;        int min = prices[0];        for (int i = 1; i < prices.length; i++) {            min = Math.min(prices[i], min);            left[i] = Math.max(left[i - 1], prices[i] - min);        }        //DP from right to left;        right[prices.length - 1] = 0;        int max = prices[prices.length - 1];        for (int i = prices.length - 2; i >= 0; i--) {            max = Math.max(prices[i], max);            right[i] = Math.max(right[i + 1], max - prices[i]);        }        int profit = 0;        for (int i = 0; i < prices.length; i++){            profit = Math.max(left[i] + right[i], profit);          }        return profit;    }}

public class Solution {    public int maxProfit(int[] prices) {        if (prices == null || prices.length == 0) {            return 0;        }        int res = 0;        int l = prices.length;                //the maximum profit when sell stock before day[i]        int[] endDay = new int[l];        endDay[0] = 0;        for (int i = 1; i < l; i++) {            endDay[i] = Math.max((endDay[i - 1] + prices[i] - prices[i - 1]), 0);        }                //the maximum profit when buy stock after day[i]        int[] highestPrice = new int[l];        highestPrice[l - 1] = prices[l - 1];        for (int i = l - 2; i >= 0; i--) {            highestPrice[i] = Math.max(highestPrice[i + 1], prices[i + 1]);        }        int[] startDay = new int[l];        startDay[l - 1] = 0;        for (int i = l - 2; i >= 0; i--) {            startDay[i] = Math.max(startDay[i + 1], highestPrice[i] - prices[i]);        }                //combine to find the maximum profit for two transactions        res = Math.max(endDay[l - 1],startDay[0]);        for (int i = 0; i < l - 1; i++) {            res = Math.max(res, endDay[i] + startDay[i + 1]);        }        return res;    }}






0 0
原创粉丝点击