Keep the best three with a heap
transcript
Ride offers arrive one by one. Each offer has a fare. Show the three best fares so far. Do not sort every time.
Here are seven fares. Sorting after each offer is slow. A hundred thousand offers would need billions of steps. A heap does it in log steps.
Keep three fares. The smallest is on top. A five arrives. Push it in. Four fares is too many. Give back the smallest, three. A twelve pushes out the five. The total is twenty nine.
Push the new fare. Over three fares? Pop the smallest. The heap always holds the best three.
The smallest fare is the one to lose. Every other fare in the heap is at least as big. So the heap holds the best three. A fare that is too small bounces straight out. Memory depends on three, not on the stream.
Push the fare. Give back the smallest. Full breakdown in the lecture.