Given the input array and the amount, to return the minimum elements you need to get the amount

The problem is selection algorithmwhen you select the smallest number of elements whose sum is equal to at least some N. For example, you can have a list of items whose sum is 5000 or more, but you don’t want more items than you have to take from the input list. Therefore, if one number is 5.001, then your list will contain one number.

another example Input list {3,4,5,1,2} target = {8}. output list will be : {5,3}.

This problem was resolved with help binaryHeapin this excellent series of messages ; but when I implemented in Java, I do not get the desired result. I get everything input list. I can’t pinpoint the cause of the problem. Here is my code;

public class SelectTopSum {
    public static void main(String[] args){
        int[] arr = {5,2,10,1,33};
        int target=33;

        System.out.println(Arrays.toString(selectTop(arr, target)));
    }

    private static int[] selectTop(int[] arr, int sum) {
        //get max heap
        PriorityQueue<Integer> pq = new PriorityQueue<>(10, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });
        int runningTot=0;

        for (int i : arr) {
            if (runningTot<sum) {
                runningTot+=i;
                pq.add(i);
            }
            else if (i > pq.peek()) {
                runningTot-=pq.remove();
                runningTot+=i;
                pq.add(i);
            }
            while (runningTot-pq.peek()>=sum) {
                runningTot-=pq.remove();
            }
        }

        //System.out.println("priority queue is "+ pq);

        int[] result=new int[pq.size()];
        int i=0;
        while (!pq.isEmpty()) {
            result[i]=pq.remove();
            i++;
        }
        return result;
    }
}
+3
1

.

PriorityQueue ( ), , return o2.compareTo(o1);, , , , .

:

return o1.compareTo(o2);

( , o1 o2)

, , , Integer.compareTo, , .

+2

All Articles