File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments