public class Solution {
##RECURSIVE
public static int cutRod(int price[], int T, int ind) {
// Write your code here.
if(ind == 0) return T*price[0];
int notTake = cutRod(price, T, ind-1);
int Take = (T >= (ind+1)) ? price[ind] + cutRod(price, (T-(ind+1)), ind) : Integer.MIN_VALUE;
return Math.max(notTake, Take);
}
public static int cutRod(int price[], int n) {
// Write your code here.
return cutRod(price, n, price.length-1);
}
##MEMORIZATION
public static int cutRod(int price[], int T, int ind, int[][] dp) {
// Write your code here.
if(ind == 0) return T*price[0];
if(dp[ind][T] != 0) return dp[ind][T];
int notTake = cutRod(price, T, ind-1, dp);
int Take = (T >= (ind+1)) ? price[ind] + cutRod(price, (T-(ind+1)), ind, dp) : Integer.MIN_VALUE;
return dp[ind][T] = Math.max(notTake, Take);
}
public static int cutRod(int price[], int n) {
// Write your code here.
int[][] dp = new int[n][n+1];
return cutRod(price, n, n-1, dp);
}
##TABULATION
public static int cutRod(int price[], int n) {
// Write your code here.
int[][] dp = new int[n][n+1];
for(int T = 0; T <= n; T++){
dp[0][T] = T*price[0];
}
for(int ind = 1; ind < n; ind++){
for(int T = 0; T <= n; T++){
int notTake = dp[ind-1][T];
int Take = (T >= (ind+1)) ? price[ind] + dp[ind][T-(ind+1)] : Integer.MIN_VALUE;
dp[ind][T] = Math.max(notTake, Take);
}
}
return dp[n-1][n];
}
##SPACE OPTIMIZATION
public static int cutRod(int price[], int n) {
// Write your code here.
int[] dp = new int[n+1];
for(int T = 0; T <= n; T++){
dp[T] = T*price[0];
}
for(int ind = 1; ind < n; ind++){
for(int T = 0; T <= n; T++){
int notTake = dp[T];
int Take = (T >= (ind+1)) ? price[ind] + dp[T-(ind+1)] : Integer.MIN_VALUE;
dp[T] = Math.max(notTake, Take);
}
}
return dp[n];
}
}