The Wayback Machine - https://web.archive.org/web/20240914210601/https://www.geeksforgeeks.org/dynamic-programming-dp-on-arrays-tutorial/
Open In App

Dynamic Programming (DP) on Arrays Tutorial

Last Updated : 28 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We know that Dynamic Programming is a way to reduce the time complexity of a problem using memoization or tabulation of the overlapping states. While applying DP on arrays the array indices act as DP states and transitions occurs between indices.

How to Identify if Array problem has a DP solution?

  • Using Constraints: Generally, in Competitive Programming the required solution should perform nearly 10^7 to 10^8 operations, so if the array size N = 1000 to 5000 we can expect to have an N^2 DP solution, and for N = 100 we can have an N^3 DP solution.
  • Minimize/Maximize Values: Dynamic Programming can be applied if the problem is to maximize or minimize any value over all possible scenarios.
  • Various functions in the problem: If the question consists of functions f(x) as operations then we can try to think towards Dynamic programming.
  • Greedy fails: If you can think of a test case where the Greedy solution fails, then the problem has a high chance of having a DP solution.
  • Recursive Sub-Problems: Determining whether the problem has a recursive solution where an over-lapping subproblem occurs is a difficult task but if you manage to do that, then DP can be a solution if the constraints allow that.

Quick Approximation of DP Time & Space Complexity for Arrays:

Before coding the solution, we need to verify whether the time complexity of our solution fits the given constraints or not, we can approximate the time complexity using the below formula:

Time Complexity = Total Number of States * ( 1 + Average number of Transitions per State)

Space Complexity = Average number of States.

Why classical-DP problems differ than DP problems on Arrays?

The problems that we see on Competitive Programming platforms are mainly made up of two parts:

  • Adhoc part
  • Standard part

The Adhoc part of the problem is the one that makes each problem unique and also the one that decides the difficulty of the problem. One needs to make several observations to deduce the Adhoc part into the standard solution. Good dp problems will often require you to make adhoc observations to figure out some properties that allow you to apply dp on them.

Let’s us see how an Adhoc problem changes a standard DP problem:

Problem: You are given N tiles 1 to N, and initially you are standing at 1. In one move you can make a jump of either 1 or 2 in forward direction. Determine the total number of ways you can reach from tile 1 to tile N.

Example: N=4

Output: total 3 ways are possible

Explaination: 1->2->3->4

1->2->4

1->3->4

Adhoc Part: The Adhoc part of the problem diverts the question towards thinking of moving on tiles from 1 to N in different ways, the programmer will dry run several test cases and make several observations in order to reach to the solution, he might even try to make some mathematical formula to calculate the solution.

Standard Part: If observed carefully this question is nothing but print the N’th fibonacci number the simplest DP problem that might exist. each tile T can be reached only via previous two tiles that is T is dependent upon T-1 and T-2. Using This we can write the DP states as:

  • Number _of_ways[i]= Number _of_ways[i-1] + Number _of_ways[i-2]

DP for Precomputation on Arrays:

The recurrence relation for the factorial of a number n is given by:

  • Factorial [n] = factorial[n-1] * n

The recurrence relation for the inverse factorial of a number n is given by:

  • Inverse_fact[n] = (n+1) * (inverse_fact[n+1])

Recognizing which type of Standard DP can be used to solve Array Problems:

When tackling DP problems during a contest the most difficult task is to define the states and transitions for the problem. The states and transitions for problems are mostly the variations of existing standard DP problems, let us see how we can try to think towards a particular standard DP problem:

0/1 Knapsack Problem:

  • Weight/ Volume/Value Constraints in the problem.
  • 0-1 decision problem, i.e. either include or exclude an item to the final result.
  • Task is to minimize or maximize the profit.
  • O(N^2) solution is permissible

Coin Change:

  • Array values can be used as a denomination on a particular sum.
  • Minimum array values required to achieve a target.
  • Total number of ways required as a result.
  • O(N^2) solution is permissible.

Fibonacci:

  • For a particular index i, dp[i] depends on some previously calculated indices.
  • O(N) solution is required.
  • State Transition: F(n)=F(n-1) + F(n-2)

