Skip to content

Commit c0ff73e

Browse files
Added solution
1 parent 4325c90 commit c0ff73e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

best_time_to_buy_sell_stock_iv.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public:
3+
int greedy(vector<int>& prices) {
4+
int profit = 0;
5+
for (int i = 1; i < prices.size(); i++) {
6+
profit += (prices[i] > prices[i - 1]) ? (prices[i] - prices[i - 1]) : 0;
7+
}
8+
return profit;
9+
}
10+
11+
int maxProfit(int k, vector<int>& prices) {
12+
13+
int n = prices.size();
14+
if(n < 2 || k < 1) return 0;
15+
16+
if(k > n/2){
17+
return greedy(prices);
18+
}
19+
20+
vector<int> buy(k, INT_MIN);
21+
vector<int> sell(k, 0);
22+
23+
for(auto p : prices){
24+
buy[0] = max(buy[0], -p);
25+
sell[0] = max(sell[0], buy[0] + p);
26+
27+
for(int j=1; j<k; j++){
28+
buy[j] = max(buy[j], (sell[j-1] - p));
29+
sell[j] = max(sell[j], (buy[j] + p));
30+
}
31+
}
32+
return sell.back();
33+
}
34+
};

0 commit comments

Comments
 (0)