File tree 1 file changed +8
-3
lines changed
1 file changed +8
-3
lines changed Original file line number Diff line number Diff line change @@ -115,9 +115,14 @@ def find_optimal_binary_search_tree(nodes):
115
115
dp [i ][j ] = sys .maxsize # set the value to "infinity"
116
116
total [i ][j ] = total [i ][j - 1 ] + freqs [j ]
117
117
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 ):
121
126
left = dp [i ][r - 1 ] if r != i else 0 # optimal cost for left subtree
122
127
right = dp [r + 1 ][j ] if r != j else 0 # optimal cost for right subtree
123
128
cost = left + total [i ][j ] + right
You can’t perform that action at this time.
0 commit comments