I. Title Description
Say you had an array for which the i-th element was 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:you engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Two. Topic analysis
Compared with the first two questions, this problem limits the number of trades traded, up to two trades.
You can use dynamic planning to do it, first of all, first scan, calculate [0, …, i]
the maximum profit in the sequence, profit
save it with an array f1
, this step is the complexity of O(n)
time.
The second step is to reverse scan, calculate [i, …, n - 1]
the maximum profit in the sub-sequence, profit
also save it with an array f2
, the time complexity of this step is also O(n)
.
The last step, for, yes f1 + f2
, find the maximum value.
Three. Sample code
#include <iostream>#include <vector>using namespace STD;classSolution { Public:intMaxprofit ( vector<int>&prices) {intSize = Prices.size ();if(Size <=1)return 0; vector<int>F1 (size); vector<int>F2 (size);intMINV = prices[0]; for(inti =1; i < size; ++i) {MINV =STD:: Min (MINV, prices[i]); F1[i] =STD:: Max (F1[i-1], Prices[i]-MINV); }intMAXV = Prices[size-1]; F2[size-1] =0; for(inti = size-2; I >=0; -i) {MAXV =STD:: Max (MAXV, prices[i]); F2[i] =STD:: Max (F2[i +1], maxv-prices[i]); }intsum =0; for(inti =0; i < size; ++i) sum =STD:: Max (SUM, f1[i] + f2[i]);returnSum }};
Four. Summary
Compared to the first two questions, the problem is slightly more difficult, and the question related to the topic there are several. Subsequent updates ...
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode notes: Best time to Buy and Sell Stock III