Skip to content

Commit f8038db

Browse files
new DP problem added
1 parent 21bb394 commit f8038db

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//Question Link= https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
2+
3+
4+
import java.util.*;
5+
6+
public class BestTimeToBuyAndSellStockThree{
7+
8+
public static void main(String[] args) throws Exception {
9+
int prices[]={1,3,4,2,6,1,6};
10+
System.out.println(maxProfit(prices));
11+
}
12+
13+
14+
public static int maxProfit(int[] prices) {
15+
Map<String,Integer> mp=new HashMap<>();
16+
return solve(prices,0,true,2,mp);
17+
}
18+
19+
public static int solve(int price[],int i,boolean canBuy,int count,Map<String,Integer> mp){
20+
21+
if(i>=price.length || count<=0) return 0;
22+
23+
String key=i+"!"+canBuy+"!"+count;
24+
25+
if(mp.containsKey(key)) return mp.get(key);
26+
27+
if(canBuy){
28+
29+
int idle=solve(price,i+1,canBuy,count,mp);
30+
int buying=(-1*price[i])+solve(price,i+1,false,count,mp);
31+
mp.put(key,Math.max(idle,buying));
32+
return mp.get(key);
33+
34+
}else{
35+
36+
int idle=solve(price,i+1,canBuy,count,mp);
37+
int selling=price[i]+solve(price,i+1,true,count-1,mp);
38+
mp.put(key,Math.max(idle,selling));
39+
return mp.get(key);
40+
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)