Matrix Chain Multiplication:

  • If Each pair of indices {i,j} have to be used as a State then we can try to think towards MCM approach.
  • Constraints allow a time complexity of O(N^3)

Longest Increasing Subsequence (LIS):

  • dp[i] represents the length of the LIS ending at index i. This idea can be extended to the context where we can calculate the best answer ending at ith index.

Edit Distance:

  • In Edit Distance, dp[i][j] represents the minimum number of operations to convert the first i characters of string1 to the first j characters of string2.

Transition:

  • If characters s1[i] and s2[j] are the same: dp[i][j] = dp[i-1][j-1].
  • Otherwise: dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1.

The transitions in Edit distance are very commonly seen in many questions where a particular dp value depends upon previously calculated adjacent dp cells.

Longest Common Subsequence (LCS):

  • In LCS dp[i][j] represents the length of the LCS of the first i characters of string1 and the first j characters of string2.

Transition:

  • If characters s1[i] and s2[j] are the same: dp[i][j] = dp[i-1][j-1] + 1.
  • Otherwise: dp[i][j] = max(dp[i-1][j], dp[i][j-1]).

Similar to Edit distance, LCS transitions can also be very frequently observed in various problems.

Practice/Solve DP on Array Problems:

Problem

Practice Link

Minimum number of jumps to reach end (Jump Game)

Solve

Count number of coins required to make a given value (Coin Change II)

Solve

0/1 Knapsack Problem

Solve

Sieve of Eratosthenes

Solve

Matrix Chain Multiplication

Solve

Longest Common Subsequence (LCS)

Solve

Longest Increasing Subsequence (LIS)

Solve

Longest Palindromic Substring

Solve

Save Your Life

Solve

Travelling Salesman Problem using Dynamic Programming

Solve

Floyd Warshall Algorithm

Solve

Count Unique Paths in matrix

Solve

Edit Distance

Solve

Cutting a Rod

Solve



Similar Reads

