-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsackProb.java
More file actions
72 lines (60 loc) · 2.18 KB
/
KnapsackProb.java
File metadata and controls
72 lines (60 loc) · 2.18 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//This is a solution to a modification of the classic knapsack problem, in which you're
//given a knapsack with a certain capacity and a set of objects with weights w_1, w_2, ....
//Here, we allow for repeats of items: that is, we imagine that we have infinitely many
//objects of each weight, and the knapsack can contain as many as we like (up to the
//knapsack's capacity).
//See https://www.hackerrank.com/challenges/unbounded-knapsack for further details.
//Note that there are no controls in place to ensure that the user enters a valid input.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class KnapsackProb {
public static int knapSack(int expSum, int[] knap)
{
if(knap.length == 0 | expSum == 0)
{
return 0;
}
else
{
int[] oneLess = Arrays.copyOfRange(knap, 1, knap.length);
if(knap[0]>expSum)
{
return knapSack(expSum, oneLess);
}
else
return Math.max(knapSack(expSum, oneLess), knap[0]+knapSack(expSum-knap[0],oneLess));
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int tests = input.nextInt();
for(int i=0; i<tests; i++)
{
int size = input.nextInt();
int arraySize = 0;
int[] counts = new int[size];
int[] nums = new int[size];
int expSum = input.nextInt();
for(int j=0; j<size; j++)
{
int entry = input.nextInt();
int fits = (int)Math.ceil(expSum/entry);
arraySize = arraySize+fits;
counts[j] = fits;
nums[j]=entry;
}
int[] knap = new int[arraySize];
int index = 0;
for(int j=0; j<size; j++)
for(int k=0; k<counts[j]; k++)
{
knap[index]=nums[j];
index++;
}
System.out.println(knapSack(expSum, knap));
}
}
}