Problem:
Say you has an array for which the i-th element is the price of a given-stock on day I.
Design an algorithm to find the maximum profit. You are in most of the transactions.
Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
Hide TagsArray Dynamic ProgrammingTest instructions: Given a stock price list, there is a maximum of both hands trading, seeking maximum profit. A very classical algorithm problem!
Thinking:
(1) Read up to two trades: in fact, it is said that the first sale and the second buy may be on the same day
(2) Open two arrays, one for the maximum benefit of sequential recording to that day, and the other to record the maximum benefit after that day.
First of all, because can buy 2 times (the first sale can and second buy at the same time), but the second buy can not be sold to the left on the first time.
So the maintenance of 2 tables, F1 and f2,size are as large as prices.
Significance:
F1[i] said--until the end of the subscript, the left side of the transaction can reach the maximum profit;
F2[i] said--as of the end to I subscript, the right of the transaction can reach the maximum profit;
So, for F1 + F2, seek maximum.
Code
Class Solution {public: int maxprofit (vector<int> &prices) { int size = Prices.size (); if (size = = 0) return 0; Vector<int> F1 (size); vector<int> F2 (size); int MINV = prices[0]; for (int i = 1; i < size; i++) { MINV = std::min (MINV, prices[i]); F1[i] = Std::max (F1[i-1], prices[i]-MINV); } int maxv = prices[size-1]; F2[size-1] = 0; for (int i = size-2; I >= 0; i--) { MAXV = Std::max (MAXV, prices[i]); F2[i] = Std::max (f2[i+1], maxv-prices[i]); } int sum = 0; for (int i = 0; i < size; i++) sum = Std::max (sum, f1[i] + f2[i]); return sum; }};
Leetcode | | 123. Best time to Buy and Sell Stock III