AlgoTales · Roadmap

Interval DP

Advanced · 13 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Interval DP solves problems on a stretch of a sequence by solving smaller stretches inside it first. A typical question is "if this item is the last one handled in the stretch, what is the best result?". It fits problems where removing or combining items changes who their neighbours are.

Practical use cases

  • Web app: Balloon-bursting game scoring. A mobile game has a row of balloons with numbers, and popping one scores its number times its two neighbours. The designers want the maximum possible score for each level. They compute the best score for every stretch of balloons, short stretches first, and the answer for the full row is the cap players see.
  • Web app: Merging files in the cheapest order. A file tool merges a row of chunks, where each merge costs the combined size. The cost depends on which neighbours are merged first. Trying every last merge for each stretch of chunks finds the cheapest plan. Planners then see the cheapest plan and total cost, and can reuse the same table when a new chunk arrives, instead of starting again.
  • System: Parsing and optimal search trees. Parsers decide how to group words or symbols into sentences by testing every split of a stretch. Databases build search trees that minimise lookups by trying every possible root for each range.

The story: Balloons at the Mela

At the village mela, Raju ran a balloon game. Four balloons hung in a row with numbers 3, 1, 5, 8. Burst a balloon and you win (number on its left) × (its own number) × (number on its right) coins; beyond the ends the "number" is 1. After a burst, its neighbours become neighbours of each other. Burst all four to collect the most coins.

Kabir tried bursting the biggest first. Fewer coins than expected! The trouble: after each burst the neighbours change, so the choices tangle up. Mira found a way to untangle them: think about the LAST balloon to burst in a range. When it goes last, its two neighbours are the fixed walls of the range, and everything inside the left side and inside the right side was burst earlier, independently of each other.

So for every range of balloons, try each balloon as the last one: coins = walls × it, plus the best of the left part, plus the best of the right part. Short ranges first, then longer. The whole row gave 167 coins. Any problem solved by "best answer for every stretch, built from shorter stretches" is called Interval DP.

How to spot this problem, and where you need it

Your answer depends on a continuous stretch of a list, and handling one item changes which items become neighbours, so you cannot decide from left to right.

Signs you need it

  • The problem says "burst", "merge" or "remove" items from a row, and the cost depends on the neighbours at that moment.
  • Cutting or merging a stretch splits it into a left part and a right part that can be solved independently.
  • A greedy approach of always taking the cheapest item at the moment gives a wrong total.

Where to use it in a project

  • Game scoring, merge-cost planning and cutting problems on a row of items.
  • Parsing and grouping features where every split point of a phrase must be considered.

The solution

Make a table indexed by the start and end of a stretch. Solve stretches of length 1 first, then 2, then 3, and so on. For each stretch, try every item k as the last one handled: the score is the best of the left part, plus the best of the right part, plus the value of handling k last, when only the stretch edges remain as its neighbours. Keep the best. The cell for the whole row is the answer.

Payoff: Before: trying every popping order, 3.6 million for 10 balloons. After: a table of about 100 cells.

Explain it like I am 8

Think of a stretch of the row as a small box. Ask: "If this balloon is the last one left in my box, what is the best score?" Everything left of it and right of it were popped earlier in their own smaller boxes. You build bigger boxes out of smaller boxes.

How it works, step by step

  1. Pad the row with an imaginary balloon of 1 on both ends.
  2. dp[i][j] = most coins from bursting all balloons between positions i and j.
  3. Process ranges by length: 1, 2, 3... so shorter ranges are ready.
  4. For each range try every balloon k as the last burst: coins(left wall, k, right wall) + dp[i][k-1] + dp[k+1][j].
  5. The best over all k is the cell; the answer is the cell for the whole row.

The code in four languages

PHP

<?php
// Burst balloons for the most coins. Bursting k pays left * k * right.
function maxCoins(array $nums): int {
    $a = array_merge([1], $nums, [1]);              // imaginary balloons of 1 at both ends
    $n = count($nums);
    // dp[i][j]: best for the real balloons i..j (1-based in $a); empty ranges count 0
    $dp = array_fill(0, $n + 2, array_fill(0, $n + 2, 0));
    for ($len = 1; $len <= $n; $len++) {             // range length, short to long
        for ($i = 1; $i + $len - 1 <= $n; $i++) {
            $j = $i + $len - 1;
            for ($k = $i; $k <= $j; $k++) {           // k is the LAST balloon to burst in i..j
                $coins = $a[$i - 1] * $a[$k] * $a[$j + 1] + $dp[$i][$k - 1] + $dp[$k + 1][$j];
                $dp[$i][$j] = max($dp[$i][$j], $coins);
            }
        }
    }
    return $dp[1][$n];
}
echo maxCoins([3, 1, 5, 8]), "\n";                  // 167

JavaScript

// Burst balloons for the most coins. Bursting k pays left * k * right.
function maxCoins(nums) {
  const a = [1, ...nums, 1];                        // imaginary balloons of 1 at both ends
  const n = nums.length;
  // dp[i][j]: best for the real balloons i..j (1-based in a); empty ranges count 0
  const dp = Array.from({ length: n + 2 }, () => new Array(n + 2).fill(0));
  for (let len = 1; len <= n; len++) {              // range length, short to long
    for (let i = 1; i + len - 1 <= n; i++) {
      const j = i + len - 1;
      for (let k = i; k <= j; k++) {                // k is the LAST balloon to burst in i..j
        const coins = a[i - 1] * a[k] * a[j + 1] + dp[i][k - 1] + dp[k + 1][j];
        dp[i][j] = Math.max(dp[i][j], coins);
      }
    }
  }
  return dp[1][n];
}
console.log(maxCoins([3, 1, 5, 8]));                // 167

Java

public class Main {
    // Burst balloons for the most coins. Bursting k pays left * k * right.
    static int maxCoins(int[] nums) {
        int n = nums.length;
        int[] a = new int[n + 2];                       // imaginary balloons of 1 at both ends
        a[0] = 1;
        a[n + 1] = 1;
        for (int i = 0; i < n; i++) a[i + 1] = nums[i];
        // dp[i][j]: best for the real balloons i..j (1-based in a); empty ranges count 0
        int[][] dp = new int[n + 2][n + 2];
        for (int len = 1; len <= n; len++) {             // range length, short to long
            for (int i = 1; i + len - 1 <= n; i++) {
                int j = i + len - 1;
                for (int k = i; k <= j; k++) {           // k is the LAST balloon to burst in i..j
                    int coins = a[i - 1] * a[k] * a[j + 1] + dp[i][k - 1] + dp[k + 1][j];
                    dp[i][j] = Math.max(dp[i][j], coins);
                }
            }
        }
        return dp[1][n];
    }

    public static void main(String[] args) {
        System.out.println(maxCoins(new int[]{3, 1, 5, 8}));   // 167
    }
}

Go

package main

import "fmt"

// maxCoins: burst balloons for the most coins. Bursting k pays left * k * right.
func maxCoins(nums []int) int {
	a := append([]int{1}, nums...) // imaginary balloons of 1 at both ends
	a = append(a, 1)
	n := len(nums)
	// dp[i][j]: best for the real balloons i..j (1-based in a); empty ranges count 0
	dp := make([][]int, n+2)
	for i := range dp {
		dp[i] = make([]int, n+2)
	}
	for length := 1; length <= n; length++ { // range length, short to long
		for i := 1; i+length-1 <= n; i++ {
			j := i + length - 1
			for k := i; k <= j; k++ { // k is the LAST balloon to burst in i..j
				coins := a[i-1]*a[k]*a[j+1] + dp[i][k-1] + dp[k+1][j]
				dp[i][j] = max(dp[i][j], coins)
			}
		}
	}
	return dp[1][n]
}

func main() {
	fmt.Println(maxCoins([]int{3, 1, 5, 8})) // 167
}

Time: O(n³) · Extra space: O(n²). n² ranges, each trying up to n choices for the last balloon.

Watch out for

  • Thinking about the FIRST balloon to burst: its neighbours change afterwards and the two sides are no longer independent.
  • Forgetting the padding balloons of 1 at both ends.
  • Filling by start index instead of by range length, so inner ranges are not ready.

Quick check

  1. Why choose the LAST balloon in a range?
    • It makes the two sides independent
    • It is always the largest
    • It is easier to loop
  2. What order do we fill ranges in?
    • Longest first
    • Shortest first
    • Random
  3. Best score for balloons [3, 1, 5, 8]?
    • 167
    • 40
    • 315