Optimal Binary Search Tree
Last Updated :
23 Jul, 2025
Given a sorted array key [0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts, where freq[i] is the number of searches for keys[i]. Construct a binary search tree of all keys such that the total cost of all the searches is as small as possible. The cost of a BST node is the level of that node multiplied by its frequency. The level of the root is 1.
Examples:
Input: keys[] = [10, 12], freq[]= [34, 50]
Output: 118
Explanation: There can be following two possible BSTs
The cost of tree I is 34*1 + 50*2 = 134
The cost of tree II is 50*1 + 34*2 = 118
Input: keys[] = [10, 12, 20], freq[]= [34, 8, 50]
Output: 142
Explanation: There can be many possible BSTs
Among all possible BSTs, cost of the fifth BST is minimum.
Cost of this BST is 1*50 + 2*34 + 3*8 = 142.
Using Recursion - O(n*(2^n)) Time and O(n) Space
We can identify a recursive pattern in this problem.
Recurrence Relation:
- optCost(i, j) = fsum + min(optCost(i, r - 1) + optCost(r + 1, j)) for r in [i , j], where fsum is the sum of frequencies between the indices i and j.
Base Cases:
- If i > j, return 0 (no nodes).
- If i == j, return freq[i] (only one node at index i).
For each subproblem, we compute the cost of selecting each node r as the root of the subtree, recursively calculate the cost for the left and right subtrees, and then add the total frequency sum for the nodes between i and j.
C++
// C++ program for recursive implementation of
// optimal binary search tree
#include <bits/stdc++.h>
using namespace std;
// A utility function to get sum of
// array elements freq[i] to freq[j]
int sum(vector<int> &freq, int i, int j) {
int s = 0;
for (int k = i; k <= j; k++)
s += freq[k];
return s;
}
// A recursive function to calculate
// cost of optimal binary search tree
int optCost(vector<int> &freq, int i, int j) {
// no elements in this subarray
if (j < i)
return 0;
// one element in this subarray
if (j == i)
return freq[i];
// Get sum of freq[i], freq[i+1], ... freq[j]
int fsum = sum(freq, i, j);
// Initialize minimum value
int min = INT_MAX;
// One by one consider all elements
// as root and recursively find cost
// of the BST, compare the cost with
// min and update min if needed
for (int r = i; r <= j; ++r) {
int cost = optCost(freq, i, r - 1) + optCost(freq, r + 1, j);
if (cost < min)
min = cost;
}
// Return minimum value
return min + fsum;
}
int optimalSearchTree(vector<int> &keys, vector<int> &freq) {
int n = keys.size();
return optCost(freq, 0, n - 1);
}
int main() {
vector<int> keys = {10, 12, 20};
vector<int> freq = {34, 8, 50};
cout << optimalSearchTree(keys, freq);
return 0;
}
Java
// Java program for recursive implementation of
// optimal binary search tree
import java.util.*;
class GfG {
// A utility function to get the sum of array elements
// freq[i] to freq[j]
static int sum(int[] freq, int i, int j) {
int s = 0;
for (int k = i; k <= j; k++)
s += freq[k];
return s;
}
// A recursive function to calculate the cost of an
// optimal binary search tree
static int optCost(int[] freq, int i, int j) {
// No elements in this subarray
if (j < i)
return 0;
// One element in this subarray
if (j == i)
return freq[i];
// Get the sum of freq[i], freq[i+1], ... freq[j]
int fsum = sum(freq, i, j);
// Initialize minimum value
int min = Integer.MAX_VALUE;
// One by one, consider all elements as root and
// recursively find cost of the BST, compare the
// cost with min, and update min if needed
for (int r = i; r <= j; r++) {
int cost = optCost(freq, i, r - 1)
+ optCost(freq, r + 1, j);
if (cost < min)
min = cost;
}
// Return minimum value
return min + fsum;
}
static int optimalSearchTree(int[] keys, int[] freq) {
int n = keys.length;
return optCost(freq, 0, n - 1);
}
public static void main(String[] args) {
int[] keys = { 10, 12, 20 };
int[] freq = { 34, 8, 50 };
System.out.println(optimalSearchTree(keys, freq));
}
}
Python
# Python program for recursive implementation of
# optimal binary search tree
def sum(freq, i, j):
s = 0
for k in range(i, j + 1):
s += freq[k]
return s
# A recursive function to calculate the
# cost of an optimal binary search tree
def optCost(freq, i, j):
# No elements in this subarray
if j < i:
return 0
# One element in this subarray
if j == i:
return freq[i]
# Get the sum of freq[i], freq[i+1], ... freq[j]
fsum = sum(freq, i, j)
# Initialize minimum value
min_val = float('inf')
# One by one, consider all elements as root and recursively find
# cost of the BST, compare the cost
# with min_val, and update min_val if needed
for r in range(i, j + 1):
cost = optCost(freq, i, r - 1) + optCost(freq, r + 1, j)
min_val = min(min_val, cost)
# Return minimum value
return min_val + fsum
def optimalSearchTree(keys, freq):
n = len(keys)
return optCost(freq, 0, n - 1)
keys = [10, 12, 20]
freq = [34, 8, 50]
print(optimalSearchTree(keys, freq))
C#
// C# program for recursive implementation of
// optimal binary search tree
using System;
class GfG {
// A utility function to get the sum of array elements
// freq[i] to freq[j]
static int Sum(int[] freq, int i, int j) {
int s = 0;
for (int k = i; k <= j; k++)
s += freq[k];
return s;
}
// A recursive function to calculate the cost of an
// optimal binary search tree
static int OptCost(int[] freq, int i, int j) {
// No elements in this subarray
if (j < i)
return 0;
// One element in this subarray
if (j == i)
return freq[i];
// Get the sum of freq[i], freq[i+1], ... freq[j]
int fsum = Sum(freq, i, j);
// Initialize minimum value
int min = int.MaxValue;
// One by one, consider all elements as root and
// recursively find cost of the BST, compare the
// cost with min, and update min if needed
for (int r = i; r <= j; r++) {
int cost = OptCost(freq, i, r - 1)
+ OptCost(freq, r + 1, j);
if (cost < min)
min = cost;
}
// Return minimum value
return min + fsum;
}
static int OptimalSearchTree(int[] keys, int[] freq) {
int n = keys.Length;
return OptCost(freq, 0, n - 1);
}
static void Main(string[] args) {
int[] keys = { 10, 12, 20 };
int[] freq = { 34, 8, 50 };
Console.WriteLine(OptimalSearchTree(keys, freq));
}
}
JavaScript
// JavaScript program for recursive implementation of
// optimal binary search tree
// A utility function to get the sum of array elements
// freq[i] to freq[j]
function sum(freq, i, j) {
let s = 0;
for (let k = i; k <= j; k++)
s += freq[k];
return s;
}
// A recursive function to calculate the cost of an optimal
// binary search tree
function optCost(freq, i, j) {
// Base cases
// No elements in this subarray
if (j < i)
return 0;
// One element in this subarray
if (j === i)
return freq[i];
// Get the sum of freq[i], freq[i+1], ... freq[j]
let fsum = sum(freq, i, j);
// Initialize minimum value
let min = Number.MAX_SAFE_INTEGER;
// One by one, consider all elements as root and
// recursively find cost of the BST, compare the cost
// with min, and update min if needed
for (let r = i; r <= j; r++) {
let cost = optCost(freq, i, r - 1)
+ optCost(freq, r + 1, j);
min = Math.min(min, cost);
}
// Return minimum value
return min + fsum;
}
function optimalSearchTree(keys, freq) {
let n = keys.length;
return optCost(freq, 0, n - 1);
}
// Driver Code
let keys = [ 10, 12, 20 ];
let freq = [ 34, 8, 50 ];
console.log(optimalSearchTree(keys, freq));
Using Top - Dowm Dp (Memoization) - O(n^3) Time and O(n^2) Space
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure: Minimum cost for a given i, j i.e. optCost(i, j), depends on the optimal solutions of the subproblems optCost(i, r-1) and optCost(r + 1, j). By choosing the total of these optimal substructures, we can efficiently calculate answer.
2. Overlapping Subproblems: While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times. For example optCost(1, 1) is computed multiple times from optCost(1, 2) and optCost(1, 3).
- There are two parameter that change in the recursive solution: i going from 0 to n-1, j ranges from i to n-1. So we create a 2D array of size n*n for memoization.
- We initialize array as -1 to indicate nothing is computed initially.
- Now we modify our recursive solution to first check if the value is -1, then only make recursive calls. This way, we avoid re-computations of the same subproblems.
C++
// C++ program for implementation of
// optimal binary search tree using memoization
#include <bits/stdc++.h>
using namespace std;
// A utility function to get sum of
// array elements freq[i] to freq[j]
int sum(vector<int> &freq, int i, int j) {
int s = 0;
for (int k = i; k <= j; k++)
s += freq[k];
return s;
}
// A recursive function to calculate
// cost of optimal binary search tree
int optCost(vector<int> &freq, int i, int j, vector<vector<int>> &memo) {
// Base cases
if (j < i)
return 0;
if (j == i)
return freq[i];
if (memo[i][j] != -1)
return memo[i][j];
// Get sum of freq[i], freq[i+1], ... freq[j]
int fsum = sum(freq, i, j);
// Initialize minimum value
int min = INT_MAX;
// One by one consider all elements
// as root and recursively find cost
// of the BST, compare the cost with
// min and update min if needed
for (int r = i; r <= j; ++r) {
int cost = optCost(freq, i, r - 1, memo) + optCost(freq, r + 1, j, memo);
if (cost < min)
min = cost;
}
// Return minimum value
return memo[i][j] = min + fsum;
}
// The main function that calculates
// minimum cost of a Binary Search Tree.
// It mainly uses optCost() to find
// the optimal cost.
int optimalSearchTree(vector<int> &keys, vector<int> &freq) {
int n = keys.size();
vector<vector<int>> memo(n, vector<int>(n, -1));
return optCost(freq, 0, n - 1, memo);
}
int main() {
vector<int> keys = {10, 12, 20};
vector<int> freq = {34, 8, 50};
cout << optimalSearchTree(keys, freq);
return 0;
}
Java
// Java program for implementation of
// optimal binary search tree using memoization
import java.util.Arrays;
class GfG {
// A utility function to get sum of
// array elements freq[i] to freq[j]
static int sum(int[] freq, int i, int j) {
int s = 0;
for (int k = i; k <= j; k++)
s += freq[k];
return s;
}
// A recursive function to calculate
// cost of optimal binary search tree
static int optCost(int[] freq, int i, int j,
int[][] memo) {
// no elements in this subarray
if (j < i)
return 0;
// one element in this subarray
if (j == i)
return freq[i];
if (memo[i][j] != -1)
return memo[i][j];
// Get sum of freq[i], freq[i+1], ... freq[j]
int fsum = sum(freq, i, j);
// Initialize minimum value
int min = Integer.MAX_VALUE;
// One by one consider all elements
// as root and recursively find cost
// of the BST, compare the cost with
// min and update min if needed
for (int r = i; r <= j; r++) {
int cost = optCost(freq, i, r - 1, memo)
+ optCost(freq, r + 1, j, memo);
if (cost < min)
min = cost;
}
// Return minimum value
return memo[i][j] = min + fsum;
}
// The main function that calculates
// minimum cost of a Binary Search Tree.
// It mainly uses optCost() to find
// the optimal cost.
static int optimalSearchTree(int[] keys, int[] freq) {
int n = keys.length;
int[][] memo = new int[n][n];
for (int[] row : memo)
Arrays.fill(row, -1);
return optCost(freq, 0, n - 1, memo);
}
public static void main(String[] args) {
int[] keys = { 10, 12, 20 };
int[] freq = { 34, 8, 50 };
System.out.println(optimalSearchTree(keys, freq));
}
}
Python
# Python program for implementation of
# optimal binary search tree using memoization
def sum(freq, i, j):
s = 0
for k in range(i, j + 1):
s += freq[k]
return s
# A recursive function to calculate
# cost of optimal binary search tree
def optCost(freq, i, j, memo):
# Base cases
# no elements in this subarray
if j < i:
return 0
# one element in this subarray
if j == i:
return freq[i]
if memo[i][j] != -1:
return memo[i][j]
# Get sum of freq[i], freq[i+1], ... freq[j]
fsum = sum(freq, i, j)
# Initialize minimum value
min_cost = float('inf')
# One by one consider all elements
# as root and recursively find cost
# of the BST, compare the cost with
# min and update min if needed
for r in range(i, j + 1):
cost = optCost(freq, i, r - 1, memo) + \
optCost(freq, r + 1, j, memo)
if cost < min_cost:
min_cost = cost
# Return minimum value
memo[i][j] = min_cost + fsum
return memo[i][j]
# The main function that calculates
# minimum cost of a Binary Search Tree.
# It mainly uses optCost() to find
# the optimal cost.
def optimalSearchTree(keys, freq):
n = len(keys)
memo = [[-1 for _ in range(n)] for _ in range(n)]
return optCost(freq, 0, n - 1, memo)
keys = [10, 12, 20]
freq = [34, 8, 50]
print(optimalSearchTree(keys, freq))
C#
// C# program for implementation of
// optimal binary search tree using memoization
using System;
class GfG {
// A utility function to get sum of
// array elements freq[i] to freq[j]
static int Sum(int[] freq, int i, int j) {
int s = 0;
for (int k = i; k <= j; k++)
s += freq[k];
return s;
}
// A recursive function to calculate
// cost of optimal binary search tree
static int OptCost(int[] freq, int i, int j,
int[, ] memo) {
// Base cases
// no elements in this subarray
if (j < i)
return 0;
// one element in this subarray
if (j == i)
return freq[i];
if (memo[i, j] != -1)
return memo[i, j];
// Get sum of freq[i], freq[i+1], ... freq[j]
int fsum = Sum(freq, i, j);
// Initialize minimum value
int min = int.MaxValue;
// One by one consider all elements
// as root and recursively find cost
// of the BST, compare the cost with
// min and update min if needed
for (int r = i; r <= j; r++) {
int cost = OptCost(freq, i, r - 1, memo)
+ OptCost(freq, r + 1, j, memo);
if (cost < min)
min = cost;
}
// Return minimum value
memo[i, j] = min + fsum;
return memo[i, j];
}
// The main function that calculates
// minimum cost of a Binary Search Tree.
// It mainly uses OptCost() to find
// the optimal cost.
static int OptimalSearchTree(int[] keys, int[] freq) {
int n = keys.Length;
int[, ] memo = new int[n, n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
memo[i, j] = -1;
return OptCost(freq, 0, n - 1, memo);
}
static void Main(string[] args) {
int[] keys = { 10, 12, 20 };
int[] freq = { 34, 8, 50 };
Console.WriteLine(OptimalSearchTree(keys, freq));
}
}
JavaScript
// JavaScript program for implementation of
// optimal binary search tree using memoization
function sum(freq, i, j) {
let s = 0;
for (let k = i; k <= j; k++)
s += freq[k];
return s;
}
// A recursive function to calculate
// cost of optimal binary search tree
function optCost(freq, i, j, memo) {
// no elements in this subarray
if (j < i)
return 0;
// one element in this subarray
if (j === i)
return freq[i];
if (memo[i][j] !== -1)
return memo[i][j];
// Get sum of freq[i], freq[i+1], ... freq[j]
let fsum = sum(freq, i, j);
// Initialize minimum value
let min = Number.MAX_VALUE;
// One by one consider all elements
// as root and recursively find cost
// of the BST, compare the cost with
// min and update min if needed
for (let r = i; r <= j; r++) {
let cost = optCost(freq, i, r - 1, memo)
+ optCost(freq, r + 1, j, memo);
if (cost < min)
min = cost;
}
// Return minimum value
memo[i][j] = min + fsum;
return memo[i][j];
}
// The main function that calculates
// minimum cost of a Binary Search Tree.
// It mainly uses optCost() to find
// the optimal cost.
function optimalSearchTree(keys, freq) {
let n = keys.length;
let memo
= Array.from({length : n}, () => Array(n).fill(-1));
return optCost(freq, 0, n - 1, memo);
}
let keys = [ 10, 12, 20 ];
let freq = [ 34, 8, 50 ];
console.log(optimalSearchTree(keys, freq));
Using Bottom - Up Dp (Tabulation) - O(n^3) Time and O(n^2) Space
We use an auxiliary array dp[n][n] to store the solutions of subproblems. dp[0][n-1] will hold the final result.
The challenge in implementation is, all diagonal values must be filled first, then the values which lie on the line just above the diagonal. In other words, we must first fill all dp[i][i] values, then all dp[i][i+1] values, then all dp[i][i+2] values. The idea used in the implementation is same as Matrix Chain Multiplication problem, we use a variable 'l' for chain length and increment 'l', one by one. We calculate column number 'j' using the values of 'i' and 'l'.
C++
// C++ program for implementation of
// optimal binary search tree using tabulation
#include <bits/stdc++.h>
using namespace std;
// A utility function to get sum of
// array elements freq[i] to freq[j]
int sum(vector<int> &freq, int i, int j) {
int s = 0;
for (int k = i; k <= j; k++)
s += freq[k];
return s;
}
// A Dynamic Programming based function that calculates the
// minimum cost of a Binary Search Tree.
int optimalSearchTree(vector<int> &keys, vector<int> &freq) {
int n = keys.size();
// Create an auxiliary 2D matrix to store
// results of subproblems
vector<vector<int>> dp(n, vector<int>(n, 0));
// dp[i][j] = Optimal cost of binary search tree
// that can be formed from keys[i] to keys[j].
// dp[0][n-1] will store the resultant dp
// For a single key, dp is equal to frequency of the key
for (int i = 0; i < n; i++) {
dp[i][i] = freq[i];
}
// Now we need to consider chains of length 2, 3, ... .
// l is chain length.
for (int l = 2; l <= n; l++) {
// i is row number in dp[][]
for (int i = 0; i <= n - l; i++) {
// Get column number j from row number i
// and chain length l
int j = i + l - 1;
dp[i][j] = INT_MAX;
int fsum = sum(freq, i, j);
// Try making all keys in interval keys[i..j] as root
for (int r = i; r <= j; r++) {
// c = dp when keys[r] becomes root of this subtree
int c = ((r > i) ? dp[i][r - 1] : 0) + ((r < j) ? dp[r + 1][j] : 0) + fsum;
if (c < dp[i][j]) {
dp[i][j] = c;
}
}
}
}
return dp[0][n - 1];
}
int main() {
vector<int> keys = {10, 12, 20};
vector<int> freq = {34, 8, 50};
cout << optimalSearchTree(keys, freq);
return 0;
}
Java
// Java program for implementation of
// optimal binary search tree using tabulation
import java.util.Arrays;
class GfG {
// A utility function to get sum of
// array elements freq[i] to freq[j]
static int sum(int[] freq, int i, int j) {
int s = 0;
for (int k = i; k <= j; k++)
s += freq[k];
return s;
}
// A Dynamic Programming based function that calculates
// minimum cost of a Binary Search Tree.
static int optimalSearchTree(int[] keys, int[] freq) {
int n = keys.length;
// Create an auxiliary 2D matrix to store results
// of subproblems
int[][] dp = new int[n][n];
// dp[i][j] = Optimal cost of binary search tree
// that can be formed from keys[i] to keys[j].
// dp[0][n-1] will store the resultant dp
// For a single key, dp is equal to frequency of the
// key
for (int i = 0; i < n; i++)
dp[i][i] = freq[i];
// Now we need to consider chains of length 2, 3,
// ... l is chain length.
for (int l = 2; l <= n; l++) {
// i is row number in dp[][]
for (int i = 0; i <= n - l; i++) {
// Get column number j from row number i and
// chain length l
int j = i + l - 1;
dp[i][j] = Integer.MAX_VALUE;
int fsum = sum(freq, i, j);
// Try making all keys in interval
// keys[i..j] as root
for (int r = i; r <= j; r++) {
// c = dp when keys[r] becomes root of
// this subtree
int c = ((r > i) ? dp[i][r - 1] : 0)
+ ((r < j) ? dp[r + 1][j] : 0)
+ fsum;
if (c < dp[i][j])
dp[i][j] = c;
}
}
}
return dp[0][n - 1];
}
public static void main(String[] args) {
int[] keys = { 10, 12, 20 };
int[] freq = { 34, 8, 50 };
System.out.println(optimalSearchTree(keys, freq));
}
}
Python
# Python program for implementation of
# optimal binary search tree using tabulation
def sum(freq, i, j):
s = 0
for k in range(i, j + 1):
s += freq[k]
return s
# A Dynamic Programming based function that calculates
# minimum cost of a Binary Search Tree.
def optimalSearchTree(keys, freq):
n = len(keys)
# Create an auxiliary 2D matrix to store results
# of subproblems
dp = [[0] * n for _ in range(n)]
# dp[i][j] = Optimal cost of binary search tree
# that can be formed from keys[i] to keys[j].
# dp[0][n-1] will store the resultant dp
# For a single key, dp is equal to frequency of the key
for i in range(n):
dp[i][i] = freq[i]
# Now we need to consider chains of length 2, 3, ...
# l is chain length.
for l in range(2, n + 1):
# i is row number in dp[][]
for i in range(n - l + 1):
# Get column number j from row number i and
# chain length l
j = i + l - 1
dp[i][j] = float('inf')
fsum = sum(freq, i, j)
# Try making all keys in interval keys[i..j] as root
for r in range(i, j + 1):
# c = dp when keys[r] becomes root of this subtree
c = ((dp[i][r - 1] if r > i else 0) +
(dp[r + 1][j] if r < j else 0) +
fsum)
if c < dp[i][j]:
dp[i][j] = c
return dp[0][n - 1]
keys = [10, 12, 20]
freq = [34, 8, 50]
print(optimalSearchTree(keys, freq))
C#
// C# program for implementation of
// optimal binary search tree using tabulation
using System;
class GfG {
// A utility function to get sum of
// array elements freq[i] to freq[j]
static int Sum(int[] freq, int i, int j) {
int s = 0;
for (int k = i; k <= j; k++)
s += freq[k];
return s;
}
// A Dynamic Programming based function that calculates
// minimum cost of a Binary Search Tree.
static int OptimalSearchTree(int[] keys, int[] freq) {
int n = keys.Length;
// Create an auxiliary 2D matrix to store results
// of subproblems
int[, ] dp = new int[n, n];
// dp[i][j] = Optimal cost of binary search tree
// that can be formed from keys[i] to keys[j].
// dp[0][n-1] will store the resultant dp
// For a single key, dp is equal to frequency of the
// key
for (int i = 0; i < n; i++)
dp[i, i] = freq[i];
// Now we need to consider chains of length 2, 3,
// ... l is chain length.
for (int l = 2; l <= n; l++) {
// i is row number in dp[][]
for (int i = 0; i <= n - l; i++) {
// Get column number j from row number i and
// chain length l
int j = i + l - 1;
dp[i, j] = int.MaxValue;
int fsum = Sum(freq, i, j);
// Try making all keys in interval
// keys[i..j] as root
for (int r = i; r <= j; r++) {
// c = dp when keys[r] becomes root of
// this subtree
int c = ((r > i ? dp[i, r - 1] : 0)
+ (r < j ? dp[r + 1, j] : 0)
+ fsum);
if (c < dp[i, j])
dp[i, j] = c;
}
}
}
return dp[0, n - 1];
}
static void Main(string[] args) {
int[] keys = { 10, 12, 20 };
int[] freq = { 34, 8, 50 };
Console.WriteLine(OptimalSearchTree(keys, freq));
}
}
JavaScript
// JavaScript program for implementation of
// optimal binary search tree using tabulation
// A utility function to get sum of
// array elements freq[i] to freq[j]
function sum(freq, i, j) {
let s = 0;
for (let k = i; k <= j; k++)
s += freq[k];
return s;
}
// A Dynamic Programming based function that calculates
// minimum cost of a Binary Search Tree.
function optimalSearchTree(keys, freq) {
let n = keys.length;
// Create an auxiliary 2D matrix to store results
// of subproblems
let dp
= Array.from({length : n}, () => Array(n).fill(0));
// dp[i][j] = Optimal cost of binary search tree
// that can be formed from keys[i] to keys[j].
// dp[0][n-1] will store the resultant dp
// For a single key, dp is equal to frequency of the key
for (let i = 0; i < n; i++)
dp[i][i] = freq[i];
// Now we need to consider chains of length 2, 3, ...
// l is chain length.
for (let l = 2; l <= n; l++) {
// i is row number in dp[][]
for (let i = 0; i <= n - l; i++) {
// Get column number j from row number i and
// chain length l
let j = i + l - 1;
dp[i][j] = Number.MAX_VALUE;
let fsum = sum(freq, i, j);
// Try making all keys in interval keys[i..j] as
// root
for (let r = i; r <= j; r++) {
// c = dp when keys[r] becomes root of this
// subtree
let c
= ((r > i ? dp[i][r - 1] : 0)
+ (r < j ? dp[r + 1][j] : 0) + fsum);
if (c < dp[i][j])
dp[i][j] = c;
}
}
}
return dp[0][n - 1];
}
// Driver Code
let keys = [ 10, 12, 20 ];
let freq = [ 34, 8, 50 ];
console.log(optimalSearchTree(keys, freq));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem