The Wayback Machine - https://web.archive.org/web/20241116182808/https://www.geeksforgeeks.org/knuths-optimization-in-dynamic-programming/
Open In App

Knuth’s Optimization in Dynamic Programming

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

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 solve a problem with it.

Optimization Criteria:

Knuth’s optimization is applied to DP problems with a transition of the following form –

dp[i][j] = cost[i][j] + miniâ‰Īk<j(dp[i][k] + dp[k+1][j])

Further, the cost function must satisfy the following conditions (for a â‰Ī b â‰Ī c â‰Ī d) –

  1. It is a Monotone on the lattice of intervals (MLI) [cost(b, c) â‰Ī cost(a, d)]
  2. It satisfies the quadrangle inequality (QI) [cost(a, c) + cost(b, d) â‰Ī cost(b, c) + cost(a, d)]

Optimization:

For a solution that runs in O(N3) time, we would iterate through all values of k from i to j-1. However, we can do better than this using the following optimization:

  • Let’s define another array in addition to the dp array – opt[N][N]. Define opt[i][j] as the maximum (or minimum) value of k for which dp[i][j] is minimized in the dp transition.
    opt[i][j] = argminiâ‰Īk<j(dp[i][k] + dp[k+1][j])
  • The key to Knuth’s optimization, and several other optimizations in DP such as the Divide and Conquer optimization (not to be confused with the divide and conquer algorithm explained in this article), is the following inequality –

opt[i][j-1] â‰Ī opt[i][j] â‰Ī opt[i+1][j]

  • This helps because now, for each dp[] transition to calculate dp[i][j], we only have to test values of k between opt[i][j-1] and opt[i+1][j] instead in between i to j-1. This reduces the time complexity of the algorithm by a linear factor, which is a significant improvement.

Proof of Correctness:

To prove the correctness of this algorithm, we only need to prove the inequality: 

opt[i][j-1] â‰Ī opt[i][j] â‰Ī opt[i+1][j].

Follow the below section for the proof of the correctness of the algorithm:

Assumptions: If cost(i, j) is an MLI and satisfies the Quadrangle Inequality, then dp[i][j] also satisfies the inequality.  
Now, consider the following setup – 

  • For i < j, we have some indices i â‰Ī p â‰Ī q < j-1. 
  • Let dpk[i][j] = cost[i][j] + dp[i][k] + dp[k+1][j]. 

If we can show that:

dpp[i][j-1] â‰Ĩ dpq[i][j-1] ⇒ dpp[i][j] â‰Ĩ dpq[i][j] 

then setting q = opt[i][j-1], it will be clear that opt[i][j] will be at least as much as opt[i][j-1], due to the implication of the above inequality for all indices p less than opt[i][j-1]. 
This will prove that opt[i][j-1] â‰Ī opt[i][j].

Proof: Using the quadrangle inequality on the dp array, we get –

dp[p+1][j-1] + dp[q+1][j] â‰Ī dp[q+1][j-1] + dp[p+1][j]
⇒ (dp[i, p] + dp[p+1][j-1] + cost(i, j-1)) + (dp[i, q] + dp[q+1][j] + cost(i, j))
     â‰Ī (dp[i, q] + dp[q+1][j-1] + cost(i, j-1)) + (dp[i, p] + dp[p+1][j] + cost(i, j))
⇒ dpp[i][j-1] + dpq[i][j] â‰Ī dpp[i][j] + dpq[i][j-1]
⇒ dpp[i][j-1] – dpq[i][j-1] â‰Ī dpp[i][j] – dpq[i][j]

dpp[i][j-1] â‰Ĩ dpq[i][j-1] 
⇒ 0 â‰Ī dpp[i][j-1] – dpq[i][j-1] â‰Ī dpp[i][j] – dpq[i][j] 
⇒ dpp[i][j] â‰Ĩ dpq[i][j]. 

Hence it is proved that: dpp[i][j-1] â‰Ĩ dpq[i][j-1] ⇒ dpp[i][j] â‰Ĩ dpq[i][j]

The second part of the inequality (i.e. opt[i][j] â‰Ī opt[i+1][j]) can be shown with the same idea, starting with the inequality

dp[i][p]+dp[i+1][q] â‰Ī dp[i][q]+dp[i+1][p].

