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

代码

解法一:动态规划求解

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length <= 1) {
            return 0;
        }
        int[] maxFromHead = new int[prices.length];
        maxFromHead[0] = 0;
        int minPrice = prices[0];
        int maxProfit = 0;
        for(int i = 1; i < prices.length; i++) {
            // 找到当前结点前面得最低价格
            // 因为是依次向后,所有只需要比较上一个结点和 minPrice 的值即可
            if(prices[i - 1] < minPrice) {
                minPrice = prices[i - 1];
            }
            // 判断现在卖出是否能获得最大利润
            if(prices[i] - minPrice > maxProfit) {
                // 更新最大利润
                maxProfit = prices[i] - minPrice;
            }
            maxFromHead[i] = maxProfit;
        }
        int maxPrice = prices[prices.length - 1];
        int res = maxFromHead[prices.length - 1];
        maxProfit = 0;
        for(int i = prices.length - 2; i >= 1; i--) {
            if(prices[i + 1] > maxPrice) {
                maxPrice = prices[i + 1];
            }
            if(maxProfit < maxPrice - prices[i]) {
                maxProfit = maxPrice - prices[i];
            }
            if(maxProfit + maxFromHead[i - 1] > res) {
                res = maxProfit + maxFromHead[i - 1];
            }
        }
        return res;
    }
}

你可能感兴趣的:(123. Best Time to Buy and Sell Stock III)