-
Notifications
You must be signed in to change notification settings - Fork 0
/
besttimetobuyandsellstockIV.java
77 lines (74 loc) · 1.66 KB
/
besttimetobuyandsellstockIV.java
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
int [][][] memo;
int dp(int i,int k,int[] p,boolean flag)
{
if(k==0&&flag==false)
return 0;
else if(i>=p.length&&flag)
return -10000;
else if(i>=p.length)
return 0;
boolean t=false;
if(memo[i][k][flag?1:0]>0)
return memo[i][k][flag?1:0];
else
{
int q=dp(i+1,k,p,flag);
if(flag)
q=Math.max(q,dp(i+1,k,p,false)+p[i]);
else
q=Math.max(q,dp(i+1,k-1,p,true)-p[i]);
return memo[i][k][flag?1:0]=q;
}
}
int greedy(int[] p)
{
int ret=0;
for(int i=1;i<p.length;++i)
ret+=p[i]>p[i-1]?p[i]-p[i-1]:0;
return ret;
}
public int maxProfit(int k, int[] prices)
{
if(k>=prices.length/2)
return greedy(prices);
else
{
memo=new int[prices.length][k+1][2];
return dp(0,k,prices,false);
}
}
vector<vector<vector<int>>> memo;
int dp(int i,int k,vector<int>& p,bool flag)
{
if(k==0&&flag==false)
return 0;
else if(i>=p.size()&&flag)
return -10000;
else if(i>=p.size())
return 0;
if(memo[i][k][flag?1:0]>0)
return memo[i][k][flag?1:0];
else
{
int q=dp(i+1,k,p,flag);
if(flag)
q=max(q,dp(i+1,k,p,false)+p[i]);
else
q=max(q,dp(i+1,k-1,p,true)-p[i]);
return memo[i][k][flag?1:0]=q;
}
}
int greedy(vector<int>& p)
{
int ret=0;
for(int i=1;i<p.size();++i)
ret+=p[i]>p[i-1]?p[i]-p[i-1]:0;
return ret;
}
int maxProfit(int k,vector<int>& prices)
{
if(k>=prices.size()/2)
return greedy(prices);
memo.resize(prices.size(),vector<vector<int>>(k+1,vector<int>(2)));
return dp(0,k,prices,false);
}