Optimal BST Construction - Problem
Given an array of keys and their corresponding search frequencies, construct a Binary Search Tree that minimizes the total search cost.
The search cost for a key is defined as: frequency * (depth + 1), where depth is the level of the node in the BST (root has depth 0).
Your task is to return the minimum possible total search cost for the optimal BST.
Note: Keys are given in sorted order, and all frequencies are positive integers.
Input & Output
Example 1 — Basic Case
$
Input:
keys = [10, 12, 20], frequencies = [34, 8, 50]
›
Output:
168
💡 Note:
Optimal BST has key 20 as root (cost: 50×1=50), key 12 as left child (cost: 8×2=16), and key 10 as left child of 12 (cost: 34×3=102). Total: 50+16+102=168.
Example 2 — Two Keys
$
Input:
keys = [10, 20], frequencies = [34, 50]
›
Output:
118
💡 Note:
With two keys, optimal BST has key 20 as root (cost: 50×1=50) and key 10 as left child (cost: 34×2=68). Total: 50+68=118.
Example 3 — Equal Frequencies
$
Input:
keys = [1, 2, 3], frequencies = [10, 10, 10]
›
Output:
40
💡 Note:
With equal frequencies, optimal BST has key 2 as root (cost: 10×1=10), keys 1 and 3 as children (cost: 10×2 + 10×2=40). Total: 10+40=50.
Constraints
- 1 ≤ keys.length ≤ 100
- keys are sorted in ascending order
- 1 ≤ frequencies[i] ≤ 100
- keys.length == frequencies.length
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code