Skip to content

Commit e44016c

Browse files
Merge pull request TheAlgorithms#132 from dpacmen/patch-5
Rodcuting dp approach in java
2 parents 3d42e00 + b67efdf commit e44016c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Dynamic Programming/rod_cutting.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/* A Dynamic Programming solution for Rod cutting problem
2+
Returns the best obtainable price for a rod of
3+
length n and price[] as prices of different pieces */
4+
5+
public class RodCutting
6+
{
7+
8+
private static int cutRod(int price[],int n)
9+
{
10+
int val[] = new int[n+1];
11+
val[0] = 0;
12+
13+
for (int i = 1; i<=n; i++)
14+
{
15+
int max_val = Integer.MIN_VALUE;
16+
for (int j = 0; j < i; j++)
17+
max_val = Math.max(max_val,price[j] + val[i-j-1]);
18+
19+
val[i] = max_val;
20+
}
21+
22+
return val[n];
23+
}
24+
25+
//main function to test
26+
public static void main(String args[])
27+
{
28+
int arr[] = new int[] {2, 5, 13, 19, 20};
29+
int size = arr.length;
30+
System.out.println("Maximum Obtainable Value is " +
31+
cutRod(arr, size));
32+
}
33+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy