educative.io

Why does heap store index of capital and profit?

I may misunderstand this solution. What’s the purpose of storing the index of capital and profit? Why not store capital and profit itself? I’m confused.

1 Like

It seems that both arrays are sorted here and storing indexes for minHeap seems enough. But if Arrays are not sorted , we need to create an object which includes indexes and values and we need to store these objects to minHeap. MinHeap should be designed based on values. When we get the lowest value every time, we will get the related index, then we will find the profit with the help of index and it is enough to insert only profit values to maxHeap. To sum up, minHeap should include indexes together with capitals.

2 Likes

gee, the solution for this problem here is terrible. It’s working but it’s really error prone since both maps are storing indices unless you 200% understand the problem. If I had to write code like this in a real interview, I would have been failed for sure. You have to be super careful when write code like this.
Leetcode solution for this problem is much easier to write.

2 Likes

Minheap should include indexes, yes, but there is no need to store indexes for profit max heap though.

You shouldnt write any code unless you 100% understand the problem. The problem with the code is that there is no need to store indexes for profit max heap. Nothing more.

1 Like

I tried to create the maxHeap without using the index, just storing maxHeap.push(profit[index])
and then did maxHeap.pop(), however, instead of returning 2, it returns 1, suggesting that for some reason, the maxHeap isn’t functioning correctly. I have no idea why this is because if I turn it back into maxHeap.push([profit[index], index]), and run maxHeap.pop() again, this issue disappears and I return 2, the correct value.