Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. /*
  2. Runtime: 1 ms, faster than 92.91% of Java online submissions for Minimum Cost For Tickets.
  3. Memory Usage: 34.7 MB, less than 100.00% of Java online submissions for Minimum Cost For Tickets.
  4. */
  5.  
  6. class Solution {
  7.     int[] cache;
  8.     int[] days;
  9.     int[][] costs = new int[3][2];
  10.     public int mincostTickets(int[] days, int[] costs) {
  11.         if (days.length == 0) return 0;
  12.         this.days=days;
  13.         this.costs[0][0] = 1;
  14.         this.costs[1][0] = 7;
  15.         this.costs[2][0] = 30;
  16.         this.costs[0][1] = costs[0];
  17.         this.costs[1][1] = costs[1];
  18.         this.costs[2][1] = costs[2];
  19.         this.cache = new int[days.length];
  20.         return minCostTickets(days.length-1);
  21.     }
  22.    
  23.     private int minCostTickets(int dayP) {
  24.         if (cache[dayP] != 0) return cache[dayP];
  25.        
  26.         int cost = -1;
  27.         int day = days[dayP];
  28.         for(int[] ticket : costs) {
  29.             int prevDay = day - ticket[0];
  30.             int dayId = Arrays.binarySearch(days, prevDay);
  31.             int currentCost;
  32.             if (dayId == -1) { // before 1stDay
  33.                 currentCost = ticket[1];
  34.             } else {
  35.                 if (dayId < 0) {
  36.                     dayId = -dayId - 1 - 1;
  37.                 }
  38.                 currentCost = ticket[1] + minCostTickets(dayId);
  39.             }
  40.            
  41.             cost = cost == -1 ? currentCost : Math.min(cost, currentCost);
  42.         }
  43.         cache[dayP] = cost;
  44.         return cost;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement