Question
Given an array arr of positive integers, consider all binary trees such that:
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.
Example 1:
- 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
Solution
Naive Solution
- #!/usr/bin/env python
- import sys
- class Solution:
- def mctFromLeafValues(self, arr):
- sum_of_non_leaf = 0
- print("### arr={}".format(arr))
- def look_4_min(arr):
- mi = 0
- mv = arr[0] * arr[1]
- for i in range(1, len(arr)-1):
- v = arr[i] * arr[i+1]
- if v < mv:
- mi = i
- mv = v
- rst = (mi, max(arr[mi], arr[mi+1]), mv)
- print('\t{}'.format(rst))
- return rst
- while len(arr) > 2:
- print("{}: {}".format(arr, sum_of_non_leaf))
- mi, mx, mv = look_4_min(arr)
- sum_of_non_leaf += mv
- arr[mi:mi+2] = [mx]
- print("{}: {}".format(arr, sum_of_non_leaf))
- sum_of_non_leaf += arr[0] * arr[1]
- print("[]: {}".format(sum_of_non_leaf))
- return sum_of_non_leaf
- if __name__ == '__main__':
- s = Solution()
- for arr, aw in [
- ([6,2,4], 32),
- ([15,13,5,3,15], 500),
- ([1,2,3,4], 20),
- ([4,3,2,1], 20),
- ([1,3,4,2], 23),
- ([4,2,3,1], 21)
- ]:
- rel = s.mctFromLeafValues(arr)
- assert aw == rel
- print("")
Supplement
* 米开:LeetCode 1130. Minimum Cost Tree From Leaf Values
Water Hack Burns 2 lb of Fat OVERNIGHT
回覆刪除Over 160 thousand men and women are trying a easy and SECRET "liquid hack" to lose 2lbs each and every night as they sleep.
It's proven and works with everybody.
This is how to do it yourself:
1) Hold a drinking glass and fill it with water half glass
2) And then follow this strange hack
and be 2lbs skinnier as soon as tomorrow!