The UC San Diego course on coursera has been really helping me learn a lot about Data Structures. The latest thing I've learned is about binary heaps, and priority queues. So, I've been solving some data structures problems on the side on HackerRank in order to gain a further understanding. One such problem is Jesse and Cookies.
This problem is really simple if you know what a min heap is. The way to do that in C++ (STL) is make a priority queue with a custom comparison function:
We need a minHeap here. What we do is this:
1. Push all the cookies into the minHeap
2. initialize integer operations = 0
3. while root of minHeap < k:
int newSweetness = minHeap.getMin()
minHeap.ExtractMin()
newSweetness += 2 * minHeap.getMin()
minHeap.ExtractMin()
minHeap.Push(newSweetness)
increment operations by 1
4. return operations
Why does this work?
Due to the property of the min Heap data structure we know that each node is >= to its parent. This means the smallest node is the root, and if that is >= k, every single node in the heap is >= k.
So for each iteration we check if the root is >= k. If not, we take the smallest node and the second smallest nodes out, and put in a new node with sweetness = (smallest) + 2*(second smallest)
The moment the root becomes >= k, we know we are done!
This problem is really simple if you know what a min heap is. The way to do that in C++ (STL) is make a priority queue with a custom comparison function:
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
std::priority_queue<int, std::vector<int>> maxHeap;
We need a minHeap here. What we do is this:
1. Push all the cookies into the minHeap
2. initialize integer operations = 0
3. while root of minHeap < k:
int newSweetness = minHeap.getMin()
minHeap.ExtractMin()
newSweetness += 2 * minHeap.getMin()
minHeap.ExtractMin()
minHeap.Push(newSweetness)
increment operations by 1
4. return operations
Why does this work?
Due to the property of the min Heap data structure we know that each node is >= to its parent. This means the smallest node is the root, and if that is >= k, every single node in the heap is >= k.
So for each iteration we check if the root is >= k. If not, we take the smallest node and the second smallest nodes out, and put in a new node with sweetness = (smallest) + 2*(second smallest)
The moment the root becomes >= k, we know we are done!