![]() |
VOOZH | about |
Given an array arr[] of size N, the task is to generate a Complete Binary Tree in such a way that sum of the non-leaf nodes is minimum, whereas values of the leaf node corresponds to the array elements in an In-order Traversal of the tree and value of each non-leaf node corresponds to the product of the largest leaf value in the left sub-tree and right sub-tree
Examples:
Input: arr[] = {1, 2, 3, 4}
Output: 20
Explanation:
Please refer below for explanation
Input: arr[] = {5, 2, 3}
Output: 21
Approach:
To remove a number arr[i], it needs a cost a * b, where b >= a and also an element of the array. To minimize the cost of removal, the idea is to minimize b. To compute the non-leaf node there are two candidates, that is the first largest number on the left and the first largest number on the right. The cost to remove arr[i] is a * min(left, right). It can be further decomposed as to find the next greater element in the array, on the left and one right.
Refer: Next greater element
Below is the implementation of the above approach:
21
Time Complexity: O(n)
Auxiliary Space: O(n), where n is the length of the given array.