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 encrypt the stock before you buy again ).
Original question link: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
Question: Suppose you have an array where the I element represents the given I-day stock price.
Design an algorithm to find the maximum profit. You can complete up to two transactions.
Idea: divide the array into two intervals and obtain the maximum difference between these two intervals.
I learned from the practices of Netizens [1]. Dynamic Planning: records the status with two arrays. f [I] indicates the maximum profit of the range [0, I] (0 <= I <= N-1, G [I] indicates the maximum profit of the range [I, n-1] (0 <= I <= N-1.
public static int maxProfit(int[] prices) {if (prices.length < 2)return 0;int f[] = new int[prices.length];int g[] = new int[prices.length];for (int i = 1, valley = prices[0]; i < prices.length; ++i) {valley = Math.min(valley, prices[i]);f[i] = Math.max(f[i - 1], prices[i] - valley);}for (int i = prices.length - 2, peak = prices[prices.length - 1]; i >= 0; --i) {peak = Math.max(peak, prices[i]);g[i] = Math.max(g[i], peak - prices[i]);}int max_profit = 0;for (int i = 0; i < prices.length; ++i)max_profit = Math.max(max_profit, f[i] + g[i]);return max_profit;}
[1] http://www.cnblogs.com/apoptoxin/p/3770092.html