Skip to content

Instantly share code, notes, and snippets.

@sogwiz
Created July 9, 2019 18:46
Show Gist options
  • Save sogwiz/0992fe299873b99aaca893382bff03c3 to your computer and use it in GitHub Desktop.
Save sogwiz/0992fe299873b99aaca893382bff03c3 to your computer and use it in GitHub Desktop.
public int mincostTickets(int[] days, int[] costs) {
Set<Integer> setRideDays = new HashSet<>();
for(int day : days){
setRideDays.add(day);
}
int[] minCostCache = new int[366];
for(int i = 0; i<minCostCache.length;i++){
minCostCache[i]=-1;
}
minCostCache[0]=0;
return mincostTicketsHelper(costs,minCostCache, setRideDays, days[days.length-1]);
}
public int mincostTicketsHelper(int[] costs, int[] minCostCache, Set<Integer> setRideDays, int currDay){
if(currDay<=0)return minCostCache[0];
if(minCostCache[currDay]>=0)return minCostCache[currDay];
if(setRideDays.contains(currDay)){
int dayMinCost = mincostTicketsHelper(costs,minCostCache,setRideDays,currDay-1) + costs[0];
int weekMinCost = mincostTicketsHelper(costs,minCostCache,setRideDays,currDay-7)+costs[1];
int min = Math.min(dayMinCost,weekMinCost);
int monthCost = mincostTicketsHelper(costs,minCostCache,setRideDays,currDay-30)+costs[2];
minCostCache[currDay]=Math.min(min,monthCost);
}else {
minCostCache[currDay]=mincostTicketsHelper(costs,minCostCache,setRideDays,currDay-1);
}
return minCostCache[currDay];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment