Introduction to dynamic programming (DP)

Dynamic programming (DP) is a technique for optimizing problems that can be divided into smaller, overlapping subproblems with optimal substructure. This lesson combines theory, visualization of DP states and interactive examples to make the concept easier for students to understand.


1. Overlapping subproblems and optimal substructure

Every problem we solve with DP has two key properties:

  • Optimal substructure: the optimal solution of the whole problem can be obtained from the optimal solutions of its subproblems.
  • Overlapping subproblems: the same subproblem appears several times; by storing the results we avoid repeated computations.

A visual example: the Fibonacci sequence


// Fib(5) recursively:
// fib(5)
// ├─ fib(4)
// │  ├─ fib(3)
// │  │  ├─ fib(2)
// │  │  └─ fib(1)
// │  └─ fib(2) <- this repeats
// └─ fib(3) <- this repeats

Note: memoization prevents computing the same nodes of the recursion tree more than once.


2. Top-down (memoization) vs bottom-up (tabulation)

Top-down: recursion + storing the results of subproblems in an array or a map.


int fib(int n, vector& memo) {
    if(n <= 1) return n;
    if(memo[n] != -1) return memo[n];
    memo[n] = fib(n-1, memo) + fib(n-2, memo);
    return memo[n];
}

Bottom-up: we build the solutions iteratively from the smallest subproblems to larger ones, without recursion.


int fibTab(int n) {
    vector dp(n+1);
    dp[0] = 0; dp[1] = 1;
    for(int i=2; i<=n; ++i)
        dp[i] = dp[i-1] + dp[i-2];
    return dp[n];
}

Visualizing tabulation: dp array = [0, 1, 1, 2, 3, 5]


3. Simple practice examples

3.1 The number of ways to climb a staircase


// DP array dp[i] = the number of ways to climb to the i-th step
dp[0] = 1;
dp[1] = 1;
for i = 2 do N:
    dp[i] = dp[i-1] + dp[i-2];

Visualization for N = 5: dp = [1, 1, 2, 3, 5, 8]

3.2 Maximum subarray sum


// dp[i] = the maximum sum of a subarray ending at the i-th element
dp[0] = nums[0];
for i = 1 to n-1:
    dp[i] = max(nums[i], dp[i-1] + nums[i]);
maxSum = max(dp[0..n-1]);

Visualization: nums = [3, -1, 4, -2, 5] → dp = [3, 2, 6, 4, 9]


4. Practice suggestions (interactive)

  • Compute the number of ways to climb a staircase of 10 steps using memoization and tabulation.
  • Find the maximum subarray sum of the array {3, -1, 4, -2, 5}.
  • Write a DP function for the minimum number of coins needed to make a given amount (the Coin Change problem).
  • Show the dp array visually for every step of the algorithm (you can use print or the console).

5. Additional resources


The page for this lesson: /uvod_u_dp.html

Dynamic programming examples — national competition level

In this section we show two typical problems for students in grade 8 or the first year of high school, solved with dynamic programming (DP) in C++. Each example contains a step-by-step explanation, the DP array and the implementation.


Example 1 — The number of ways to climb a staircase (Staircase problem)

Task: You have N steps. You can climb 1 or 2 steps in one move. Compute the number of different ways to climb to the top.

Analysis of the problem:

  • To reach the i-th step, you can come from the (i-1)-th step or the (i-2)-th step.
  • Overlapping subproblems: the number of ways for (i-1) and (i-2) is reused for a larger i.
  • Optimal substructure: the number of ways for i depends only on the previous two solutions.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int N;
    cout << "Enter the number of steps: ";
    cin >> N;

    if(N == 0) { cout << 0; return 0; }

    vector<int> dp(N+1);
    dp[0] = 1;  // 1 way to stay on the ground
    dp[1] = 1;  // 1 way to climb the first step

    for(int i = 2; i <= N; i++) {
        dp[i] = dp[i-1] + dp[i-2];
    }

    cout << "Number of ways: " << dp[N] << endl;
    return 0;
}

Explanation: - dp[i] stores the number of ways to reach the i-th step. - Initial conditions dp[0] = 1, dp[1] = 1. - We compute iteratively dp[i] = dp[i-1] + dp[i-2]. - In the end dp[N] contains the final number of ways.


Example 2 — Maximum subarray sum

Task: An array of integers is given. Find the sum of the largest contiguous subarray.

Analysis of the problem:

  • dp[i] = the maximum sum of a subarray ending at the i-th element.
  • Optimal substructure: dp[i] depends only on dp[i-1] and the current element.
  • Overlapping subproblems: every sum uses the previous solution dp[i-1].

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> nums = {3, -1, 4, -2, 5};
    int n = nums.size();

    vector<int> dp(n);
    dp[0] = nums[0];
    int maxSum = dp[0];

    for(int i = 1; i < n; i++) {
        dp[i] = max(nums[i], dp[i-1] + nums[i]);
        maxSum = max(maxSum, dp[i]);
    }

    cout << "Maximum subarray sum: " << maxSum << endl;
    return 0;
}

Explanation: - For the first element dp[0] = nums[0]. - For every next element dp[i] = max(nums[i], dp[i-1] + nums[i]) — we choose whether to start a new subarray or continue the previous one. - The maximum value in the dp array is the sum we are looking for.


These examples cover the basic DP techniques: the number of ways (overlapping and optimal substructure) and the maximum subarray sum (iterative tabulation). Such problems often appear at national competitions and prepare students for more complex DP tasks.

Example 3 — The number of ways to make a sum (Coin Change)

Task: An array of coins of different values and a total sum S are given. Find in how many different ways the sum S can be made using the coins. Each coin can be used many times.

Analysis of the problem:

  • Overlapping subproblems: the number of ways to make the sum S depends on the number of ways for smaller sums.
  • Optimal substructure: for each sum we can add a coin and combine the previous solutions.
  • The DP array dp[i] stores the number of ways to make the sum i.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, S;
    cout << "Enter the number of coin types: ";
    cin >> n;
    vector<int> coins(n);
    cout << "Enter the coin values: ";
    for(int i = 0; i < n; i++) cin >> coins[i];

    cout << "Enter the sum: ";
    cin >> S;

    vector<int> dp(S+1, 0);
    dp[0] = 1;  // there is 1 way to make the sum 0

    for(int i = 0; i < n; i++) {
        for(int s = coins[i]; s <= S; s++) {
            dp[s] += dp[s - coins[i]];
        }
    }

    cout << "Number of ways to make the sum " << S << ": " << dp[S] << endl;
    return 0;
}

Explanation:

  • dp[0] = 1 because there is only one way to take no coins.
  • For each coin coins[i] we go through all sums from coins[i] to S.
  • For the sum s, we add the number of ways dp[s - coins[i]], because if we complete that sum with this coin, we get a new combination.
  • In the end, dp[S] contains the total number of different combinations that give the sum S.

This task introduces students to **DP with several moves** and **the combinatorics of combinations**, a common type of problem at national competitions.

Limitations of dynamic programming (DP)

Dynamic programming is a powerful technique for solving optimization and combinatorial problems, but it is not a universal solution. There are situations where DP cannot be applied or can be inefficient. Below are the most important limitations of DP that students should understand.

  • No overlapping subproblems – If the subproblems do not repeat (as in the “divide and conquer” approach), DP brings no saving; classic recursion or another algorithm is often faster.
  • No optimal substructure – DP relies on the fact that the optimal solution can be obtained by combining optimal solutions of subproblems. If that does not hold (e.g. problems where a local optimum leads to a globally bad solution), DP will not work.
  • Memory use can be large – DP tables can have thousands or millions of states. For problems with two or more dimensions, memory grows quickly (e.g. DP[n][sum]).
  • Too many states – If the number of states is huge (e.g. hundreds of thousands or more), the running time becomes unusable, even if each step is O(1).
  • States are hard to define – For some problems it is hard to define clear DP states or the transitions between them. Often the very attempt to build a DP formulation can be more complex than the problem itself.
  • Inefficient for problems with continuous values – DP usually works on discrete states. If the problem involves real numbers, the range can be infinite and DP becomes impractical.
  • Complex transitions – If the transitions between states are too expensive (e.g. each state requires iterating through 1000 others), the DP formula becomes slow and infeasible.

Understanding these limitations helps students recognize when DP is the right solution and when other techniques should be used, such as heuristics, greedy approaches, graph algorithms or recursive “divide and conquer”.

DP vs. Greedy vs. Divide & Conquer

A short overview of the most important differences between these three key techniques for solving algorithmic problems. The table helps students choose the right approach depending on the structure of the problem.

Technique When it is used Advantages Disadvantages Example problems
Dynamic programming (DP) Problems with overlapping subproblems and optimal substructure. – optimal solutions
– good for combinatorial problems
– solves complex tasks such as schedules and paths
– sometimes a lot of memory
– states are hard to define
– slower than greedy methods
Fibonacci, Knapsack, LCS, shortest paths (DAG)
Greedy algorithms Problems where a local optimum leads to a globally optimal solution. – very fast (often O(n log n) or better)
– simple to implement
– a good approximation when the optimum is not possible
– do not always guarantee optimality
– require a special problem structure
Kruskal, Prim, Huffman, Activity Selection
Divide & Conquer Problems that can be divided into mutually independent subproblems. – efficient solving of large problems
– uses parallelism
– often very elegant solutions
– does not help if the subproblems overlap (then DP wins)
– sometimes complicated recursion
MergeSort, QuickSort, binary search, FFT

Time and space complexity in dynamic programming

Dynamic programming allows a significant speed-up of algorithms, but it often comes with increased memory use. Understanding the complexity and the ways to optimize it is key to applying DP to real problems.

Time complexity

The time complexity of DP algorithms is usually proportional to the number of states and the number of transitions between them. In the most common applications, the complexity is:

  • O(n) — the simplest linear DP (e.g. Fibonacci in the iterative version)
  • O(n · k) — problems where each state has a limited number of transitions
  • O(n²) or more — typical for problems with segments, intervals, matrices

Space complexity

The space complexity of DP depends on the size of the DP table. Often:

  • O(n) — for optimized linear DP models
  • O(n · k) — for combinatorial and knapsack variants
  • O(n²) — for DP over intervals or 2D subproblems

Tips for optimizing DP algorithms

1. Iterative tabulation instead of recursion with memoization

When possible, use an iterative bottom-up implementation. It is faster, more efficient and avoids problems such as excessive stack depth.

2. Reducing memory (space optimization)

Many DP models do not need the whole table — only the last row or the last two rows. Typical examples:

  • Fibonacci — from O(n) to O(1)
  • Knapsack — reduce the 2D table to a 1D array
  • LCS/LIS — partial memory reduction

3. Testing on large inputs

Before applying a DP solution to competition or real data, check:

  • whether the DP table fits into memory (especially for 2D matrices)
  • how many transitions per state there are
  • whether modular arithmetic is needed for large numbers

4. Recognizing unnecessary states

A DP table often contains more states than are really needed. Before removing memory, identify which states are really reachable or useful.

5. State compression and optimizing transitions

For more complex problems (e.g. DP over bitmasks), memory can be reduced by encoding the states with fewer bits or using more efficient structures.

Understanding these principles makes it possible to apply dynamic programming to very large problems too, without slowing down the program or using too much memory.

Hidden mini quiz — dynamic programming (DP)

Click to check your knowledge of DP basics, memoization and tabulation!

Open the quiz

Mini quiz: do you understand the basics of DP?

1. Which two properties must a problem have to be solved with the DP technique?




2. What is the basic difference between the top-down and bottom-up approaches?




3. For the array {3, -1, 4, -2, 5}, which dp array corresponds to the maximum subarray sum step by step?




4. How many ways are there to climb 5 steps if you go 1 or 2 steps at a time?




5. What is the main goal of memoization?







Mini tasks to do on your own

  1. Compute the number of ways to climb 10 steps using the top-down approach.
  2. Find the maximum subarray sum of the array {1, 2, -3, 4, 5, -2} using bottom-up tabulation.
  3. Write a DP function that returns the number of ways to reach the sum 7 using dice (numbers 1–6).
  4. Implement memoization for the Fibonacci sequence up to n = 20 and compare the time with plain recursion.
  5. For the array {3, 34, 4, 12, 5, 2} implement a DP algorithm for the subset sum problem.
  6. Make a dp table for the knapsack problem (0/1 Knapsack) for small weights and values.
  7. Find the LCS of the strings "ABCD" and "ACBAD".

Task 8: Profitable jumps — an application of dynamic programming


□ This example is inspired by the task “Profitable jumps” from the Junior Serbian Olympiad in Informatics 2025/2026. The original task text is available at: takprog.petlja.org

This task is a very nice example of how classic dynamic programming can be optimized using suffix maximums.

At first glance it seems that for each square we have to check a large number of possible jumps and different paths through the game. However, with a well-defined DP state and an additional auxiliary array, a very efficient solution is possible.

A player is on a straight track consisting of N squares numbered from 1 to N.

Two arrays of integers are given:

  • A of length N - 1
  • B of length N

The number B[i] is the amount of money the player gets when at some moment they are on square i.

From square i the player has two options:

  • to end the game on that square
  • or, if a jump is allowed, to move to some square j for which: A[i] ≤ j ≤ N

From every square except the last one, a jump is possible only to a square with a strictly larger number.

Formally, for every:


1 ≤ i < N

we have:


i < A[i] ≤ N

From square N the player can only end the game.

Q queries are given. Each query gives a starting position x.

For each query, find the largest possible amount of money the player can collect starting from square x.

The player also gets the money for the starting square.


Input

The first line contains the numbers:


N Q

The second line contains the array:


A1 A2 ... A(N-1)

The third line contains the array:


B1 B2 ... BN

Each of the next Q lines contains one number:


x

which is the starting square for the corresponding query.


Output

For each query print the maximum amount of money the player can collect.


Constraints


2 ≤ N ≤ 200000
1 ≤ Q ≤ 200000

i < A[i] ≤ N

-10^9 ≤ B[i] ≤ 10^9
1 ≤ x ≤ N

The large constraints immediately suggest that an O(N²) solution will not be fast enough, so an optimization has to be found.


Example


Input:
5 2
3 5 5 5
2 -1 3 4 5
1
2

Output:
11
4

Explanation of the example

If the player starts from square 1, the best is:


1 -> 4 -> 5

Then the total is:


2 + 4 + 5 = 11

If the player starts from square 2, they can only jump to square 5, so the maximum earnings are:


-1 + 5 = 4

Recommended resources for learning dynamic programming

For a deeper understanding of DP techniques, it is useful to learn from different formats: text tutorials, video lessons and interactive platforms. Here are carefully selected quality resources that cover both basic and advanced topics.

Text tutorials and articles

Video lectures

Interactive platforms

Recommended books

Exploring these resources will help students broaden their knowledge of dynamic programming and gain confidence in solving different problems.