Steps to solve a Dynamic Programming Problem
Last Updated :
23 Dec, 2024
Steps to solve a Dynamic programming problem:
- Identify if it is a Dynamic programming problem.
- Decide a state expression with the Least parameters.
- Formulate state and transition relationship.
- Apply tabulation or memorization.
Step 1: How to classify a problem as a Dynamic Programming Problem?
- Typically, all the problems that require maximizing or minimizing certain quantities or counting problems that say to count the arrangements under certain conditions or certain probability problems can be solved by using Dynamic Programming.
- All dynamic programming problems satisfy the overlapping subproblems property and most of the classic Dynamic programming problems also satisfy the optimal substructure property. Once we observe these properties in a given problem be sure that it can be solved using Dynamic Programming.
Step 2: Deciding the state
Dynamic Programming problems are all about the state and its transition. This is the most basic step which must be done very carefully because the state transition depends on the choice of state definition you make.
State:
A state can be defined as the set of parameters that can uniquely identify a certain position or standing in the given problem. This set of parameters should be as small as possible to reduce state space.
Example:
Let's take the classic Knapsack problem, where we need to maximize profit by selecting items within a weight limit. Here, we define our state using two parameters: index and weight (dp[index][weight]). Think of it like this: dp[3][10] would tell us "what's the maximum profit we can make by choosing from the first 4 items (index 0 to 3) when our bag can hold 10 units of weight?" These two parameters (index and weight) work together to uniquely identify each subproblem we need to solve.
Just like GPS coordinates need both latitude and longitude to pinpoint a location, our knapsack solution needs both the item range and remaining capacity to determine the optimal profit at each step.
So, our next step will be to find a relation between previous states to reach the current state.
Step 3: Formulating a relation among the states
This part is the hardest part of solving a Dynamic Programming problem and requires a lot of intuition, observation, and practice.
Example:
Given 3 numbers {1, 3, 5}, The task is to tell the total number of ways we can form a number n using the sum of the given three numbers. (allowing repetitions and different arrangements).
The total number of ways to form 6 is: 8
1 + 1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 3
1 + 1 + 3 + 1
1 + 3 + 1 + 1
3 + 1 + 1 + 1
3 + 3
1 + 5
5 + 1
The steps to solve the given problem will be:
- We decide a state for the given problem.
- We will take a parameter n to decide the state as it uniquely identifies any subproblem.
- DP state will look like state(n), state(n) means the total number of arrangements to form n by using {1, 3, 5} as elements. Derive a transition relation between any two states.
- Now, we need to compute state(n).
How to Compute the state?
As we can only use 1, 3, or 5 to form a given number n. Let us assume that we know the result for n = 1, 2, 3, 4, 5, 6
Let us say we know the result for:
state (n = 1), state (n = 2), state (n = 3) ......... state (n = 6)
Now, we wish to know the result of the state (n = 7). See, we can only add 1, 3, and 5. Now we can get a sum total of 7 in the following 3 ways:
1) Adding 1 to all possible combinations of state (n = 6)
Eg : [(1 + 1 + 1 + 1 + 1 + 1) + 1]
[(1 + 1 + 1 + 3) + 1]
[(1 + 1 + 3 + 1) + 1]
[(1 + 3 + 1 + 1) + 1]
[(3 + 1 + 1 + 1) + 1]
[(3 + 3) + 1]
[(1 + 5) + 1]
[(5 + 1) + 1]
2) Adding 3 to all possible combinations of state (n = 4);
[(1 + 1 + 1 + 1) + 3]
[(1 + 3) + 3]
[(3 + 1) + 3]
3) Adding 5 to all possible combinations of state(n = 2)
[(1 + 1) + 5]
(Note how it sufficient to add only on the right-side - all the add-from-left-side cases are covered, either in the same state, or another, e.g. [1 + (1 + 1 + 1 + 3)] is not needed in state (n=6) because it's covered by state (n = 4) [(1 + 1 + 1 + 1) + 3])
Now, think carefully and satisfy yourself that the above three cases are covering all possible ways to form a sum total of 7;
Therefore, we can say that result for
state(7) = state (6) + state (4) + state (2)
OR
state(7) = state (7-1) + state (7-3) + state (7-5)
In general,
state(n) = state(n-1) + state(n-3) + state(n-5)
Below is the implementation of the above approach:
C++
// C++ program to express
// n as sum of 1, 3, 5.
#include <bits/stdc++.h>
using namespace std;
// Returns the number of
// arrangements to form 'n'
int countWays(int n) {
// base case
if (n < 0)
return 0;
if (n == 0)
return 1;
return countWays(n-1) + countWays(n-3) + countWays(n-5);
}
int main() {
int n = 7;
cout << countWays(n);
}
Java
// Java program to express
// n as sum of 1, 3, 5.
class GfG {
// Returns the number of
// arrangements to form 'n'
static int countWays(int n) {
// base case
if (n < 0)
return 0;
if (n == 0)
return 1;
return countWays(n - 1) + countWays(n - 3) + countWays(n - 5);
}
public static void main(String[] args) {
int n = 7;
System.out.println(countWays(n));
}
}
Python
# Python program to express
# n as sum of 1, 3, 5.
# Returns the number of
# arrangements to form 'n'
def countWays(n):
# base case
if n < 0:
return 0
if n == 0:
return 1
return countWays(n - 1) + countWays(n - 3) + countWays(n - 5)
if __name__ == "__main__":
n = 7
print(countWays(n))
C#
// C# program to express
// n as sum of 1, 3, 5.
using System;
class GfG {
// Returns the number of
// arrangements to form 'n'
static int countWays(int n) {
// base case
if (n < 0)
return 0;
if (n == 0)
return 1;
return countWays(n - 1) + countWays(n - 3) + countWays(n - 5);
}
static void Main(string[] args) {
int n = 7;
Console.WriteLine(countWays(n));
}
}
JavaScript
// JavaScript program to express
// n as sum of 1, 3, 5.
// Returns the number of
// arrangements to form 'n'
function countWays(n) {
// base case
if (n < 0)
return 0;
if (n === 0)
return 1;
return countWays(n - 1) + countWays(n - 3) + countWays(n - 5);
}
let n = 7;
console.log(countWays(n));
Time Complexity: O(3^n), As at every stage we need to take three decisions and the height of the tree will be of the order of n.
Auxiliary Space: O(n), The extra space is used due to the recursion call stack.
The above code seems exponential as it is calculating the same state again and again. So, we just need to add memoization.
Step 4: Adding memoization or tabulation for the state
This is the easiest part of a dynamic programming solution. We just need to store the state answer so that the next time that state is required, we can directly use it from our memory.
Using Top-Down DP (Memoization)
We break down the problem into smaller subproblems, where each subproblem corresponds to finding the number of ways to form a sum for a smaller value of 'n'. By utilizing previously computed results, we can avoid redundant calculations and build up the solution for larger values of 'n'.
C++
// C++ program to express
// n as sum of 1, 3, 5.
#include <bits/stdc++.h>
using namespace std;
int countRecur(int n, vector<int> &memo) {
// base case
if (n < 0)
return 0;
if (n == 0)
return 1;
// If value is memoized
if (memo[n] != -1) {
return memo[n];
}
// Memoize the state
memo[n] = countRecur(n-1, memo) +
countRecur(n-3, memo) + countRecur(n-5, memo);
return memo[n];
}
// Returns the number of
// arrangements to form 'n'
int countWays(int n) {
vector<int> memo(n+1, -1);
return countRecur(n, memo);
}
int main() {
int n = 7;
cout << countWays(n);
}
Java
// Java program to express
// n as sum of 1, 3, 5.
import java.util.Arrays;
class GfG {
static int countRecur(int n, int[] memo) {
// base case
if (n < 0)
return 0;
if (n == 0)
return 1;
// If value is memoized
if (memo[n] != -1) {
return memo[n];
}
// Memoize the state
memo[n] = countRecur(n - 1, memo) +
countRecur(n - 3, memo) +
countRecur(n - 5, memo);
return memo[n];
}
// Returns the number of
// arrangements to form 'n'
static int countWays(int n) {
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
return countRecur(n, memo);
}
public static void main(String[] args) {
int n = 7;
System.out.println(countWays(n));
}
}
Python
# Python program to express
# n as sum of 1, 3, 5.
def countRecur(n, memo):
# base case
if n < 0:
return 0
if n == 0:
return 1
# If value is memoized
if memo[n] != -1:
return memo[n]
# Memoize the state
memo[n] = countRecur(n - 1, memo) + \
countRecur(n - 3, memo) + \
countRecur(n - 5, memo)
return memo[n]
# Returns the number of
# arrangements to form 'n'
def countWays(n):
memo = [-1] * (n + 1)
return countRecur(n, memo)
if __name__ == "__main__":
n = 7
print(countWays(n))
C#
// C# program to express
// n as sum of 1, 3, 5.
using System;
class GfG {
static int countRecur(int n, int[] memo) {
// base case
if (n < 0)
return 0;
if (n == 0)
return 1;
// If value is memoized
if (memo[n] != -1) {
return memo[n];
}
// Memoize the state
memo[n] = countRecur(n - 1, memo) +
countRecur(n - 3, memo) +
countRecur(n - 5, memo);
return memo[n];
}
// Returns the number of
// arrangements to form 'n'
static int countWays(int n) {
int[] memo = new int[n + 1];
for (int i = 0; i <= n; i++) {
memo[i] = -1;
}
return countRecur(n, memo);
}
static void Main(string[] args) {
int n = 7;
Console.WriteLine(countWays(n));
}
}
JavaScript
// JavaScript program to express
// n as sum of 1, 3, 5.
function countRecur(n, memo) {
// base case
if (n < 0)
return 0;
if (n === 0)
return 1;
// If value is memoized
if (memo[n] !== -1) {
return memo[n];
}
// Memoize the state
memo[n] = countRecur(n - 1, memo) +
countRecur(n - 3, memo) +
countRecur(n - 5, memo);
return memo[n];
}
// Returns the number of
// arrangements to form 'n'
function countWays(n) {
let memo = Array(n + 1).fill(-1);
return countRecur(n, memo);
}
let n = 7;
console.log(countWays(n));
Time Complexity: O(n), As at every stage we need to take three decisions and the height of the tree will be of the order of n.
Auxiliary Space: O(n + n), The extra space is used due to the recursion call stack and memo array of size n+1 is used to store the results of subproblems.
Using Bottom-Up DP (Tabulation)
We define a DP array where each element dp[i] represents the number of ways to form the sum 'i'. Starting with the base case dp[0] = 1 (since there is exactly one way to form a sum of 0 - using no numbers), we iteratively calculate the number of ways to form each value from 1 to n.
C++
// C++ program to express
// n as sum of 1, 3, 5.
#include <bits/stdc++.h>
using namespace std;
// Returns the number of
// arrangements to form 'n'
int countWays(int n) {
vector<int> dp(n + 1);
dp[0] = 1;
for (int i = 1; i <= n; i++) {
dp[i] = 0;
if (i - 1 >= 0)
dp[i] += dp[i - 1];
if (i - 3 >= 0)
dp[i] += dp[i - 3];
if (i - 5 >= 0)
dp[i] += dp[i - 5];
}
return dp[n];
}
int main() {
int n = 7;
cout << countWays(n);
}
Java
// Java program to express
// n as sum of 1, 3, 5.
class GfG {
// Returns the number of
// arrangements to form 'n'
static int countWays(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
for (int i = 1; i <= n; i++) {
dp[i] = 0;
if (i - 1 >= 0) dp[i] += dp[i - 1];
if (i - 3 >= 0) dp[i] += dp[i - 3];
if (i - 5 >= 0) dp[i] += dp[i - 5];
}
return dp[n];
}
public static void main(String[] args) {
int n = 7;
System.out.println(countWays(n));
}
}
Python
# Python program to express
# n as sum of 1, 3, 5.
# Returns the number of
# arrangements to form 'n'
def countWays(n):
dp = [0] * (n + 1)
dp[0] = 1
for i in range(1, n + 1):
dp[i] = 0
if i - 1 >= 0:
dp[i] += dp[i - 1]
if i - 3 >= 0:
dp[i] += dp[i - 3]
if i - 5 >= 0:
dp[i] += dp[i - 5]
return dp[n]
if __name__ == "__main__":
n = 7
print(countWays(n))
C#
// C# program to express
// n as sum of 1, 3, 5.
using System;
class GfG {
// Returns the number of
// arrangements to form 'n'
static int countWays(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
for (int i = 1; i <= n; i++) {
dp[i] = 0;
if (i - 1 >= 0) dp[i] += dp[i - 1];
if (i - 3 >= 0) dp[i] += dp[i - 3];
if (i - 5 >= 0) dp[i] += dp[i - 5];
}
return dp[n];
}
static void Main(string[] args) {
int n = 7;
Console.WriteLine(countWays(n));
}
}
JavaScript
// JavaScript program to express
// n as sum of 1, 3, 5.
// Returns the number of
// arrangements to form 'n'
function countWays(n) {
let dp = new Array(n + 1).fill(0);
dp[0] = 1;
for (let i = 1; i <= n; i++) {
dp[i] = 0;
if (i - 1 >= 0) dp[i] += dp[i - 1];
if (i - 3 >= 0) dp[i] += dp[i - 3];
if (i - 5 >= 0) dp[i] += dp[i - 5];
}
return dp[n];
}
let n = 7;
console.log(countWays(n));
Time Complexity: O(n), As we just need to make 3n function calls and there will be no repetitive calculations as we are returning previously calculated results.
Auxiliary Space: O(n), dp array of size n+1 is used to store the results of subproblems.
Please Refer to Tabulation vs Memoization to understand the difference between memoization and tabulation.
Dynamic Programming comes with lots of practice. One must try solving various classic DP problems that can be found here. You may check the below problems first and try solving them using the above-described steps:-
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem