forked from mithlesh4257/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDynamic_Programming_Rod_Cutting.java
More file actions
48 lines (37 loc) · 922 Bytes
/
Copy pathDynamic_Programming_Rod_Cutting.java
File metadata and controls
48 lines (37 loc) · 922 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// A Dynamic programming solution for Rod Cutting problem
import java.util.*;
import java.lang.*;
import java.io.*;
class RodCutting
{
// A function for calculating max of two nos.
static int max(int a,int b)
{
return (a > b) ? a : b;
}
// Returns the max obtainable cost
static int CutRod(int cost[],int n)
{
int []val = new int[n+1];
int i,j;
val[0] = 0;
for(i = 1; i <= n; i++)
{
int max_value = Integer.MIN_VALUE;
for(j = 0; j < i; j++)
max_value = max(max_value, cost[j] + val[i-j-1]);
val[i] = max_value;
}
return val[n];
}
// Driver function
public static void main(String args[])
{
int []arr = new int [] {3, 5, 8, 9, 10, 17, 17, 20};
int size = arr.length;
System.out.println("Maximum value is " + CutRod(arr, size));
}
}
/* OUTPUT
Maximum value is 24
*/