The proof of these two inequalities combinedly gives: opt[i][j-1] â‰Ī opt[i][j] â‰Ī opt[i+1][j]

Example:

Given an array arr[] of N elements, the task is to find the minimum cost for reducing the array to a single element in N-1 operations where in each operation: 

  • Delete the elements at indices i and i+1 for some valid index i, replacing them with their sum. 
  • The cost of doing so is arr[i] + arr[i+1], where arr[] is the array state just before the operation.
  • This cost will be added to the final cost.

Examples: 

Input: arr[] = {3, 4, 2, 1, 7}
Output: 37
Explanation: 
Remove the elements at 0th and 1st index. arr[] = {7, 2, 1, 7}, Cost = 3 + 4 = 7
Remove 1st and 2nd index elements. arr[] = {7, 3, 7}, Cost = 2 + 1 = 3
Remove 1st and 2nd index elements, arr[] = {7, 10}, Cost = 3 + 7 = 10
Remove the last two elements. arr[] = {17}, Cost =  = 7 + 10 = 17
Total cost = 7 + 3 + 10 + 17 = 37
This is the minimum possible total cost for this array.

Input: arr[] = {1, 2, 3, 4}
Output: 19
Explanation: 
Remove the 0th and 1st index elements. arr[] = {3, 3, 4}. Cost = 1 + 2 = 3
Remove the 0th and 1st index elements. arr[] = {6, 4}. Cost = 3 + 3 = 6
Remove the 0th and 1st index elements. arr[] = {10}. Cost = 6 + 4 = 10
Total cost = 3 + 6 + 10 = 19.
This is the minimi=um possible cost.

 

Sub-optimal solution (using Range DP): The problem can be solved using the following idea: 

  • Let arr[] be the original array before any modifications are made. 
  • For an element in the array that has been derived from indices i to j of a[], the cost of the final operation to form this single element will be the sum arr[i] + arr[i+1] + . . . + arr[j]. Let this value be denoted by the function cost(i, j).
  • To find the minimum cost for the section arr[i, i+1, … j], consider the cost of converting the pairs of sub-arrays arr[i, i+1 . . . k] & arr[k+1, k+2 . . . j] into single elements, and choose the minimum over all possible values of k from i to j-1 (both inclusive).

For implementing the above idea:

  • The cost function can be calculated in constant time with preprocessing, using a prefix sum array:
    • Calculate prefix sum (say stored in pref[] array).
    • So cost(i, j) can be calculated as (pref[j] – pref[i-1]).
  • Traverse from i = 0 to N-1:
    • Traverse j =  i+1 to N-1 to generate all the subarray of the main array:
      • Solve this problem for all these possible subarrays with the following dp transition – 
        dp[i][j] = cost(i, j) + miniâ‰Īkâ‰Īj-1(dp[i][k] + dp[k+1][j]) as explained in the above idea.
  • Here dp[i][j] is the minimum cost of applying (j – i) operations on the sub-array arr[i, i+1, . . . j] to convert it to a single element. 
    cost(i, j) denotes the cost of the final operation i.e. the cost of adding the last two values to convert arr[i, i+1, . . ., j] to a single element.
  • The final answer will be stored on dp[0][N-1].

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum cst
int minCost(int arr[], int N)
{
    // Creating the prefix sum array
    int pref[N+1], dp[N][N];
    pref[0] = 0;
    memset(dp, 0, sizeof(dp));
   
    // Loop to calculate the prefix sum
    for (int i = 0; i < N; i++) {
        pref[i + 1] = pref[i] + arr[i];
    }
 
    // Iterating through all subarrays
    // of length 2 or greater
    for (int i = N - 2; i >= 0; i--) {
        for (int j = i + 1; j < N; j++) {
             
            // Cost function = sum of
            // all elements in the subarray
            int cost = pref[j + 1] - pref[i];
            dp[i][j] = INT_MAX;
            for (int k = i; k < j; k++) {
                 
                // dp transition
                dp[i][j]
                = min(dp[i][j], dp[i][k]
                      + dp[k + 1][j] + cost);
            }
        }
    }
 
    // Return answer
    return dp[0][N - 1];
}
 
// Driver code
int main()
{
    int arr[] = { 3, 4, 2, 1, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
     
    // Function call
    cout << minCost(arr, N);
    return 0;
}


Java




// Java code for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
// Function to find the minimum cst
static int minCost(int[] arr, int N)
{
    // Creating the prefix sum array
    int pref[] = new int[N+1];
    int dp[][] = new int[N][N];
    pref[0] = 0;
   
    // Loop to calculate the prefix sum
    for (int i = 0; i < N; i++) {
        pref[i + 1] = pref[i] + arr[i];
    }
 
    // Iterating through all subarrays
    // of length 2 or greater
    for (int i = N - 2; i >= 0; i--) {
        for (int j = i + 1; j < N; j++) {
             
            // Cost function = sum of
            // all elements in the subarray
            int cost = pref[j + 1] - pref[i];
            dp[i][j] = Integer.MAX_VALUE;
            for (int k = i; k < j; k++) {
                 
                // dp transition
                dp[i][j]
                = Math.min(dp[i][j], dp[i][k]
                      + dp[k + 1][j] + cost);
            }
        }
    }
 
    // Return answer
    return dp[0][N - 1];
}
 
// Driver Code
public static void main (String[] args) {
    int[] arr = { 3, 4, 2, 1, 7 };
    int N = arr.length;
     
    // Function call
    System.out.println(minCost(arr, N));
}
}
 
// This code is contributed by sanjoy_62.


Python3




def minCost(arr, N):
    # Creating the prefix sum array
    pref = [0] * (N + 1)
    dp = [[0] * N for i in range(N)]
    pref[0] = 0
   
    # Loop to calculate the prefix sum
    for i in range(N):
        pref[i + 1] = pref[i] + arr[i]
 
    # Iterating through all subarrays
    # of length 2 or greater
    for i in range(N - 2, -1, -1):
        for j in range(i + 1, N):
             
            # Cost function = sum of
            # all elements in the subarray
            cost = pref[j + 1] - pref[i]
            dp[i][j] = float('inf')
            for k in range(i, j):
                 
                # dp transition
                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + cost)
 
    # Return answer
    return dp[0][N - 1]
 
# Driver Code
if __name__ == '__main__':
    arr = [3, 4, 2, 1, 7]
    N = len(arr)
 
    # Function call
    print(minCost(arr, N))
 
    # This code is contributed by unstoppablepandu.


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function to find the minimum cst
static int minCost(int[] arr, int N)
{
    // Creating the prefix sum array
    int[] pref = new int[N+1];
    int[,] dp = new int[N, N];
    pref[0] = 0;
   
    // Loop to calculate the prefix sum
    for (int i = 0; i < N; i++) {
        pref[i + 1] = pref[i] + arr[i];
    }
 
    // Iterating through all subarrays
    // of length 2 or greater
    for (int i = N - 2; i >= 0; i--) {
        for (int j = i + 1; j < N; j++) {
             
            // Cost function = sum of
            // all elements in the subarray
            int cost = pref[j + 1] - pref[i];
            dp[i, j] = Int32.MaxValue;
            for (int k = i; k < j; k++) {
                 
                // dp transition
                dp[i, j]
                = Math.Min(dp[i,j], dp[i,k]
                      + dp[k + 1, j] + cost);
            }
        }
    }
 
    // Return answer
    return dp[0, N - 1];
}
 
 
// Driver Code
public static void Main(String[] args)
{
        int[] arr = { 3, 4, 2, 1, 7 };
    int N = arr.Length;
     
    // Function call
    Console.WriteLine(minCost(arr, N));
}
}
 
// This code is contributed by avijitmondal1998.


Javascript




