Untitled
unknown
plain_text
2 years ago
1.2 kB
3
Indexable
Never
public static class HeapElement { private final long sum; private final int absArrayIndex; public HeapElement(long sum, int absArrayIndex) { this.sum = sum; this.absArrayIndex = absArrayIndex; } } public static List<Long> bestCombo(List<Integer> popularity, int k) { PriorityQueue<HeapElement> heap = new PriorityQueue<>((heapEle1, heapEle2) -> (int) (heapEle2.sum - heapEle1.sum)); int[] absArray = popularity.stream().mapToInt(Math::abs).sorted().toArray(); long maxSum = popularity.stream().filter(x -> x > 0).mapToInt(x -> x).sum(); heap.add(new HeapElement(maxSum - absArray[0], 0)); List<Long> result = new ArrayList<>(); result.add(maxSum); while(result.size() < k) { HeapElement heapElement = heap.poll(); result.add(heapElement.sum); int currentIndex = heapElement.absArrayIndex; if(currentIndex + 1 < absArray.length) { heap.add(new HeapElement(heapElement.sum + absArray[currentIndex] - absArray[currentIndex + 1], currentIndex + 1)); heap.add(new HeapElement(heapElement.sum - absArray[currentIndex + 1],currentIndex + 1)); } } return result; }