Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add boundary checking to optimal bst #11771

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions dynamic_programming/optimal_binary_search_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,14 @@ def find_optimal_binary_search_tree(nodes):
dp[i][j] = sys.maxsize # set the value to "infinity"
total[i][j] = total[i][j - 1] + freqs[j]

# Apply Knuth's optimization
# Loop without optimization: for r in range(i, j + 1):
for r in range(root[i][j - 1], root[i + 1][j] + 1): # r is a temporal root
# Apply Knuth's optimization with boundary checking
r_start = max(i, root[i][j - 1] if j > i else i)
r_end = min(j, root[i + 1][j] if i < j else j)

if r_start > r_end:
r_start, r_end = i, j # fall back to the full range

for r in range(r_start, r_end + 1):
left = dp[i][r - 1] if r != i else 0 # optimal cost for left subtree
right = dp[r + 1][j] if r != j else 0 # optimal cost for right subtree
cost = left + total[i][j] + right
Expand Down