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. Transactions at the most K.
Solution:
The typical dynamic programming
Runtime error occurs when you apply too much memory when K (k=1000000000) is large
dealt with in two categories of situations.
1 intMaxprofit (intK, vector<int> &prices) {2 if(K > (Prices.size () >>1)) {3 intMAXM =0;4 for(inti =0; I < (int) Prices.size ()-1; ++i) {5 if(prices[i+1] >Prices[i]) {6MAXM + = prices[i+1] -Prices[i];7 }8 }9 Ten returnMAXM; One } A Else { - int*DP =New int[(k <<1) |1)]; -dp[0] =0; the for(inti =1; I <= (k<<1); ++i) { -Dp[i] =int_min; - } - for(inti =0; I < prices.size (); ++i) { + for(intj = min (i+1, k<<1); J >=1; --j) { - intv = j &0x01? -Prices[i]: prices[i]; +DP[J] = max (Dp[j], dp[j-1] +v); A } at } - intMAXM =0; - for(inti =1; I <= (k<<1); ++i) { -MAXM =Max (MAXM, Dp[i]); - } - in Delete[] DP; - returnMAXM; to}
Leetcode best time to Buy and Sell Stock IV