Skip to content

Commit c7da220

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 16fd736 commit c7da220

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution {
2+
public:
3+
// Recursive function to calculate the minimum cost to combine leaf nodes
4+
int solve(vector<int>& arr, map<pair<int, int>, int> & maxi, int left, int right) {
5+
// Base case: If there is only one leaf node, no cost is required
6+
if(left == right) return 0;
7+
8+
int mini = INT_MAX; // Initialize minimum cost to a very high value
9+
10+
// Try every possible split point `i` between `left` and `right`
11+
for(int i = left; i < right; i++) {
12+
// Calculate the cost for this split:
13+
// maxi[{left, i}] * maxi[{i+1, right}] gives the product of the largest
14+
// leaf values in the two partitions
15+
// Add recursive costs for the left and right partitions
16+
mini = min(mini,
17+
maxi[{left, i}] * maxi[{i+1, right}] +
18+
solve(arr, maxi, left, i) +
19+
solve(arr, maxi, i+1, right)
20+
);
21+
}
22+
23+
return mini; // Return the minimum cost for the current range
24+
}
25+
26+
int mctFromLeafValues(vector<int>& arr) {
27+
// Precompute the maximum value in all subarrays using a map
28+
map<pair<int, int>, int> maxi;
29+
30+
// Fill the maxi map with maximum values for every subarray [i, j]
31+
for(int i = 0; i < arr.size(); i++) {
32+
// For subarray of size 1, the maximum is the element itself
33+
maxi[{i, i}] = arr[i];
34+
for(int j = i + 1; j < arr.size(); j++) {
35+
// For larger subarrays, the maximum is the larger of:
36+
// - The current element arr[j]
37+
// - The maximum of the previous subarray [i, j-1]
38+
maxi[{i, j}] = max(arr[j], maxi[{i, j-1}]);
39+
}
40+
}
41+
42+
// Call the recursive function to compute the minimum cost
43+
// The range is the entire array: [0, arr.size() - 1]
44+
return solve(arr, maxi, 0, arr.size()-1);
45+
}
46+
};

0 commit comments

Comments
 (0)