A task scheduler stores urgency scores in an array that it treats as a binary tree: the children of index i are 2i + 1 and 2i + 2. Before it can serve the most urgent task first, it must turn the array into a max-heap, where every parent is at least as big as its children.
Build the heap bottom-up, exactly like heap sort's first phase: for i from Math.floor(n / 2) - 1 down to 0, sift nums[i] down. Sifting compares the item with its children and, if a child is strictly bigger, swaps it with the bigger child (the left one if both children are equal) and continues from there.
Write buildMaxHeap(nums) that returns the array after building the heap.
Input: nums = [4,10,3,5,1] Output: [10,5,3,4,1]
10 stays above 5 and 1; then 4 sinks below 10 and then below 5.
Input: nums = [1,2,3] Output: [3,2,1]
The root 1 swaps with its bigger child, 3.
0 <= nums.length <= 10000-10^6 <= nums[i] <= 10^6Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #200 Heapify the Task List. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.