The problem is similar to subset-sum in which we determine whether or not a list of number has a subset which produces a given sum, but in this case, we are allowed to create a subset from elements of list p only if it is equal or greater than the respective element in other list q. Also instead of sum of values of elements, the k is number of elements that can be added. so if k is 3 we need to select 3 elements from list p but those elements cannot be smaller than respective element of list q. I am new to dynamic programming and knapsack please help me.
public static List<Integer> kthPerson(int k, List<Integer> p, List<Integer> q) {
List<Integer> q1 = new ArrayList<>();
q1.addAll(q);
Collections.sort(q1);
int maxQ = q1.get(q1.size()-1);
List<Integer> res = new ArrayList<>();
int[][] dp = new int[k+1][maxQ+1];
for(int[] d:dp){
Arrays.fill(d, 0);
}
for (int u = 0; u < maxQ; u++) {
int count = 0;
for (int i = 0; i < p.size(); i++){
if (p.get(i) >= u){
dp[count][u] = i+1;
count++;
}
if (count == k){
break;
}
}
}
for (int s = 0; s < q.size(); s++) {
res.add(dp[k-1][q.get(s)]);
}
return res;
}
/*if you want to test*/
public static void main(String args[]) {
List<Integer> p = new ArrayList<>();
p.add(1);
p.add(4);
p.add(4);
p.add(3);
p.add(1);
p.add(2);
p.add(6);
List<Integer> q = new ArrayList<>();
q.add(1);
q.add(2);
q.add(3);
q.add(4);
q.add(5);
q.add(6);
q.add(7);
kthPerson(2, p, q);
}
/*you will get
2
3
3
3
0
0
0. which is desired result but when the input is really large I get the java heap error*/