ven4coding

Rodcut problem with and without memoization

Aug 31st, 2025
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | Software | 0 0
  1. package dp.clrs;
  2.  
  3. import java.util.HashMap;
  4. import java.util.Map;
  5.  
  6. public class RodCut {
  7.     public static void main(String[] args) {
  8.         System.out.println(findMaxRevenue(new int[]{1,5,8,9,10,17, 17, 20, 24, 30}, 7));
  9.         System.out.println(findMaxRevenue(new int[]{1,5,8,9,10,17, 17, 20, 24, 30}, 4));
  10.         System.out.println(findMaxRevenue(new int[]{1,5,8,9,10,17, 17, 20, 24, 30}, 5));
  11.         System.out.println(findMaxRevenue(new int[]{1,5,8,9,10,17, 17, 20, 24, 30}, 8));
  12.         System.out.println(findMaxRevenueWMem(new int[]{1,5,8,9,10,17, 17, 20, 24, 30}, 5, new HashMap<>()));
  13.     }
  14.  
  15.     private static int findMaxRevenue(int[] prices, int rodLength) {
  16.         if (rodLength <= 0) {
  17.             return 0;
  18.         }
  19.         int maxRevenue = 0;
  20.         for (int i = 1; i <= rodLength; i++) {
  21.             maxRevenue = Integer.max(maxRevenue, prices[i-1] + findMaxRevenue(prices, rodLength - i));
  22.         }
  23.         return maxRevenue;
  24.     }
  25.  
  26.     private static int findMaxRevenueWMem(int[] prices, int rodLength, Map<Integer, Integer> lenRevStore) {
  27.         if (rodLength <= 0) {
  28.             return 0;
  29.         }
  30.         if (lenRevStore.containsKey(rodLength)) {
  31.             return lenRevStore.get(rodLength);
  32.         }
  33.         var maxRevenue = computeBalancePieceRevenue(prices, rodLength);
  34.         lenRevStore.put(rodLength, maxRevenue);
  35.         return maxRevenue;
  36.     }
  37.  
  38.     private static int computeBalancePieceRevenue(int[] prices, int rodLength) {
  39.         int maxRevenue = 0;
  40.         for (int i = 1; i <= rodLength; i++) {
  41.             maxRevenue = Integer.max(maxRevenue, prices[i-1] + findMaxRevenue(prices, rodLength - i));
  42.         }
  43.         return maxRevenue;
  44.     }
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment