forked from alexprut/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
44 lines (39 loc) · 1.08 KB
/
Solution.java
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
import java.io.*;
import java.util.*;
import java.lang.*;
public class Solution {
public static Hashtable<Integer, Integer> cache;
public static HashSet<Integer> arr;
public static int min;
public static int solve(int k) {
if (k < min) { return 0; }
if (cache.containsKey(k)) { return cache.get(k); }
int max = Integer.MIN_VALUE;
Iterator<Integer> it = arr.iterator();
while (it.hasNext()) {
int current = it.next();
if (current <= k) {
max = Math.max(max, solve(k - current) + current);
}
}
cache.put(k, max);
return max;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
min = Integer.MAX_VALUE;
cache = new Hashtable<Integer, Integer>();
int n = sc.nextInt();
int k = sc.nextInt();
arr = new HashSet<Integer>();
for (int j = 0; j < n; j++) {
int current = sc.nextInt();
arr.add(current);
min = Math.min(min, current);
}
System.out.println(solve(k));
}
}
}