From a067b9588820fc30a0c90d5f29ed4d9bbb9f05cb Mon Sep 17 00:00:00 2001 From: Om prakash Date: Sun, 31 Oct 2021 00:13:06 +0530 Subject: [PATCH] Dp problem added --- ...olutionBestTimeToBuyAndSellStockThree.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 javaSolutionBestTimeToBuyAndSellStockThree.java diff --git a/javaSolutionBestTimeToBuyAndSellStockThree.java b/javaSolutionBestTimeToBuyAndSellStockThree.java new file mode 100644 index 0000000..7251381 --- /dev/null +++ b/javaSolutionBestTimeToBuyAndSellStockThree.java @@ -0,0 +1,43 @@ +//Question Link= https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ + + +import java.util.*; + +public class BestTimeToBuyAndSellStockThree{ + + public static void main(String[] args) throws Exception { + int prices[]={1,3,4,2,6,1,6}; + System.out.println(maxProfit(prices)); + } + + + public static int maxProfit(int[] prices) { + Map mp=new HashMap<>(); + return solve(prices,0,true,2,mp); + } + + public static int solve(int price[],int i,boolean canBuy,int count,Map mp){ + + if(i>=price.length || count<=0) return 0; + + String key=i+"!"+canBuy+"!"+count; + + if(mp.containsKey(key)) return mp.get(key); + + if(canBuy){ + + int idle=solve(price,i+1,canBuy,count,mp); + int buying=(-1*price[i])+solve(price,i+1,false,count,mp); + mp.put(key,Math.max(idle,buying)); + return mp.get(key); + + }else{ + + int idle=solve(price,i+1,canBuy,count,mp); + int selling=price[i]+solve(price,i+1,true,count-1,mp); + mp.put(key,Math.max(idle,selling)); + return mp.get(key); + + } + } + }