|
| 1 | + |
| 2 | +/* |
| 3 | + * Question: What is the best price for cutting a rod of length n |
| 4 | + * |
| 5 | + * Question and Answer Source: http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/ |
| 6 | + * https://www.youtube.com/watch?v=U-09Gs6cbsQ&list=PL962BEE1A26238CA3&index=4 |
| 7 | + * |
| 8 | + */ |
| 9 | + |
| 10 | +package dynamicProgramming; |
| 11 | + |
| 12 | +import java.util.Scanner; |
| 13 | + |
| 14 | +public class CuttingRodProblem { |
| 15 | + public static void main(String[] args){ |
| 16 | + Scanner in = new Scanner(System.in); |
| 17 | + try{ |
| 18 | + System.out.println("Enter the number of cuts"); |
| 19 | + int n = in.nextInt(); |
| 20 | + int[] prices = new int[n]; |
| 21 | + System.out.println("Enter the prices of rod cuts"); |
| 22 | + for(int i=0;i<n;i++){ |
| 23 | + System.out.println("Enter price for "+(i+1)+" rod length"); |
| 24 | + prices[i] = in.nextInt(); |
| 25 | + } |
| 26 | + System.out.println("The best price for rod cut of size "+n+" using Recursion is: "+byRecursion(prices, n)); |
| 27 | + System.out.println("The best price for rod cut of size "+n+" using DP is: "+byDP(prices, n)); |
| 28 | + } |
| 29 | + finally{ |
| 30 | + in.close(); |
| 31 | + } |
| 32 | + } |
| 33 | + public static int byRecursion(int[] prices, int rodLength){ |
| 34 | + |
| 35 | + // Base Case |
| 36 | + if(rodLength<=0) |
| 37 | + return 0; // if rod length is 0 then there is no best price |
| 38 | + |
| 39 | + // Recursive Step |
| 40 | + int maxPrice = 0; |
| 41 | + for (int i = 0; i<rodLength; i++) |
| 42 | + maxPrice = Math.max(maxPrice, prices[i]+byRecursion(prices,rodLength-1-i)); |
| 43 | + |
| 44 | + |
| 45 | + // Returning Step |
| 46 | + return maxPrice; |
| 47 | + |
| 48 | + } |
| 49 | + /* |
| 50 | + * Analysis: |
| 51 | + * Time Complexity = O(2^n) // not sure |
| 52 | + * Space Complexity = O(1) used by dp array |
| 53 | + */ |
| 54 | + public static int byDP(int[] prices, int rodLength){ |
| 55 | + |
| 56 | + int[] dp = new int[rodLength+1]; // +1 because 0 rodLength will have best prices of 0 |
| 57 | + dp[0] = 0; |
| 58 | + |
| 59 | + int maxPrice = -1; |
| 60 | + for(int i=1;i<=rodLength;i++){ // i represents rodLength |
| 61 | + for(int j=0;j<i;j++) // price of cut from 0 to rodLength-1 |
| 62 | + maxPrice = Math.max(maxPrice,prices[j]+dp[i-j-1]); // here i represents rodLength |
| 63 | + dp[i] = maxPrice; |
| 64 | + } |
| 65 | + |
| 66 | + return dp[rodLength]; |
| 67 | + } |
| 68 | + /* |
| 69 | + * Analysis: |
| 70 | + * Time Complexity = O(n^2) |
| 71 | + * Space Complexity = O(n) used by dp array |
| 72 | + */ |
| 73 | +} |
0 commit comments