Difference between Static Arrays and Dynamic Arrays
In the Data structure, we know that an array plays a vital role in having similar types of elements arranged in a contiguous manner with the same data type. According to the concept of array, an array can be defined in two ways as per the memory allocation concept. Types of Arrays:There are basically two types of arrays: Static Array: In this type
5 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
How do Dynamic arrays work?
A Dynamic array (vector in C++, ArrayList in Java) automatically grows when we try to make an insertion and there is no more space left for the new item. Usually the area doubles in size. A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required. The elements of
15+ min read
Design a dynamic stack using arrays that supports getMin() in O(1) time and O(1) extra space
Design a special dynamic Stack using an array that supports all the stack operations such as push(), pop(), peek(), isEmpty(), and getMin() operations in constant Time and Space complexities. Examples: Assuming the right to left orientation as the top to bottom orientation and performing the operations: Push(10): 10 is added to the top of the stack
15+ min read
Algorithms | Dynamic Programming | Question 7
Which of the following standard algorithms is not Dynamic Programming based? (A) Bellman–Ford Algorithm for single source shortest path (B) Floyd Warshall Algorithm for all pairs shortest paths (C) 0-1 Knapsack problem (D) Prim\'s Minimum Spanning Tree Answer: (D) Explanation: Prim\'s Minimum Spanning Tree is a Greedy Algorithm. All others are dyna
1 min read
Algorithms | Dynamic Programming | Question 2
We use dynamic programming approach when (A) We need an optimal solution (B) The solution has optimal substructure (C) The given problem can be reduced to the 3-SAT problem (D) It\'s faster than Greedy Answer: (B) Explanation: We use dynamic programming approach when the solution has an optimal substructure. Hence Option(B) is the correct answer. Q
1 min read
Algorithms | Dynamic Programming | Question 3
An algorithm to find the length of the longest monotonically increasing sequence of numbers in an array A[0 :n-1] is given below. Let Li denote the length of the longest monotonically increasing sequence starting at index i in the array. Which of the following statements is TRUE? (A) The algorithm uses dynamic programming paradigm (B) The algorithm
2 min read
Algorithms | Dynamic Programming | Question 4
Which of the following is NOT a characteristic of dynamic programming? (A) Memoization, which involves storing the results of expensive function calls and reusing them. (B) Breaking a problem into smaller overlapping subproblems. (C) Solving problems in a sequential manner. (D) Dynamic programming can be used for problems where the solution has an
2 min read
Algorithms | Dynamic Programming | Question 5
Four matrices M1, M2, M3 and M4 of dimensions pxq, qxr, rxs and sxt respectively can be multiplied is several ways with different number of total scalar multiplications. For example, when multiplied as ((M1 X M2) X (M3 X M4)), the total number of multiplications is pqr + rst + prt. When multiplied as (((M1 X M2) X M3) X M4), the total number of sca
1 min read
Algorithms | Dynamic Programming | Question 7
The subset-sum problem is defined as follows. Given a set of n positive integers, S = {a1 ,a2 ,a3 ,â€Ķ,an} and positive integer W, is there a subset of S whose elements sum to W? A dynamic program for solving this problem uses a 2-dimensional Boolean array X, with n rows and W+1 columns. X[i, j],1 <= i <= n, 0 <= j <= W, is TRUE if and on
2 min read
Introduction to Dynamic Programming on Trees
Dynamic Programming(DP) is a technique to solve problems by breaking them down into overlapping sub-problems which follows the optimal substructure. There are various problems using DP like subset sum, knapsack, coin change etc. DP can also be applied on trees to solve some specific problems.Pre-requisite: DFSGiven a tree with N nodes and N-1 edges
10 min read
Print equal sum sets of Array (Partition Problem) using Dynamic Programming
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both sets is equal. If it is possible, then print both sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Input : arr
13 min read
Dynamic Programming vs Divide-and-Conquer
In this article I’m trying to explain the difference/similarities between dynamic programming and divide and conquer approaches based on two examples: binary search and minimum edit distance (Levenshtein distance).The ProblemWhen I started to learn algorithms it was hard for me to understand the main idea of dynamic programming (DP) and how it is d
12 min read
Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming
Given a N-ary tree with a value associated with each node, the task is to choose a subset of these nodes such that sum of chosen nodes is maximum under a constraint that no two chosen node in subset should be directly connected that is, if we have taken a node in our sum then we can’t take its any children in consideration and vice versa.Examples:
9 min read
Distinct palindromic sub-strings of the given string using Dynamic Programming
Given a string str of lowercase alphabets, the task is to find all distinct palindromic sub-strings of the given string. Examples: Input: str = "abaaa" Output: 5 Palindromic sub-strings are "a", "aa", "aaa", "aba" and "b" Input: str = "abcd" Output: 4 Approach: The solution to this problem has been discussed here using Manacher’s algorithm. However
8 min read
Longest path in a directed Acyclic graph | Dynamic Programming
Given a directed graph G with N vertices and M edges. The task is to find the length of the longest directed path in Graph.Note: Length of a directed path is the number of edges in it. Examples: Input: N = 4, M = 5 Output: 3 The directed path 1->3->2->4 Input: N = 5, M = 8 Output: 3 Simple Approach: A naive approach is to calculate the len
8 min read
Count of numbers from range [L, R] whose sum of digits is Y using Dynamic Programming
Pre-requisites: Recursion, Dynamic Programming, Digit DP Given an integer Y and a range [L, R], the task is to find the count of all numbers from the given range whose sum of digits is equal to Y.Examples: Input: L = 0, R = 11, Y = 2 Output: 2 2 -> 2 11 -> 1 + 1 = 2Input: L = 500, R = 1000, Y = 6 Output: 3 Constraints: 0 <= L <= R <=
10 min read
Minimum time required to rot all oranges | Dynamic Programming
Given a matrix of dimension m * n where each cell in the matrix can have values 0, 1, or 2 which has the following meaning: 0: Empty cell 1: Cells have fresh oranges 2: Cells have rotten oranges So the task is to determine what is the minimum time required so that all the oranges become rotten. A rotten orange at index [i, j] can rot other fresh or
15 min read
Reliability Design Problem in Dynamic Programming
The reliability design problem is the designing of a system composed of several devices connected in series or parallel. Reliability means the probability to get the success of the device. Let's say, we have to set up a system consisting of D1, D2, D3, ............, and Dn devices, each device has some costs C1, C2, C3, ........, Cn. Each device ha
6 min read
Convert N to M with given operations using dynamic programming
Given two integers N and M and the task is to convert N to M with the following operations: Multiply N by 2 i.e. N = N * 2.Subtract 1 from N i.e. N = N - 1. Examples: Input: N = 4, M = 6 Output: 2 Perform operation 2: N = N - 1 = 4 - 1 = 3 Perform operation 1: N = N * 2 = 3 * 2 = 6 Input: N = 10, M = 1 Output: 9 Approach: Create an array dp[] of si
7 min read
Longest subsequence with a given OR value : Dynamic Programming Approach
Given an array arr[], the task is to find the longest subsequence with a given OR value M. If there is no such sub-sequence then print 0.Examples: Input: arr[] = {3, 7, 2, 3}, M = 3 Output: 3 {3, 2, 3} is the required subsequence 3 | 2 | 3 = 3Input: arr[] = {2, 2}, M = 3 Output: 0 Approach: A simple solution is to generate all the possible sub-sequ
6 min read
Python | Implementing Dynamic programming using Dictionary
Dynamic Programming is one way which can be used as 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 subproblems so that we do not have to re-compute them when needed later. This simple opti
3 min read
Ackermann's function using Dynamic programming
Given two non-zero integers M and N, the problem is to compute the result of the Ackermann function based on some particular equations. Ackermann function is defined as: Examples: Input: M = 2, N = 2Output: 7 Input: M = 2, N = 7Output: 6141004759 The approach for Ackermann function described in this article, takes a very huge amount of time to comp
13 min read
Count ways to select N pairs of candies of distinct colors (Dynamic Programming + Bitmasking)
Given an integer N representing the number of red and blue candies and a matrix mat[][] of size N * N, where mat[i][j] = 1 represents the existence of a pair between ith red candy and jth blue candy, the task is to find the count of ways to select N pairs of candies such that each pair contains distinct candies of different colors. Examples: Input:
13 min read
Hamiltonian Path ( Using Dynamic Programming )
Given an adjacency matrix adj[][] of an undirected graph consisting of N vertices, the task is to find whether the graph contains a Hamiltonian Path or not. If found to be true, then print "Yes". Otherwise, print "No". A Hamiltonian path is defined as the path in a directed or undirected graph which visits each and every vertex of the graph exactly
10 min read
Minimum moves to make M and N equal by repeated addition of divisors except 1 using Dynamic Programming
Given two integers N and M, the task is to calculate the minimum number of moves to change N to M, where In one move it is allowed to add any divisor of the current value of N to N itself except 1. Print "-1" if it is not possible. Example: Input: N = 4, M = 24Output: 5Explanation: The given value of N can be converted into M using the following st
8 min read
Dynamic Programming meaning in DSA
Dynamic Programming is defined as an algorithmic technique that is used to solve problems by breaking them into smaller subproblems and avoiding repeated calculation of overlapping subproblems and using the property that the solution of the problem depends on the optimal solution of the subproblems Properties of Dynamic Programming:Optimal Substruc
2 min read
Knuth's Optimization in Dynamic Programming
Knuth's optimization is a very powerful tool in dynamic programming, that can be used to reduce the time complexity of the solutions primarily from O(N3) to O(N2). Normally, it is used for problems that can be solved using range DP, assuming certain conditions are satisfied. In this article, we will first explore the optimization itself, and then s
15+ min read
Divide and Conquer Optimization in Dynamic Programming
Dynamic programming (DP) is arguably the most important tool in a competitive programmer's repertoire. There are several optimizations in DP that reduce the time complexity of standard DP procedures by a linear factor or more, such as Knuth's optimization, Divide and Conquer optimization, the Convex Hull Trick, etc. They are, of paramount importanc
15+ min read
Comparison among Greedy, Divide and Conquer and Dynamic Programming algorithm
Greedy algorithm, divide and conquer algorithm, and dynamic programming algorithm are three common algorithmic paradigms used to solve problems. Here's a comparison among these algorithms: Approach:Greedy algorithm: Makes locally optimal choices at each step with the hope of finding a global optimum.Divide and conquer algorithm: Breaks down a probl
4 min read