Build a Max Heap
Problem statement
Given an integer array nums, return its exact array after bottom-up max-heap construction.
The array represents a complete binary tree in level order: the children of index i are 2*i+1 and 2*i+2 when those indices exist. Process parent indices from floor(n/2)-1 down through 0, sifting each parent down.
During a sift, swap with the larger child only when that child is strictly greater than the current value. When both children are equal and greater than the current value, choose the left child. Stop when no swap is needed or a leaf is reached. These rules specify one deterministic result; returning a different valid heap is insufficient. Empty input returns an empty array.
Function
buildMaxHeap(nums: int[]) → int[]Examples
Example 1
nums = [6,15,2,4,3,8,19]return = [19,15,8,4,3,6,2]Process parent indices 2, 1 and 0. The final root is 19; sifting the displaced 6 through index 2 produces the exact shown array.
Example 2
nums = [1,4,4]return = [4,1,4]The equal children are both larger than the root, so the left child is selected.
Example 3
nums = [-3,-1,-2]return = [-1,-3,-2]The larger child is -1; negative values use the same ordering rule.
Constraints
0 <= nums.length <= 100000.- Every element is a signed 32-bit integer.