|
| 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