Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Minimum Cost Tree From Leaf Values

Posted on August 5, 2019July 26, 2020 by braindenny

Minimum Cost Tree From Leaf Values



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #dynamicprogramming, #binarytree, #inspiring, #intervaldp, #stack, #greedy

Given an array arr of positive integers, consider all binary trees such that:

Each node has either 0 or 2 children;
The values of 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.)
The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree respectively.
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

Constraints:

  • 2 <= arr.length <= 40
  • 1 <= arr[i] <= 15
  • It is guaranteed that the answer fits into a 32-bit signed integer (ie. it is less than 2^31).

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution: Interval DP
// https://code.dennyzhang.com/minimum-cost-tree-from-leaf-values
// Basic Ideas: Interval DP
//
//   dp(i, j): arr[i...j]
//     With parent node, we can divide it into arr[i...k], arr[k+1...j]
// Complexity: Time O(n^3), Space O(n^2)
func max(x, y int) int {
    if x>y {
        return x
    } else {
        return y
    }
}

func min(x, y int) int {
    if x<y {
        return x
    } else {
        return y
    }
}

func mctFromLeafValues(arr []int) int {
    dp := make([][]int, len(arr))
    maxL := make([][]int, len(arr))

    for i, _ := range dp {
        dp[i] = make([]int, len(arr))
        maxL[i] = make([]int, len(arr))
    }
    // caculate max value for a range
    for i:=len(maxL)-1; i>=0; i-- {
        for j:=i; j<len(maxL); j++ {
            if j == i {
                maxL[i][j] = arr[i]
                continue
            }
            maxL[i][j] = max(maxL[i][j-1], arr[j])
        }
    }
    // dp
    for i:=len(arr)-1; i>=0; i-- {
        for j:=i+1; j<len(arr); j++ {
            dp[i][j] = 1<<32-1
            for k:=i; k+1<=j; k++ {
                dp[i][j] = min(dp[i][j], dp[i][k]+dp[k+1][j]+maxL[i][k]*maxL[k+1][j])
            }
        }
    }
    return dp[0][len(arr)-1]
}
linkedin
github
slack

Post Views: 0
Posted in HardTagged #binarytree, #dynamicprogramming, #greedy, #inspiring, #stack, intervaldp, redo

Post navigation

LeetCode: Max Sum of Rectangle No Larger Than K
LeetCode: Article Views I

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.