<script>
       // JavaScript program for the above approach
 
       // Function to find the minimum cst
       function minCost(arr, N)
       {
        
           // Creating the prefix sum array
           let pref = new Array(N + 1), dp = new Array(N);
 
           for (let i = 0; i < dp.length; i++) {
               dp[i] = new Array(N);
           }
           for (let i = 0; i < dp.length; i++) {
               for (let j = 0; j < dp[i].length; j++) {
                   dp[i][j] = 0;
               }
           }
           pref[0] = 0;
 
 
           // Loop to calculate the prefix sum
           for (let i = 0; i < N; i++) {
               pref[i + 1] = pref[i] + arr[i];
           }
 
           // Iterating through all subarrays
           // of length 2 or greater
           for (let i = N - 2; i >= 0; i--) {
               for (let j = i + 1; j < N; j++) {
 
                   // Cost function = sum of
                   // all elements in the subarray
                   let cost = pref[j + 1] - pref[i];
                   dp[i][j] = Number.MAX_VALUE;
                   for (let k = i; k < j; k++) {
 
                       // dp transition
                       dp[i][j]
                           = Math.min(dp[i][j], dp[i][k]
                               + dp[k + 1][j] + cost);
                   }
               }
           }
 
           // Return answer
           return dp[0][N - 1];
       }
 
       // Driver code
       let arr = [3, 4, 2, 1, 7];
       let N = arr.length;
 
       // Function call
       document.write(minCost(arr, N));
 
   // This code is contributed by Potta Lokesh
 
   </script>


Output

37

Time complexity: O(N3)
Auxiliary Space: O(N2) 

Optimal solution (using Knuth’s optimization):

The conditions for applying Knuth’s optimization hold for this question:

cost(i, j) is merely the sum of all elements in the subarray bounded by the indices i and j. Further, the transition function of dynamic programming matches the general case for applying this technique.

Follow the steps mentioned here to implement the idea of Knuth optimization:

  • Define the array opt[N][N] and the dp[][] array. 
  • Now, process subarrays in increasing order of length, with the initial state dp[i][i] = 0, and opt[i][i] = i (because the value should be i to minimize the value dp[i][i]).
  • Thus, when we reach the subarray arr[i, . . ., j], the value of opt[i][j-1] and opt[i+1][j] are already known. So, only check for the condition opt[i][j-1] â‰Ī k â‰Ī opt[i+1][j], to find opt[i][j] and dp[i][j]. 
  • Here also the cost function is calculated in the same way as in the previous approach using the prefix sum array.

Note: In the code given below different way of looping through all sub-arrays is used (instead of looping in increasing order of length), However, ensuring that opt[i+1][j] and opt[i][j-1] are calculated before dp[i][j].

Below is the implementation of the above approach. 

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum possible cost
int minCost(int arr[], int N)
{
    // Creating the prefix sum array
    int pref[N + 1], dp[N][N], opt[N][N];
    pref[0] = 0;
    memset(dp, 0, sizeof(dp));
    memset(dp, 0, sizeof(dp));
   
    // Loop to calculate the prefix sum
    for (int i = 0; i < N; i++) {
        pref[i + 1] = pref[i] + arr[i];
        opt[i][i] = i;
    }
 
    // Iterating through all sub-arrays
    // of length 2 or greater
    for (int i = N - 2; i >= 0; i--) {
        for (int j = i + 1; j < N; j++) {
 
            // Cost function = sum of
            // all elements in the sub-array
            int cost = pref[j + 1] - pref[i];
            int mn = INT_MAX;
            for (int k = opt[i][j - 1];
                 k <= min(j - 1, opt[i + 1][j]);
                 k++) {
                if (mn >= dp[i][k]
                    + dp[k + 1][j] + cost) {
 
                    // Updating opt table
                    opt[i][j] = k;
 
                    // Updating minimum cost
                    mn = dp[i][k]
                         + dp[k + 1][j] + cost;
                }
            }
 
            // dp transition
            dp[i][j] = mn;
        }
    }
    return dp[0][N - 1];
}
 
