Heap
Add all cards to PQ, poll a card as the start, check if there is number can make a straight. Remove from PQ. If no such card, return false.
T: O(n*logn) . S: O(n)
public boolean isNStraightHand(int[] hand, int W) {
if (hand == null || hand.length == 0) {
return false;
}
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int n : hand) {
pq.add(n);
}
while (!pq.isEmpty()) {
int start = pq.poll();
for (int i = 1; i < W; i++) {
if (!pq.remove(start + i)) {
return false;
}
}
}
return true;
}373. Find K Pairs with Smallest Sums
Loop over the numbers, save existing consecutive arrays as range into PQ. Poll pq until find the range can connects to the current number. Start a new range if PQ is empty or pq.peek().end == n (eg.[1,2,3],[3,4,5]). Otherwise connect the range into a longer range.
Add all character counts to a maxHeap. Use a separate queue to keep k distance. As pq pops curt, append the char to sb, reduce the count, and add to queue. When queue.size() >= k, it means that the characters keep at least k distance. Put back the values back in maxHeap one by one, like sliding window.
Use minHeap and maxHeap to store numbers.
addNum: if size of two heap equal, add to
minHeap, pop one fromminHeapand add tomaxHeap. Otherwise, add tomaxHeap, pop one tominHeap.findMedian: If sizes of two heaps equal, return an average from peek of both heaps. Otherwise return from the larger heap.
Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
cost[i] / cost[j] = quality[i] / quality[j]
cost[i] / total cost = quality[i] / total quality
Which means a group of workers share the same "cost[i] / quality[i]", let's call it PAID_RATIO:
PAID_RATIO = total cost / total quality
Sort the workers by paid ratio so that you have the most "efficient worker" (perform best quality and least pay), use maxHeap to and poll the most "inefficient worker" when the total number workers in the group is larger than K. Update the min cost with the updated PAID_RATIO.
3572. Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
Last updated
Was this helpful?