Skip to content

Instantly share code, notes, and snippets.

@yokolet
Last active March 29, 2017 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokolet/8df2e3d05638d0f3484bbb3e550268ac to your computer and use it in GitHub Desktop.
Save yokolet/8df2e3d05638d0f3484bbb3e550268ac to your computer and use it in GitHub Desktop.
/*
Problem: Given a rod's length and prices of each length,
find a maximum profit.
*/
public class RodCutting {
// complexity: time O(2^(n-1)), space O(n)
static int cutRodRecur(int[] price, int l) {
// base case
if (l <= 0) {
return 0;
}
int max = -1;
for (int i=0; i<l; i++) {
max = Math.max(max, price[i] + cutRodRecur(price, l - (i + 1)));
}
return max;
}
// complexity: time O(n^2), space O(n)
static int cutRod(int[] price, int L) {
int[] memo = new int[L + 1];
for (int i=1; i<=L; i++) {
int max_value = -1;
for (int j=0; j<i; j++) {
max_value = Math.max(max_value, price[j] + memo[i - (j + 1)]);
}
memo[i] = max_value;
}
return memo[L];
}
public static void main(String[] args) {
System.out.println(cutRodRecur(new int[]{1, 5, 8, 9, 10, 17, 17, 20}, 8));
System.out.println(cutRod(new int[]{1, 5, 8, 9, 10, 17, 17, 20}, 8));
System.out.println(cutRodRecur(new int[]{2, 3, 7, 8, 9}, 5));
System.out.println(cutRod(new int[]{2, 3, 7, 8, 9}, 5));
}
}
/*
References:
http://algorithms.tutorialhorizon.com/dynamic-programming-rod-cutting-problem/
http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment