forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 188.Best-Time-to-Buy-and-Sell-Stock-IV.cpp
- Loading branch information
1 parent
e3f0499
commit de9f8ec
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
...ramming/188.Best-Time-to-Buy-and-Sell-Stock-IV/188.Best-Time-to-Buy-and-Sell-Stock-IV.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
class Solution { | ||
public: | ||
int maxProfit(int k, vector<int>& prices) | ||
{ | ||
int n = prices.size(); | ||
|
||
if (k>=n/2) | ||
{ | ||
int result = 0; | ||
for (int i=1; i<prices.size(); i++) | ||
if (prices[i]>prices[i-1]) | ||
result+=prices[i]-prices[i-1]; | ||
return result; | ||
} | ||
|
||
vector<int>hold(k+1, INT_MIN/2); | ||
vector<int>sold(k+1, INT_MIN/2); | ||
|
||
hold[0] = 0; | ||
sold[0] = 0; | ||
|
||
for (int i=0; i<n; i++) | ||
{ | ||
auto hold_old = hold; | ||
auto sold_old = sold; | ||
|
||
for (int j=1; j<=k; j++) | ||
{ | ||
hold[j] = max (sold_old[j-1]-prices[i], hold_old[j] ); | ||
sold[j] = max (hold_old[j]+prices[i], sold_old[j] ); | ||
} | ||
|
||
} | ||
|
||
int result = INT_MIN; | ||
for (int j=0; j<=k; j++) | ||
result = max(result, sold[j]); | ||
return result; | ||
} | ||
}; |