-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuyAndSellSecondLecture36.cpp
More file actions
98 lines (95 loc) · 2.39 KB
/
Copy pathBuyAndSellSecondLecture36.cpp
File metadata and controls
98 lines (95 loc) · 2.39 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
//https://bit.ly/3nYO17H
long solve1(int ind,int buy,long *values,int n,vector<vector<long long>> &dp)
{
if(ind == n) return 0;
if(dp[ind][buy] != -1) return dp[ind][buy];
long profit = 0;
if(buy)
{
profit = max(-values[ind] + solve1(ind+1,0,values,n,dp),
solve1(ind+1,1,values,n,dp));
}
else
{
profit = max(values[ind] + solve1(ind+1,1,values,n,dp),
solve1(ind+1,0,values,n,dp));
}
return dp[ind][buy] = profit;
}
long solve2(long *values, int n)
{
vector<vector<long>> dp(n+1,vector<long>(2,-1));
dp[n][0] = dp[n][1] = 0;
for(int ind = n-1;ind >= 0;ind--)
{
for(int buy = 0;buy <= 1;buy++)
{
long profit = 0;
if(buy)
{
profit = max(-values[ind] + dp[ind+1][0],
dp[ind+1][1]);
}
else
{
profit = max(values[ind] + dp[ind+1][1],
dp[ind+1][0]);
}
dp[ind][buy] = profit;
}
}
return dp[0][1];
}
long solve3(long *values, int n)
{
vector<long> ahead(2,-1),curr(2,-1);
ahead[0] = ahead[1] = 0;
for(int ind = n-1;ind >= 0;ind--)
{
for(int buy = 0;buy <= 1;buy++)
{
long profit = 0;
if(buy)
{
profit = max(-values[ind] + ahead[0],
ahead[1]);
}
else
{
profit = max(values[ind] + ahead[1],
ahead[0]);
}
curr[buy] = profit;
}
ahead = curr;
}
return ahead[1];
}
long solve4(long *values, int n)
{
long aheadNotBuy,aheadBuy,curNotBuy,curBuy;
aheadNotBuy = aheadBuy = 0;
for(int ind = n-1;ind >= 0;ind--)
{
curNotBuy = max(values[ind] + aheadBuy,
aheadNotBuy);
curBuy = max(-values[ind] + aheadNotBuy,
aheadBuy);
aheadBuy = curBuy;
aheadNotBuy = curNotBuy;
}
return aheadBuy;
}
long getMaximumProfit(long *values, int n)
{
// vector<vector<long long>> dp(n,vector<long long>(2,-1));
// return solve1(0,1,values,n,dp);
// return solve2(values,n);
// return solve3(values,n);
return solve4(values,n);
}