Best Time to Buy and Stock III, sellstock
This article is in the study of the summary, welcome to reprint but please note the Source: http://blog.csdn.net/pistolove/article/details/43740415
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 ).
Ideas:
(1) given an array, the value of element I in the array corresponds to the stock on day I, and can only be traded twice at most. Each transaction can only be bought and sold once, find the maximum profit. This is an enhanced version entitled Best Time to Buy and SellStock II.
(2) This question also examines the maximum difference, but it is quite different from the previous two similar questions. Since a maximum of two transactions can be performed, assume that there are four points in the array (where the length of the array is greater than or equal to 4) a, B, c, d four points to get the most value, where a <B <= c <d, f (max) = (d-c) + (B-a), the array can be divided into two intervals from any position x, 0 ~ X and x ~ Len-1. Consider storing the values of the two intervals in two different arrays. By traversing the entire array, we can get the profit value of any point distributed in the two arrays after two transactions, then, the two arrays are traversed. The maximum value obtained by adding the two arrays at the same position is the result. For details, see the code below.
(3) I hope this article will help you.
Algorithm code implementation:
/** * @author liqq */public class Solution {public int maxProfit(int[] x) {if (x == null || x.length <= 1)return 0;int[] right = new int[x.length];int[] left = new int[x.length];int rmin = x[0];for (int i = 1; i < x.length; i++) {rmin = Math.min(rmin, x[i]);right[i] = Math.max(right[i - 1], x[i] - rmin);}int lmax = x[x.length - 1];left[x.length - 1] = 0;for (int i = x.length - 2; i >= 0; i--) {lmax = Math.max(lmax, x[i]);left[i] = Math.max(left[i + 1], lmax - x[i]);}int sum = 0;for (int i = 0; i < x.length; i++) {sum = Math.max(sum, right[i] + left[i]);}return sum;}}