// Driver code
int main()
{
    int arr[] = { 3, 4, 2, 1, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << minCost(arr, N);
    return 0;
}


Java




// Java code to implement the approach
import java.io.*;
 
class GFG
{
 
// Function to find the minimum possible cost
static int minCost(int arr[], int N)
{
    // Creating the prefix sum array
    int pref[] = new int[N + 1];
    int dp[][] = new int[N][N];
    int opt[][] = new int[N][N];
    pref[0] = 0;
     
    // Loop to calculate the prefix sum
    for (int i = 0; i < N; i++) {
        pref[i + 1] = pref[i] + arr[i];
        opt[i][i] = i;
    }
 
    // Iterating through all sub-arrays
    // of length 2 or greater
    for (int i = N - 2; i >= 0; i--) {
        for (int j = i + 1; j < N; j++) {
 
            // Cost function = sum of
            // all elements in the sub-array
            int cost = pref[j + 1] - pref[i];
            int mn = Integer.MAX_VALUE;
            for (int k = opt[i][j - 1];
                 k <= Math.min(j - 1, opt[i + 1][j]);
                 k++) {
                if (mn >= dp[i][k]
                    + dp[k + 1][j] + cost) {
 
                    // Updating opt table
                    opt[i][j] = k;
 
                    // Updating minimum cost
                    mn = dp[i][k]
                         + dp[k + 1][j] + cost;
                }
            }
 
            // dp transition
            dp[i][j] = mn;
        }
    }
    return dp[0][N - 1];
}
 
  // Driver code
  public static void main(String[] args)
  {
    int arr[] = { 3, 4, 2, 1, 7 };
    int N = arr.length;
 
    // Function call
    System.out.println(minCost(arr, N));
  }
}
 
// This code is contributed by sanjoy_62.


C#




// C# program to implement
// the above approach
using System;
 
class GFG
{
 
// Function to find the minimum possible cost
static int minCost(int[] arr, int N)
{
    // Creating the prefix sum array
    int[] pref = new int[N + 1];
    int[,] dp = new int[N, N];
    int[,] opt = new int[N, N];
    pref[0] = 0;
      
    // Loop to calculate the prefix sum
    for (int i = 0; i < N; i++) {
        pref[i + 1] = pref[i] + arr[i];
        opt[i, i] = i;
    }
  
    // Iterating through all sub-arrays
    // of length 2 or greater
    for (int i = N - 2; i >= 0; i--) {
        for (int j = i + 1; j < N; j++) {
  
            // Cost function = sum of
            // all elements in the sub-array
            int cost = pref[j + 1] - pref[i];
            int mn = Int32.MaxValue;
            for (int k = opt[i, j - 1];
                 k <= Math.Min(j - 1, opt[i + 1, j]);
                 k++) {
                if (mn >= dp[i, k]
                    + dp[k + 1, j] + cost) {
  
                    // Updating opt table
                    opt[i, j] = k;
  
                    // Updating minimum cost
                    mn = dp[i, k]
                         + dp[k + 1, j] + cost;
                }
            }
  
            // dp transition
            dp[i, j] = mn;
        }
    }
    return dp[0, N - 1];
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 3, 4, 2, 1, 7 };
    int N = arr.Length;
  
    // Function call
    Console.Write(minCost(arr, N));
}
}
 
// This code is contributed by spevel62.


Python3




def minCost(arr, N):
    # Creating the prefix sum array
    pref = [0] * (N + 1)
    dp = [[0 for i in range(N)] for j in range(N)]
    opt = [[0 for i in range(N)] for j in range(N)]
 
    # Loop to calculate the prefix sum
    for i in range(N):
        pref[i + 1] = pref[i] + arr[i]
        opt[i][i] = i
 
    # Iterating through all sub-arrays
    # of length 2 or greater
    for i in range(N - 2, -1, -1):
        for j in range(i + 1, N):
            # Cost function = sum of
            # all elements in the sub-array
            cost = pref[j + 1] - pref[i]
            mn = float("inf")
            for k in range(opt[i][j - 1], min(j - 1, opt[i + 1][j]) + 1):
                if mn >= dp[i][k] + dp[k + 1][j] + cost:
                    # Updating opt table
                    opt[i][j] = k
                    # Updating minimum cost
                    mn = dp[i][k] + dp[k + 1][j] + cost
            # dp transition
            dp[i][j] = mn
    return dp[0][N - 1]
 
# Driver code
if __name__ == '__main__':
    arr = [3, 4, 2, 1, 7]
    N = len(arr)
 
    # Function call
    print(minCost(arr, N))


Javascript




function minCost(arr, N) {
 
// Creating the prefix sum array
let pref = new Array(N + 1).fill(0);
let dp = new Array(N);
let opt = new Array(N);
 
for (let i = 0; i < N; i++) {
    dp[i] = new Array(N).fill(0);
    opt[i] = new Array(N).fill(0);
    pref[i + 1] = pref[i] + arr[i];
    opt[i][i] = i;
}
 
// Iterating through all sub-arrays
// of length 2 or greater
for (let i = N - 2; i >= 0; i--) {
    for (let j = i + 1; j < N; j++) {
     
        // Cost function = sum of
        // all elements in the sub-array
        let cost = pref[j + 1] - pref[i];
        let mn = Number.MAX_VALUE;
        for (let k = opt[i][j - 1]; k <= Math.min(j - 1, opt[i + 1][j]); k++) {
            if (mn >= dp[i][k] + dp[k + 1][j] + cost)
            {
             
                // Updating opt table
                opt[i][j] = k;
                 
                // Updating minimum cost
                mn = dp[i][k] + dp[k + 1][j] + cost;
            }
        }
         
        // dp transition
        dp[i][j] = mn;
    }
}
return dp[0][N - 1];
}
 
