educative.io

Why should max heap store values in the negative?

Why do we store , in the max heap, values in the negative ? I tried to store the values from profits array as they are in the max Heap, but the results were incorrect. This is because the Pop method on Max Heap returns the smallest value - working like a min Heap.

1 Like

Hello @Abhay,

Thank you for sharing this feedback. We’ve looked into the provided solution and it seems that we don’t need to store the negated values in the profits max heap. The Max Heap implementation in the max_heap.go file provides the necessary implementation of the max heap’s operations. The issue lies in the logic behind Less() function, it should return TRUE if the first of the given elements is greater than the second one. The correct implementation of this function should be:

func (h MaxHeap) Less(i, j int) bool {
    return h[i].n1 > h[j].n1
}

Where return h[i].n1 > h[j].n1 compares the values of these elements. If h[i].n1 is greater than h[j].n1, it returns true , indicating that i should come before j in the heap. This ensures that the largest elements are closer to the top of the heap.

We’ll fix the code and let you know once the updated version of the lesson is live.

Please feel free to share any more suggestions and queries.

Happy learning!