forked from Hemanth5603/DP---DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuy_stock_sell_3.cpp
43 lines (34 loc) · 1.37 KB
/
buy_stock_sell_3.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
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(int ind, int buy, int cap, vector<int> prices, int n, vector<vector<vector<int>>> &dp){
if(ind == n || cap == 0) return 0;
if(dp[ind][buy][cap] != -1) return dp[ind][buy][cap];
if(buy == 1){
return dp[ind][buy][cap] = max(-prices[ind] + solve(ind + 1, 0, cap, prices, n, dp),
0 + solve(ind+1, 1, cap, prices, n, dp));
}
return dp[ind][buy][cap] = max(prices[ind] + solve(ind+1, 1, cap-1, prices, n, dp),
0 + solve(ind +1, 0, cap, prices, n, dp));
}
int maxProfit(vector<int>& prices) {
int n = prices.size();
vector<vector<vector<int>>> dp(n+1, vector<vector<int>>(2, vector<int>(3, 0)));
for(int ind = n-1;ind >=0; ind--){
for(int buy = 0;buy <=1;buy++){
for(int cap = 1;cap <= 2;cap++){
if(buy == 1){
dp[ind][buy][cap] = max(-prices[ind] + dp[ind + 1][0][cap],
0 + dp[ind+1][1][cap]);
}
else{
dp[ind][buy][cap] = max(prices[ind] + dp[ind+1][1][cap-1],
0 + dp[ind +1][0][cap]);
}
}
}
}
return dp[0][1][2];
}
};