Mariano Crosetti
  • Dynamic Programming
  • Divide And Conquer
  • Competitive Programming
  • Technical Interview
  • Algorithms

Dynamic Programming amazing tricks! — Part III.c— All you need about DP optimizations — Knapsack DP on trees!

This is the second article of Part III. In this part, I will present some popular DP optimizations. I will explain them with a problem example as they are hard-to-understand topics. And give an intuition to recognize scenarios where they might be applicable.

Part III will consist of three sub-articles: (a) Knuth optimization, (b) D&C optimization (this one), and (c) Knapsack on trees.

Motivation

This series of guides will be helpful for you if you are:

  • preparing coding interviews.
  • training for competitive programming.
  • just want to learn how to develop ideas to solve dynamic programming problems.

I assume that you have read the last parts.

In this article, I aim to explain popular “DP optimization tricks”: advanced artifices that reduce time complexity. I will focus on providing insights so you can recognize DP’s formulas that can be optimized with them.

Also, in this chapter, I will explain how to come up with the idea of the optimization trick. This is very important when training our problem-solving skills: to think about how the chain of thought could have been the technique’s inventor to come up with it. After all, if we aim to be great problem-solvers, we must be able to come up with our original techniques and ideas.

As I said in past articles, you will only truly understand it once you practice the ideas. So, I put the homework section with exercises in it again.

Finally, remember this article’s content is more advanced than the previous ones, so don’t be demotivated if you don’t understand the concepts in the first read.

D&C optimization trick

Introduction

Motivational problem: N people in a queue are waiting to get into K ships. Each ship has an arbitrarily large capacity. (N ≤ 4000, K ≤ 800). We have a symmetric square matrix of size N x N. In each entry uₓᵧ, we have how much discomfort person x feels being in the same boat with person y. We have to assign the people to ships, respecting the order of the queue: we can start filling a ship with the people from the queue in order and decide when we should stop using that ship and start using an empty one.
Let’s call the discomfort of a ship the sum of the discomfort of a pair of people inside that boat. We want to minimize the total discomfort, which is defined as the sum of each boat’s discomfort.
For example, if N = 3, K = 2 and we have the following discomfort matrix:

The pair of people (1st,2nd) feels 2 of disconfort being toghether and the pair of people (2nd, 3rd) feel 3 of disconfort being togheter.

The answer is 2: as we have only two ships, at least a pair of people must be together. As the pair of consecutive people with the most minor discomfort is (1st, 2nd), we will put them in a ship. And 3rd in another boat. Notice that we can’t put (1st, 3rd) in a ship and 2nd in another boat because we have to respect the other of the queue (that would be convenient as the discomfort of this pair is 0).

Other example: if we have N = 5 and K = 2 and the following discomfort matrix:

The optimal solution is to put the first two people on a ship and the rest on another boat. Notice that by doing this, we get 0 of total discomfort.

First attempt

We start filling the first ship. We can put 1, 2, 3 … people there. How do we know which is the optimal decision? We are in a DP tutorial so we will try all the alternatives! For each alternative, we can calculate the ship’s discomfort by summing the discomfort of the people there and then call the function recursively: we will have a list of people and a certain amount of ships again.

With the last idea, we can write a recursive function f(k, i) that calculates the minimum total discomfort for specific suffix of people [i, N) by having k boats:

Then, the answer can be obtained by calling f(K,0). Note: C[i,j] is the boat's discomfort by putting all the consecutive people from position i to j into a ship. We can calculate it in O(1) by precalculating O(N²) with 2D range sum queries.

From Part I, we know that if we have a recursive function, we can pass it to a “Top-Down” DP implementation by memorizing the states and obtaining the complexity:

This gives us a resultant complexity of O(K N²).

A key observation

How can we make it better? As we did with Knuth optimization, the trick consists of narrowing down the loop we are doing. Let’s call opt[k][i] to the minimum j, which is optimum for f(k, i). In other words, j holds:

For this particular problem, it verifies that:

opt[k][i] is monotonous at i: when we increase i, the optimal split never move left.

These are the criteria that will allow us to apply D&C Trick:

