-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCutting a rod
34 lines (29 loc) · 921 Bytes
/
Cutting a rod
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
/*
You are given a rod that is n centimeter long. You are also given an array of prices which contains prices of all pieces of the rod
which are smaller than n. You have to find out the maximum value that can be obtained by cutting the rod and selling the pieces.
*/
import java.util.*;
public class Source
{
static int cut_rod(int price[], int n)
{
// Complete this function to return the maximum value
int profit[] = new int[n+1];
for(int i = 1;i<=n;i++){
for(int j =1;j<=i;j++){
profit[i] = Math.max(profit[i], price[j-1]+profit[i-j]);
}
}
return profit[n];
}
public static void main(String args[])
{
int n;
Scanner s = new Scanner(System.in);
n = s.nextInt();
int price[] = new int[n];
for(int i = 0; i < n; i++)
price[i] = s.nextInt();
System.out.println(cut_rod(price, n) + "\n" );
}
}