Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dp problem added #230

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions javaSolutionBestTimeToBuyAndSellStockThree.java
Original file line number Diff line number Diff line change
@@ -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<String,Integer> mp=new HashMap<>();
return solve(prices,0,true,2,mp);
}

public static int solve(int price[],int i,boolean canBuy,int count,Map<String,Integer> 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);

}
}
}