“D&C condition" or “D&C criteria"

It expresses that:

  • opt[k][i] is monotonous at i (for a fixed k)
  • In other words, for a fixed k, the optimal position to split the group is not greater than the optimal position for any sub-suffix (a shorter suffix).

Optimizing our solution

Notice that for different k, the opt[k][i] are not related. This could suggest we should compute independently for each k. As dp[k][i] is based on_
dp[k-1][j]_, it’s natural to think we should calculate by increasing the k order.

How we will limit the min i < j ≤ N loop inside the formula of dp[k][i] ? Notice that the “D&C criteria” are different from the “Knuth criteria” seen in the last chapter: here, the opt[k][i] is only limited by an upper bound of a smaller substate.

A thinking strategy for recursive solutions is to analyze as if we were in the middle of solving a problem, having all the smaller states already calculated and trying to calculate a particular state. It’s good to be as concrete as possible (even maybe with a concrete example!):

  • So we will suppose we have N = 200 people and K = 5 boats.
  • Our final goal is to compute dp[5][0].
  • Let’s suppose we already calculate dp[k][i] for k ≤ 3, and we want to calculate dp[4][i] for every i. This is necesary for our final goal.
  • Notice that we can choose any i: we don’t have to do it in increasing or decreasing order as the formula only depends on dp[3][j] that’s already calculated.
  • Suppose we choose the middle as the first i (i = 100), as we don’t know if it’s better to start calculating for i = 0 or i = 200.
  • We can calculate dp[4][100] with the given formula (iterating
    100 < j ≤ 200 ). This is O(N). We don’t want to do O(N) for every i, because that will result in O(K N²).
    But notice that when we calculate dp[4][100], we can calculate
    opt[4][100] trivially: it’s the j that reach the minimum in the for loop we’ve done. This value will be useful for calculating the others dp[4][i] because it give us some constraint for the remaining dp[4][i] :
opt[4][100] set respectively an upper bound and lower bound for opt[4][i₁] and opt[4][i₂] for 0 ≤ i₁ ≤ 100 ≤ i₂ ≤ n.
  • Now we will have to calculate dp[4][i₁] for i₁ ∈ [0,99] and i₂ ∈ [101,199]. We can do it recursively (this has the smell of D&C!). Notice that the values across which we have to iterate j for calculating dp[4][i] are split by opt[4][100]. This definitely has the smell of D&C!

The D&C trick

We will create a function compute(k, L, R, optL, optR) that will:

  • Calculate dp[k][i] for every i ∈ [L, R]
  • It will assume that dp[k - 1][i] is already calculated.
  • It will assume that opt[k][L..R] is between [optL..optR].

Then we will do:

for(int k = 1 ; k<K ; k++) { 
    compute(k, 0, N, 0, N)
}

compute(k, L, R, optL, optR) is relatively straightforward: we will generalize what we did when calculating dp[4][i] in the analyzed example:

  1. If L = R, we calculate the formula by hand
    (by iterating through optL ≤ j ≤ optR).
  2. If not, we will set M = (L+R) / 2 and calculate dp[k][M] (and opt[k][M]) by iterating through optL ≤ j ≤ optR.
  3. We will then recursively call:
    a. compute(k, L, M-1, optL, opt[k][M])
    b. compute(k, M, R, opt[k][M], optR)

The code:

// It's a conceptual code, I did not test it in a problem. Use it by your own risk

void compute(int L, int R, int optL, int optR){
    if (L > R || optL > optR) 
      return;
    
    int mid = (L + R) >> 1;
    int current_opt_pos = L;
    dp[k][mid] = cost[mid][mid] + dp[k-1][mid+1];
      
    for(int j = max(mid,optL) ; j < optR ; j++){
        int current_cost = precomputed_cost[mid][j] + dp[k-1][j+1];
        if (current_cost < dp[k][mid]) {
          dp[k][mid] = current_cost
          current_opt_pos = j;
        }
    }
     = 
      
    dp(L, mid-1, optL, current_opt_pos);
    dp(mid, R, current_opt_pos, optR);
}

This is O(K N log N) … what? Why?
Because compute(k, 0, N, 0, N) is O(N log N):

  1. The recursion tree’s height is log(N) because at each time, we split [L,R] by half and we stop recursing when L = R.
  2. Let’s analyze the work done by all the calls from the same height (we will call this set of calls a level):
    Notice that seeing all the level’s call:
    a. The intervals [optL, optR] do not overlap (because we are splitting each time we do recursive calls into non-overlapping intervals).
    b. The work done for each call is O(optR-optL): in both cases, when L = R or when we do recursive calls, we iterate from optL to optR.
    c. So the total work doesn’t exceed O(N): each 0 ≤ j ≤ N is iterated only by one call from the level.
    d. We have a total O(N) work for each level height.

Combining (1) and (2), we demonstrated that the entire recursion tree of compute(k, 0, N, 0, N) is O(N log N) for every k.

Graphically, the compute recursion subtree looks very similar to the merge-sort algorithm. If we set cn = [0,N] in each call, [L, R] is divided by a factor of 2. The recursion tree's height is lg n. The difference with the merge-sort is that the amount of work per function is not [L, R]; it's [optL, optR]. But anyway, as at a certain height, the [optL, optR] intervals partitioned the whole interval [0, N], then the amount of work performed by the calls at a certain height sums up cn. So, same as merge-sort, we have cn.lg n in total.

General case

Notice that the D&C is applied K times (for each K). The general case of the D&C doesn’t depend on K. If we have a function:

Notice that cost(i,j) may depend on a recursive call f(j).

That satisfies opt[i] is monotonous:

"D&C criteria" for the general case.

Then we can apply D&C: computing all f(i) for every i ∈ [0,N] in a recursive way:
We will have to compute(L, R, optL, optR) that will calculate f(i) for i ∈ [L, R]. The implementation is equal to the explained implementation in the last subsection. Each call will compute f(M) and opt[M] for M = (L+R) / 2 by looping optL ≤ j ≤ optR and then do the recursive calls:

  • compute(L, M, optL, opt[M])
  • compute(M, R, opt[M], optR)

Recognizing when “D&C trick” problems

In the last chapter, we saw D&C’s general case. But what does it mean?
In particular, it applies to all the problems where we must partition an interval [0, N] into K subranges. These problems are trivially recursive: if we choose [0, i] as the first partition, we must solve the same problem in the suffix [i+1, N] but make K subranges.
Notice that there could be subtle variations like having prefixes instead of suffixes or if we must divide [0, N] in at most K subranges (instead of at least), etc. That’s why it’s always good to know the idea behind the trick: to adapt when necessary.

Relationship with Knuth optimization trick

By renaming the variables in the “D&C trick criteria,” we get the following:

"D&C criteria" that we saw previously if we rename k, i by i, j respectively.

Let’s remember “Knuth trick criteria”:

“Knuth trick criteria” from the previous blog entry.

Notice that if we have a formula that satisfies “Knuth trick criteria,” it will satisfy “D&C trick criteria” (Knuth applies → D&C applies!). D&C is a more powerful tool (it applies to more cases), but Knuth optimization reduces the complexity by a factor of N, while D&C reduces it by a factor of N / log (N).

So it’s not entirely true that the intuition that “D&C criteria” only applies to suffix-dp-problems; it also applies, for instance, to range problems. Especially all the ones where you can use the “Knuth trick.” Be aware of that!

Homework

Problems for practicing:

And also you can read these other tutorials:

  • Tutorial de Ciels and Gondolas: the technique is very well explained, and there is an intuitive explanation of when to apply it.
  • DP optimization Codeforces: This blog entry lists the conditions the cost function must satisfy to apply the optimization trick. Read the comments; there is essential insight there.
  • DP optimization by CP Algorithm: a great website with great tutorials. Here, you can find more implementations**; at the end of the tutorials, you will find problems.**

About Me

If you liked this post / my style, follow me.

Goodbye long hair, I'm a tech bro again.

I will try to keep on posting regularly about SE, Web, and ML, always with these objectives in mind:

  • keep it short
  • being meaningful
  • explain with examples