Skip to content

Commit 171c914

Browse files
authored
Create 188. Best Time to Buy and Sell Stock IV-dp-hard.md
1 parent 4c13031 commit 171c914

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
```cpp
2+
class Solution {
3+
public:
4+
int maxProfit(int k,const vector<int>& prices) {
5+
if(k<1 || prices.size() <=1)
6+
return 0;
7+
if(k > prices.size() / 2){
8+
int ans = 0;
9+
for(int i=1;i<prices.size() ; ++i)
10+
ans += max(0,prices[i] - prices[i-1]);
11+
return ans;
12+
}
13+
14+
vector<int> sell(k+1,0);
15+
vector<int> buy(k+1,INT32_MIN>>2);
16+
for(int price : prices){
17+
for(int i=1; i<=k ; ++i){
18+
buy[i] = max(buy[i], sell[i-1] - price);
19+
sell[i] = max(sell[i], buy[i] + price);
20+
}
21+
}
22+
return sell[k];
23+
}
24+
};
25+
```

0 commit comments

Comments
 (0)