Complete the code to build a max heap from the list.
import heapq nums = [3, 2, 1, 5, 6, 4] max_heap = [-n for n in nums] heapq.[1](max_heap) print(max_heap)
The heapify function converts a list into a heap in-place. Here, we negate numbers to simulate a max heap using Python's min heap.
Complete the code to pop the largest element from the max heap.
largest = -heapq.[1](max_heap) print(largest)
heappop removes and returns the smallest element from the heap. Since we negated numbers, it returns the largest original number when negated back.
Fix the error in the code to find the kth largest element using max heap.
def find_kth_largest(nums, k): max_heap = [-n for n in nums] heapq.heapify(max_heap) for _ in range(k-1): heapq.[1](max_heap) return -max_heap[0] print(find_kth_largest([3,2,3,1,2,4,5,5,6], 4))
To remove the top elements k-1 times, we use heappop. This pops the largest elements (negated) from the heap.
Fill both blanks to create a max heap and pop the largest element.
nums = [10, 20, 15] max_heap = [[1] for n in nums] heapq.[2](max_heap) largest = -heapq.heappop(max_heap) print(largest)
Negate numbers to simulate max heap and use heapify to build the heap.
Fill all three blanks to find the kth largest element using max heap.
def find_kth_largest(nums, k): max_heap = [[1] for n in nums] heapq.[2](max_heap) for _ in range(k-1): heapq.[3](max_heap) return -max_heap[0] print(find_kth_largest([7, 10, 4, 3, 20, 15], 3))
Negate numbers to simulate max heap, build heap with heapify, then pop k-1 times with heappop.
