Skip to content

Commit f8c3aeb

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent 5c51ac1 commit f8c3aeb

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
public:
3+
// Function to compute the minimum cost of merging the array into a single leaf value
4+
// `arr`: The input array of leaf values
5+
// `maxi`: Precomputed map storing the maximum values for all subarrays
6+
int solve(vector<int>& arr, map<pair<int, int>, int>& maxi) {
7+
int n = arr.size();
8+
9+
// `dp[i][j]` stores the minimum cost to merge elements in the range `[i, j]`
10+
vector<vector<int>> dp(n, vector<int>(n, INT_MAX));
11+
12+
// Base case: Cost of merging a single element is zero
13+
for(int i = 0; i < arr.size(); i++) dp[i][i] = 0;
14+
15+
// Iterate over subarray lengths from 2 to `n`
16+
for(int len = 2; len <= n; len++) {
17+
for(int left = 0; left <= n - len; left++) {
18+
int right = left + len - 1; // Calculate the right index for the current subarray
19+
20+
// Try splitting the subarray at each possible position `i`
21+
for(int i = left; i < right; i++) {
22+
// Compute the cost of this split:
23+
// 1. `maxi[{left, i}] * maxi[{i+1, right}]`: Cost of combining the maximum values of the two partitions
24+
// 2. `dp[left][i] + dp[i+1][right]`: Cost of solving the left and right partitions
25+
dp[left][right] = min(dp[left][right],
26+
maxi[{left, i}] * maxi[{i+1, right}] + dp[left][i] + dp[i+1][right]);
27+
}
28+
}
29+
}
30+
31+
// Return the result for the entire array `[0, n-1]`
32+
return dp[0][n-1];
33+
}
34+
35+
// Main function to calculate the minimum cost tree from leaf values
36+
int mctFromLeafValues(vector<int>& arr) {
37+
int n = arr.size();
38+
39+
// Precompute the maximum values for all subarrays `[i, j]`
40+
map<pair<int, int>, int> maxi;
41+
for(int i = 0; i < arr.size(); i++) {
42+
// For a subarray of size 1, the maximum is the element itself
43+
maxi[{i, i}] = arr[i];
44+
for(int j = i + 1; j < arr.size(); j++) {
45+
// For larger subarrays, compute the maximum as the larger of:
46+
// - The current element `arr[j]`
47+
// - The maximum of the previous subarray `[i, j-1]`
48+
maxi[{i, j}] = max(arr[j], maxi[{i, j-1}]);
49+
}
50+
}
51+
52+
// Call the solve function to calculate the result using dynamic programming
53+
return solve(arr, maxi);
54+
}
55+
};

0 commit comments

Comments
 (0)