State definition
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The state is the exact description of what a table cell or saved answer stands for, such as "best profit using the first i days". Choosing it well is the hardest and most important step in dynamic programming. If the state is clear, the rest almost writes itself.
Practical use cases
- Web app: Stock-style price chart analysis. A trading-practice app shows the best profit from buying and selling over a price history. The developer first decides the state: "best profit up to day i, holding a share or not holding one". Once that sentence is clear, the code is two short lines per day. A vague state like "best so far" would leave the developer stuck.
- Web app: Text editor undo/diff feature. A note-taking app compares two versions of a note to highlight changes. The developer defines the state as "how similar are the first i letters of version A and first j letters of version B". With that exact definition, filling the table is simple and the highlights are correct. Defined loosely as "similar so far", it would be unclear which two positions to compare, and the highlights would be wrong or missing.
- System: Route optimisers. Route planners label each stop with "cheapest cost to arrive here with this much fuel left". Adding the fuel to the label is what makes the problem solvable at all. In each of these tools the hard part is deciding what a table cell stands for, and once that is clear the code that fills the table is usually short.
The story: The Right Question to Ask
Aarav kept a piggy bank and wrote down how many rupees he saved each week: 5, 3, 4, 8, 6, 7, 9. His sister Zoya challenged him: "What is the longest run of weeks, skipping any you like, where your savings keep going up?"
Aarav tried to answer for "the first 5 weeks", then "the first 6 weeks", but he got stuck. Knowing the best run in the first 5 weeks did not tell him whether week 6 could join it. Was the run's last number small enough? His question was missing a piece of information.
Grandpa Bhaskar chuckled. "Change the question. Ask: what is the longest rising run that ends exactly at week i?" Suddenly every week was easy. Look at the earlier weeks that saved less than this one, take the best of their answers, add 1. Each box knew exactly where its run stopped, so it knew whether it could be extended.
That choice, what does one box of my table promise to answer?, is the state definition. In dynamic programming, picking a good state is the most important step. Once the state is right, the rest of the work almost writes itself.
How to spot this problem, and where you need it
You know a problem needs dynamic programming but cannot figure out what to store, or your table answers are not enough to continue the calculation.
Signs you need it
- You wrote a recursive solution and the function arguments change at every call; those arguments are your state.
- Your saved answer sometimes is not enough, because the next step also needs to know something else, like whether you are holding stock or how many items remain.
- You cannot explain in one sentence what a table cell means.
Where to use it in a project
- Designing any optimisation feature such as best price, shortest route, or longest match before coding it.
- Reviewing a teammate's dynamic programming code that nobody understands: ask "what does this cell mean?"
The solution
Write one sentence of the form "dp[...] = the best answer for ... ending here / using the first i items / with k left". List what changes between steps; each changing thing becomes an index. Check that the answer to the big problem can be read from some cell. If the next step needs extra information, add it to the state. Keep the state small, because the table size equals the number of states.
Payoff: Before: hours stuck on a vague idea. After: a clear sentence that makes the table, the loop and the answer obvious in minutes.
Explain it like I am 8
Imagine a treasure hunt where every clue card says "I am the best path that ends HERE." If every card says exactly where it ends, you can glue a new step onto any card. If the cards are vague ("a good path somewhere"), you cannot tell what you can attach.
How it works, step by step
- Say the question in one sentence: "
dp[i]is the answer to ___ for the firstithings / ending at thingi." - Check it carries enough information to build a bigger answer. If you cannot extend it, add what is missing (like "ends at i").
- Check the final answer can be read from the table: the last box, or the biggest box.
- Keep the state small. Every extra thing you track multiplies the table size, so track only what you truly need.
- Only then think about the transition (how boxes are built from earlier boxes).
The code in four languages
PHP
<?php
// State: dp[i] = length of the longest rising run that ENDS exactly at position i.
function longestRise(array $a): array {
$n = count($a);
$dp = array_fill(0, $n, 1); // a run of just one week always exists
for ($i = 1; $i < $n; $i++) {
for ($j = 0; $j < $i; $j++) {
if ($a[$j] < $a[$i]) { // week j can come right before week i
$dp[$i] = max($dp[$i], $dp[$j] + 1);
}
}
}
return $dp;
}
$savings = [5, 3, 4, 8, 6, 7, 9];
$dp = longestRise($savings);
echo implode(" ", $dp), "\n"; // 1 1 2 3 3 4 5
echo "Longest run: ", max($dp), "\n"; // 5 (the answer is the biggest box, not the last)JavaScript
// State: dp[i] = length of the longest rising run that ENDS exactly at position i.
function longestRise(a) {
const n = a.length;
const dp = new Array(n).fill(1); // a run of just one week always exists
for (let i = 1; i < n; i++) {
for (let j = 0; j < i; j++) {
if (a[j] < a[i]) { // week j can come right before week i
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
return dp;
}
const savings = [5, 3, 4, 8, 6, 7, 9];
const dp = longestRise(savings);
console.log(dp.join(" ")); // 1 1 2 3 3 4 5
console.log("Longest run:", Math.max(...dp)); // 5 (the answer is the biggest box, not the last)Java
import java.util.*;
public class Main {
// State: dp[i] = length of the longest rising run that ENDS exactly at position i.
static int[] longestRise(int[] a) {
int n = a.length;
int[] dp = new int[n];
Arrays.fill(dp, 1); // a run of just one week always exists
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (a[j] < a[i]) { // week j can come right before week i
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
return dp;
}
public static void main(String[] args) {
int[] savings = {5, 3, 4, 8, 6, 7, 9};
int[] dp = longestRise(savings);
System.out.println(Arrays.toString(dp)); // [1, 1, 2, 3, 3, 4, 5]
System.out.println("Longest run: " + Arrays.stream(dp).max().getAsInt()); // 5 (the answer is the biggest box, not the last)
}
}Go
package main
import "fmt"
// State: dp[i] = length of the longest rising run that ENDS exactly at position i.
func longestRise(a []int) []int {
n := len(a)
dp := make([]int, n)
for i := range dp {
dp[i] = 1 // a run of just one week always exists
}
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
if a[j] < a[i] { // week j can come right before week i
dp[i] = max(dp[i], dp[j]+1)
}
}
}
return dp
}
func main() {
savings := []int{5, 3, 4, 8, 6, 7, 9}
dp := longestRise(savings)
fmt.Println(dp) // [1 1 2 3 3 4 5]
longest := 0
for _, v := range dp {
longest = max(longest, v)
}
fmt.Println("Longest run:", longest) // 5 (the answer is the biggest box, not the last)
}Time: O(n²) · Extra space: O(n). n boxes, and each box looks back at up to n earlier boxes. A smarter state-free trick exists, but this shows the idea.
Watch out for
- Defining the state too loosely ("best run in the first i weeks"). It forgets how the run ends, so you cannot tell whether a new week fits.
- Assuming the answer is always the last box. With "ends at i" states, scan the whole table for the best.
- Packing too much into the state (extra dimensions you never use). The table grows huge for no benefit.
Quick check
- What is a "state" in dynamic programming?
- The country where the algorithm runs
- The exact question one box of the table answers
- The final output
- Why did "best run in the first i weeks" fail for the rising-savings puzzle?
- It was too short
- It needs sorting
- It does not say how the run ends, so you cannot tell if a new week can join it
- In the demo the dp row is 1 1 2 3 3 4 5. What is the answer?
- 5, the biggest box (which happens to be last here)
- 1
- 28