Knuth's Optimization¶
Knuth's optimization, also known as the Knuth-Yao Speedup, is a special case of dynamic programming on ranges, that can optimize the time complexity of solutions by a linear factor, from
Conditions¶
The Speedup is applied for transitions of the form
Similar to divide and conquer DP, let
We can show that it is true when the cost function
This result is proved further below.
Algorithm¶
Let's process the dp states in such a way that we calculate
Generic implementation¶
Though implementation varies, here's a fairly generic example. The structure of the code is almost identical to that of Range DP.
int solve() {
int N;
... // read N and input
int dp[N][N], opt[N][N];
auto C = [&](int i, int j) {
... // Implement cost function C.
};
for (int i = 0; i < N; i++) {
opt[i][i] = i;
... // Initialize dp[i][i] according to the problem
}
for (int i = N-2; i >= 0; i--) {
for (int j = i+1; j < N; j++) {
int mn = INT_MAX;
int cost = C(i, j);
for (int k = opt[i][j-1]; k <= min(j-1, opt[i+1][j]); k++) {
if (mn >= dp[i][k] + dp[k+1][j] + cost) {
opt[i][j] = k;
mn = dp[i][k] + dp[k+1][j] + cost;
}
}
dp[i][j] = mn;
}
}
return dp[0][N-1];
}
Complexity¶
A complexity of the algorithm can be estimated as the following sum:
As you see, most of the terms in this expression cancel each other out, except for positive terms with
rather than
On practice¶
The most common application of Knuth's optimization is in Range DP, with the given transition. The only difficulty is in proving that the cost function satisfies the given conditions. The simplest case is when the cost function
Note that more than the conditions on the dp transition and the cost function, the key to this optimization is the inequality on the optimum splitting point. In some problems, such as the optimal binary search tree problem (which is, incidentally, the original problem for which this optimization was developed), the transitions and cost functions will be less obvious, however, one can still prove that
Proof of correctness¶
To prove the correctness of this algorithm in terms of
assuming the given conditions are satisfied.
Lemma
Proof
The proof for this lemma uses strong induction. It has been taken from the paper Efficient Dynamic Programming Using Quadrangle Inequalities, authored by F. Frances Yao, which introduced the Knuth-Yao Speedup (this particular statement is Lemma 2.1 in the paper). The idea is to induct on the length
-
The inequality reduces to-
If
Note thatTherefore,
From the induction hypothesis,
-
If
-
-
Let-
If
where
Using the QI on
-
If
-
This completes the proof of the lemma.
Now, consider the following setup. We have 2 indices
Suppose we show that
Setting
Now, using the QI on some indices
Finally,
This proves the first part of the inequality, i.e.,
This completes the proof.