原題連接在這裏:https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/html
題目:node
Given an array arr
of positive integers, consider all binary trees such that:app
arr
correspond to the values of each leaf in an in-order traversal of the tree. (Recall that a node is a leaf if and only if it has 0 children.)Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.less
Example 1:ide
Input: arr = [6,2,4] Output: 32 Explanation: There are two possible trees. The first has non-leaf node sum 36, and the second has non-leaf node sum 32. 24 24 / \ / \ 12 4 6 8 / \ / \ 6 2 2 4
Constraints:post
2 <= arr.length <= 40
1 <= arr[i] <= 15
2^31
).題解:this
From the example, see that it is better to remove smaller element first.url
Remove small element i and the cost is arr[i] * Math.min(arr[i-1], arr[i+1]). minimum cost happens between smaller values of i-1 and i+1.spa
Remove until there is only one element and sum of cost is the answer.code
Use stack to maintain decreasing order, when there is bigger value num, then pop small value arr[i] and acculate the cost arr[i] * Math.min(num, stk.peek()).
Time Complexity: O(n). n = arr.length.
Space: O(n).
AC Java:
1 class Solution { 2 public int mctFromLeafValues(int[] arr) { 3 if(arr == null || arr.length < 2){ 4 return 0; 5 } 6 7 int res = 0; 8 Stack<Integer> stk = new Stack<>(); 9 stk.push(Integer.MAX_VALUE); 10 for(int num : arr){ 11 while(stk.peek() <= num){ 12 int mid = stk.pop(); 13 res += mid*Math.min(stk.peek(), num); 14 } 15 16 stk.push(num); 17 } 18 19 while(stk.size() > 2){ 20 res += stk.pop()*stk.peek(); 21 } 22 23 return res; 24 } 25 }