← Home

1130. Minimum Cost Tree From Leaf Values

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
113

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1130. Minimum Cost Tree From Leaf Values, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming, binary search, two pointers, stack.

The notes already sitting in the source point us in the right direction:

  • dp
  • time: O(N^3), space: O(N^2)

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are mctFromLeafValues.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N^2), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//dp
02//Runtime: 32 ms, faster than 10.62% of C++ online submissions for Minimum Cost Tree From Leaf Values.
03//Memory Usage: 8.1 MB, less than 100.00% of C++ online submissions for Minimum Cost Tree From Leaf Values.
04//time: O(N^3), space: O(N^2)
05
06class Solution {
07public:
08    int mctFromLeafValues(vector<int>& arr) {
09        int n = arr.size();
10        vector<vector<int>> dp(n, vector<int>(n, 0));
11        
12        //step is window size-1
13        for(int step = 1; step < n; step++){
14            //start point
15            for(int i = 0; i+step < n; i++){
16                int j = i+step;
17                //split point
18                for(int k = i; k+1 <= j; k++){
19                    int cur = dp[i][k] + dp[k+1][j] + *max_element(arr.begin()+i, arr.begin()+k+1) * *max_element(arr.begin()+k+1, arr.begin()+j+1);
20                    
21                    dp[i][j] = (dp[i][j] == 0) ? cur : min(dp[i][j], cur);
22                    // dp[i][j] = min(dp[i][j], cur);
23                    
24                    // cout << "[" << i << " " << k << "] " << dp[i][k] << ", " << *max_element(arr.begin()+i, arr.begin()+k+1) << " [" << k+1 << " " << j << "]" << dp[k+1][j] << ", " << *max_element(arr.begin()+k+1, arr.begin()+j+1) << endl;
25                }
26            }
27        }
28        // cout << endl;
29        
30        return dp[0][n-1];
31    }
32};
33
34//https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/339959/One-Pass-O(N)-Time-and-Space
35//merge node
36//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Minimum Cost Tree From Leaf Values.
37//Memory Usage: 7.7 MB, less than 100.00% of C++ online submissions for Minimum Cost Tree From Leaf Values.
38//time: O(N^2), space: O(N)
39class Solution {
40public:
41    int mctFromLeafValues(vector<int>& arr) {
42        int ans = 0;
43        
44        while(arr.size() > 1){
45            auto min_it = min_element(arr.begin(), arr.end());
46            int min_index = min_it - arr.begin();
47            // merge with its left or right neighbor
48            // it either neighbor not exist, use INT_MAX to replace it
49            ans += min(min_index >= 1 ? arr[min_index-1]: INT_MAX,
50                       min_index+1 < arr.size() ? arr[min_index+1] : INT_MAX) 
51                   * (*min_it);
52            // current node is already merged, 
53            //it's now represented by the the larger value in same subtree
54            arr.erase(arr.begin() + min_index);
55        }
56        
57        return ans;
58    }
59};
60
61//stack
62//https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/339959/One-Pass-O(N)-Time-and-Space
63//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Minimum Cost Tree From Leaf Values.
64//Memory Usage: 7.7 MB, less than 100.00% of C++ online submissions for Minimum Cost Tree From Leaf Values.
65
66class Solution {
67public:
68    int mctFromLeafValues(vector<int>& arr) {
69        int res = 0;
70        stack<int> stk;
71        stk.push(INT_MAX);
72        for(int a : arr){
73            //if a < stk.top(), just push it
74            while(stk.top() <= a){
75                int mid = stk.top(); stk.pop();
76                //stk.top(): left, a: right
77                //mid <= stk.top() and a
78                //merge it with the smaller of them
79                res += mid * min(stk.top(), a);
80            }
81            stk.push(a);
82        }
83        //excluding INT_MAX, there is still at least 2 elements
84        //two 2 elements is the largest of left and right subtree
85        while(stk.size() > 2){
86            int tmp = stk.top(); stk.pop();
87            res += tmp * stk.top();
88        }
89        return res;
90    }
91};

Cost

Complexity

Time
O(N^2), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.