-
Notifications
You must be signed in to change notification settings - Fork 0
/
BestTimetoBuyandSellStockIV.cpp
55 lines (40 loc) · 1.26 KB
/
BestTimetoBuyandSellStockIV.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
if(prices.empty()) return 0;
if(k > prices.size()) return maxProfit(prices);
vector<vector<int> > global(prices.size(), vector<int>(k+1, 0)), local(prices.size(), vector<int>(k+1, 0));
for(int i=1;i<prices.size();i++){
for(int j=1;j<=k;j++){
local[i][j] = max(global[i-1][j-1] + max(0, prices[i] - prices[i-1]), local[i-1][j] + prices[i] - prices[i-1]);
global[i][j] = max(global[i-1][j], local[i][j]);
}
}
return global[prices.size()-1][k];
}
int maxProfit(vector<int>& prices){
int maxprofit = 0;
for(int i=1;i<prices.size();i++){
if(prices[i] > prices[i-1]) maxprofit += prices[i] - prices[i-1];
}
return maxprofit;
}
};
int main(){
int n;
cin>>n;
vector<int> prices;
for(int i=0;i<n;i++){
int price;
cin>>price;
prices.push_back(price);
}
int k;
cin>>k;
Solution *solution = new Solution();
cout<<solution->maxProfit(k, prices);
return 0;
}