OptimalBST returns the minimum cost of constructing a Binary Search Tree
(keys []int, freq []int, n int)
| 4 | |
| 5 | // OptimalBST returns the minimum cost of constructing a Binary Search Tree |
| 6 | func OptimalBST(keys []int, freq []int, n int) int { |
| 7 | // Initialize DP table with size n x n |
| 8 | dp := make([][]int, n) |
| 9 | for i := range dp { |
| 10 | dp[i] = make([]int, n) |
| 11 | } |
| 12 | |
| 13 | // Base case: single key cost |
| 14 | for i := 0; i < n; i++ { |
| 15 | dp[i][i] = freq[i] |
| 16 | } |
| 17 | |
| 18 | // Build the DP table for sequences of length 2 to n |
| 19 | for length := 2; length <= n; length++ { |
| 20 | for i := 0; i < n-length+1; i++ { |
| 21 | j := i + length - 1 |
| 22 | dp[i][j] = int(^uint(0) >> 1) // Initialize with a large value |
| 23 | sum := sum(freq, i, j) |
| 24 | |
| 25 | // Try every key as root and compute cost |
| 26 | for k := i; k <= j; k++ { |
| 27 | // Left cost: dp[i][k-1] is valid only if k > i |
| 28 | var leftCost int |
| 29 | if k > i { |
| 30 | leftCost = dp[i][k-1] |
| 31 | } else { |
| 32 | leftCost = 0 |
| 33 | } |
| 34 | |
| 35 | // Right cost: dp[k+1][j] is valid only if k < j |
| 36 | var rightCost int |
| 37 | if k < j { |
| 38 | rightCost = dp[k+1][j] |
| 39 | } else { |
| 40 | rightCost = 0 |
| 41 | } |
| 42 | |
| 43 | // Total cost for root k |
| 44 | cost := sum + leftCost + rightCost |
| 45 | |
| 46 | // Update dp[i][j] with the minimum cost |
| 47 | dp[i][j] = min.Int(dp[i][j], cost) |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | return dp[0][n-1] |
| 52 | } |
| 53 | |
| 54 | // Helper function to sum the frequencies |
| 55 | func sum(freq []int, i, j int) int { |