// Driver code
let arr = [3, 4, 2, 1, 7];
let N = arr.length;
 
// Function call
console.log(minCost(arr, N));


Output

37

Time Complexity: O(N2)
Auxiliary Space: O(N2) 



Similar Reads

Knuth's Up-Arrow Notation For Exponentiation
Knuth's up-arrow notation, also known as Knuth's arrow notation, is a mathematical notation for exponentiation that was introduced by Donald Knuth in his book "Concrete Mathematics". It uses a sequence of up-arrows (↑) to represent exponentiation with various bases and exponents. Approach: Exponentiation depends on the number of arrows used in the
4 min read
Trabb Pardo–Knuth Algorithm
This article is not about learning some new complex algorithm, its more about the history of programming. TPK was introduced to illustrate the evolution of computer programming languages. By the time you are finished with this article you will have learnt something about the history of programming rather than a new concept. In their 1977 work "The
4 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
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
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
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
Expected number of moves to reach the end of a board | Dynamic programming
Given a linear board of length N numbered from 1 to N, the task is to find the expected number of moves required to reach the Nth cell of the board, if we start at cell numbered 1 and at each step we roll a cubical dice to decide the next move. Also, we cannot go outside the bounds of the board. Note that the expected number of moves can be fractio
11 min read
Double Knapsack | Dynamic Programming
Given an array 'arr' containing the weight of 'N' distinct items, and two knapsacks that can withstand 'W1' and 'W2' weights, the task is to find the sum of the largest subset of the array 'arr', that can be fit in the two knapsacks. It's not allowed to break any items in two, i.e an item should be put in one of the bags as a whole.Examples: Input
15+ min read
Optimal Strategy for the Divisor game using Dynamic Programming
Given an integer N and two players, A and B are playing a game. On each player’s turn, that player makes a move by subtracting a divisor of current N (which is less than N) from current N, thus forming a new N for the next turn. The player who does not have any divisor left to subtract loses the game. The task is to tell which player wins the game
9 min read
Optimal Substructure Property in Dynamic Programming | DP-2
As we discussed in Set 1, the following are the two main properties of a problem that suggest that the given problem can be solved using Dynamic programming: 1) Overlapping Subproblems 2) Optimal Substructure We have already discussed the Overlapping Subproblem property in Set 1. Let us discuss the Optimal Substructure property here. In Dynamic pro
9 min read
Longest Palindromic Substring using Dynamic Programming
Given a string, find the longest substring which is a palindrome. Examples: Input: Given string :"forgeeksskeegfor", Output: "geeksskeeg".Input: Given string :"Geeks", Output: "ee". Recommended PracticeLongest Palindrome in a StringTry It!BRUTE APPROACH: (TABULATION METHOD)Intuition: We create a 2-D array to fill the array with appropriate steps.We
15+ min read
Largest Independent Set Problem using Dynamic Programming
Given a Binary Tree, find size of the Largest Independent Set(LIS) in it. A subset of all tree nodes is an independent set if there is no edge between any two nodes of the subset. For example, consider the following binary tree. The largest independent set(LIS) is {10, 40, 60, 70, 80} and size of the LIS is 5. Recommended PracticeLargest Independen
15+ min read
Vertex Cover Problem (Dynamic Programming Solution for Tree)
A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complete. But it can be solved in polynomial time for tre
15+ min read
Introduction and Dynamic Programming solution to compute nCr%p
Given three numbers n, r and p, compute value of nCr mod p. Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6.We strongly recommend that you click here and practice it, before moving on to the solution.METHOD 1: (Using Dynamic Programming) A Simple Solution is to first compute nCr, then compute nCr % p. This s
15+ min read
three90RightbarBannerImg