Skip to content

Commit e12456d

Browse files
committed
Add boundary checking to optimal bst
1 parent 9a572de commit e12456d

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

Diff for: dynamic_programming/optimal_binary_search_tree.py

+8-3
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,14 @@ def find_optimal_binary_search_tree(nodes):
115115
dp[i][j] = sys.maxsize # set the value to "infinity"
116116
total[i][j] = total[i][j - 1] + freqs[j]
117117

118-
# Apply Knuth's optimization
119-
# Loop without optimization: for r in range(i, j + 1):
120-
for r in range(root[i][j - 1], root[i + 1][j] + 1): # r is a temporal root
118+
# Apply Knuth's optimization with boundary checking
119+
r_start = max(i, root[i][j - 1] if j > i else i)
120+
r_end = min(j, root[i + 1][j] if i < j else j)
121+
122+
if r_start > r_end:
123+
r_start, r_end = i, j # fall back to the full range
124+
125+
for r in range(r_start, r_end + 1):
121126
left = dp[i][r - 1] if r != i else 0 # optimal cost for left subtree
122127
right = dp[r + 1][j] if r != j else 0 # optimal cost for right subtree
123128
cost = left + total[i][j] + right

0 commit comments

Comments
 (0)