Member-only story
My LeetCode Journey to Become a Better Problem Solver (Day 1)
Today, I’m diving into the medium-level problem on Leetcode — Maximize Happiness of Selected Children on LeetCode.
This problem can be solved with max heap.
The problem
What is max heap?
The largest element is at the root, and each parent node has a value greater than or equal to its children.
Max heaps are often implemented using arrays because of their efficient use of memory and simpler indexing. In an array representation of a max heap, given an element at index i
, its left child is at index 2i + 1
and its right child is at index 2i + 2
. We can find the parent of a child at index i by using (i — 1) // 2
.
So by organizing all the happiness scores into a max heap, we ensure that the largest element is always at the top.
Code
class Solution:
def maximumHappinessSum(self, happiness: List[int], k: int) -> int:
# Convert the happiness list into a max heap
max_heap = [-h for h in happiness] # Negate values to create a max heap
heapq.heapify(max_heap)…