-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path122.best time to buy and sell stock2
37 lines (36 loc) · 1.07 KB
/
122.best time to buy and sell stock2
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
class Solution {
public int maxProfit(int[] prices) {
int dp[][]=new int[prices.length+1][2];
int n=prices.length;
dp[n][0]=0;
dp[n][1]=0;
for(int index=prices.length-1;index>=0;index--){
for(int j=0;j<2;j++){
int profit=0;
if(j==1){
profit= Math.max(-prices[index]+dp[index+1][0],dp[index+1][1]);
}
else{
profit= Math.max(prices[index]+dp[index+1][1],dp[index+1][0]);
}
dp[index][j]=profit;
}
}
return dp[0][1];
}
static int helper(int index,int buy,int[] prices,int dp[][]){
if(index==prices.length){
return 0;
}
if(dp[index][buy]!=-1){return dp[index][buy];}
int profit=0;
if(buy==1){
profit= Math.max(-prices[index]+helper(index+1,0,prices,dp),helper(index+1,1,prices,dp));
}
else{
profit= Math.max(prices[index]+helper(index+1,1,prices,dp),helper(index+1,0,prices,dp));
}
dp[index][buy]=profit;
return profit;
}
}