Kth Largest Element using Priority Queue | Rahul Singla | GeeksforGeeks

Поділитися
Вставка
  • Опубліковано 6 січ 2021
  • Get to know Kth Largest Element using Priority Queue.
    Our courses :
    practice.geeksforgeeks.org/co...
    This video is contributed by Rahul Singla
    Please Like, Comment and Share the Video among your friends.
    Install our Android App:
    play.google.com/store/apps/de...
    If you wish, translate into the local language and help us reach millions of other geeks:
    ua-cam.com/users/timedtext_cs_p...
    Follow us on Facebook:
    / gfgvideos
    And Twitter:
    / gfgvideos
    Also, Subscribe if you haven't already! :)
    #largestelement #array #Kthlargestelement #gfg #priorityqueue

КОМЕНТАРІ • 3

  • @mohitpalriwal7157
    @mohitpalriwal7157 3 роки тому +2

    for (int i = 0; i < arr.length; i++) {
    minHeap.add(arr[i]);
    if (minHeap.size() > k) {
    minHeap.remove();
    }
    }
    minHeap.peek(); // kth Largest
    Note:: The name says Min-Heap because Priority-Queue default implementation is Min-Heap (ascending order) but here we are doing a bit more. Every time we have K+1 items we remove the minimum one using Min-Heap-head so that at the end we have K largest elements in the form on a min heap.
    This problem can be solved using Max-Heap of K size also, where the Max-Heap-last element will be same as Kth largest number.

  • @mohitpalriwal7157
    @mohitpalriwal7157 3 роки тому +1

    For second for loop (k..size) you can optimize the code to simply add the kth element and the poll(). It will always remove the least from min-heap.
    for (int i=k; i < size; i++) {
    minHeap.add(arr[i]);
    minHeap.remove(); // or minHeap.poll();
    }

  • @theWorldOfIss
    @theWorldOfIss 3 роки тому

    Sir how to find the maximum in queue using maximum function?