codeparrot/xlcost-text-to-code huggingface dataset:
Largest subtree sum for each vertex of given N | Java program for the above approach ; Function to perform the DFS Traversal on the given Tree ; To check if v is leaf vertex ; Initialize answer for vertex v ; Traverse adjacency list of v ; Update maximum subtree sum ; If v is leaf ; Function to calculate maximum subtree sum for each vertex ; Stores the adjacency list ; Add Edegs to the list ; Stores largest subtree sum for each vertex ; Calculate answer ; Print the result ; Driver Code ; Given nodes ; Give N edges ; Given values ; Function Call
import java . io . * ; import java . util . ArrayList ; @ SuppressWarnings ( " unchecked " ) class GFG { static void dfs ( int v , int p , ArrayList < Integer > adj [ ] , int ans [ ] , int vals [ ] ) { boolean isLeaf = true ; ans [ v ] = Integer . MIN_VALUE ; for ( int u : adj [ v ] ) { if ( u == p ) continue ; isLeaf = false ; dfs ( u , v , adj , ans , vals ) ; ans [ v ] = Math . max ( ans [ u ] + vals [ v ] , Math . max ( ans [ u ] , vals [ u ] ) ) ; } if ( isLeaf ) { ans [ v ] = vals [ v ] ; } } static void printAnswer ( int n , int edges [ ] [ ] , int values [ ] ) { ArrayList < Integer > adj [ ] = new ArrayList [ n ] ; for ( int i = 0 ; i < n ; i ++ ) adj [ i ] = new ArrayList < > ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int u = edges [ i ] [ 0 ] - 1 ; int v = edges [ i ] [ 1 ] - 1 ; adj [ u ] . add ( v ) ; adj [ v ] . add ( u ) ; } int ans [ ] = new int [ n ] ; dfs ( 0 , - 1 , adj , ans , values ) ; for ( int x : ans ) { System . out . print ( x + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 4 ; int edges [ ] [ ] = new int [ ] [ ] { { 1 , 2 } , { 1 , 3 } , { 3 , 4 } } ; int values [ ] = { 1 , - 1 , 0 , 1 } ; printAnswer ( N , edges , values ) ; } }
Queries to count frequencies of a given character in a given range of indices | Java program for the above approach ; Function to print count of char y present in the range [ l , r ] ; Length of the string ; Stores the precomputed results ; Iterate the given string ; Increment dp [ i ] [ y - ' a ' ] by 1 ; Pre - compute ; Number of queries ; Traverse each query ; Print the result for each query ; Driver Code ; Given string ; Given Queries ; Function Call
import java . io . * ; class GFG { static void noOfChars ( String s , char [ ] [ ] queries ) { int n = s . length ( ) ; int dp [ ] [ ] = new int [ n + 1 ] [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { dp [ i + 1 ] [ s . charAt ( i ) - ' a ' ] ++ ; for ( int j = 0 ; j < 26 ; j ++ ) { dp [ i + 1 ] [ j ] += dp [ i ] [ j ] ; } } int q = queries . length ; for ( int i = 0 ; i < q ; i ++ ) { int l = ( int ) queries [ i ] [ 0 ] ; int r = ( int ) queries [ i ] [ 1 ] ; int c = queries [ i ] [ 2 ] - ' a ' ; System . out . print ( dp [ r ] - dp [ l - 1 ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { String S = " aabv " ; char queries [ ] [ ] = new char [ ] [ ] { { 1 , 2 , ' a ' } , { 2 , 3 , ' b ' } } ; noOfChars ( S , queries ) ; } }
Minimum cost required to rearrange a given array to make it equal to another given array | Java program for the above approach ; Function to find lower_bound ; Function to find length of the longest common subsequence ; Find position where element is to be inserted ; Return the length of LCS ; Function to find the minimum cost required to convert the sequence A exactly same as B ; Auxiliary array ; Stores positions of elements of A [ ] ; Initialize index array with - 1 ; Update the index array with index of corresponding elements of B ; Place only A 's array values  with its mapped values  into nums array ; Find LCS ; No of elements to be added in array A [ ] ; Stores minimum cost ; Print the minimum cost ; Driver code ; Given array A [ ] ; Given C ; Size of arr A ; Size of arr B ; Function call
import java . io . * ; class GFG { static int LowerBound ( int a [ ] , int k , int x ) { int l = - 1 ; int r = k ; while ( l + 1 < r ) { int m = ( l + r ) >>> 1 ; if ( a [ m ] >= x ) { r = m ; } else { l = m ; } } return r ; } static int findLCS ( int [ ] nums , int N ) { int k = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int pos = LowerBound ( nums , k , nums [ i ] ) ; nums [ pos ] = nums [ i ] ; if ( k == pos ) { k = pos + 1 ; } } return k ; } static int minimumCost ( int [ ] A , int [ ] B , int M , int N , int C ) { int [ ] nums = new int [ 100000 ] ; int [ ] index = new int [ 100000 ] ; for ( int i = 0 ; i < 100000 ; i ++ ) index [ i ] = - 1 ; for ( int i = 0 ; i < N ; i ++ ) { index [ B [ i ] ] = i ; } int k = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( index [ A [ i ] ] != - 1 ) { nums [ k ++ ] = index [ A [ i ] ] ; } } int lcs_length = findLCS ( nums , k ) ; int elements_to_be_added = N - lcs_length ; int min_cost = elements_to_be_added * C ; System . out . println ( min_cost ) ; return 0 ; } public static void main ( String [ ] args ) { int [ ] A = { 1 , 6 , 3 , 5 , 10 } ; int [ ] B = { 3 , 1 , 5 } ; int C = 2 ; int M = A . length ; int N = B . length ; minimumCost ( A , B , M , N , C ) ; } }
Maximize count of array elements required to obtain given sum | Java program for the above approach ; Function that count the maximum number of elements to obtain sum V ; Stores the maximum number of elements required to obtain V ; Base Case ; Initialize all table values as Infinite ; Find the max arr required for all values from 1 to V ; Go through all arr smaller than i ; If current coin value is less than i ; Update table [ i ] ; Return the final count ; Driver Code ; Given array ; Given sum V ; Function Call
import java . io . * ; class GFG { static int maxCount ( int arr [ ] , int m , int V ) { int table [ ] = new int [ V + 1 ] ; table [ 0 ] = 0 ; for ( int i = 1 ; i <= V ; i ++ ) table [ i ] = - 1 ; for ( int i = 1 ; i <= V ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( arr [ j ] <= i ) { int sub_res = table [ i - arr [ j ] ] ; if ( sub_res != - 1 && sub_res + 1 > table [ i ] ) table [ i ] = sub_res + 1 ; } } } return table [ V ] ; } public static void main ( String [ ] args ) { int arr [ ] = { 25 , 10 , 5 } ; int m = arr . length ; int V = 30 ; System . out . println ( maxCount ( arr , m , V ) ) ; } }
Maximize path sum from top | Java program to implement the above approach ; Function to get the maximum path sum from top - left cell to all other cells of the given matrix ; Store the maximum path sum ; Base case ; Compute the value of dp [ i ] [ j ] using the recurrence relation ; Print maximum path sum from the top - left cell ; Driver Code
import java . util . * ; class GFG { static final int SZ = 100 ; static void pathSum ( int [ ] [ ] mat , int N , int M ) { int [ ] [ ] dp = new int [ N ] [ M ] ; dp [ 0 ] [ 0 ] = mat [ 0 ] [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = mat [ i ] [ 0 ] + dp [ i - 1 ] [ 0 ] ; } for ( int j = 1 ; j < M ; j ++ ) { dp [ 0 ] [ j ] = mat [ 0 ] [ j ] + dp [ 0 ] [ j - 1 ] ; } for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j < M ; j ++ ) { dp [ i ] [ j ] = mat [ i ] [ j ] + Math . max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { System . out . print ( dp [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 3 , 2 , 1 } , { 6 , 5 , 4 } , { 7 , 8 , 9 } } ; int N = 3 ; int M = 3 ; pathSum ( mat , N , M ) ; } }
Length of Longest Palindrome Substring | Java program for the above approach ; Function to find the length of the longest palindromic subString ; Length of String str ; Stores the dp states ; All subStrings of length 1 are palindromes ; Check for sub - String of length 2 ; If adjacent character are same ; Update table [ i ] [ i + 1 ] ; Check for lengths greater than 2 k is length of subString ; Fix the starting index ; Ending index of subString of length k ; Check for palindromic subString str [ i , j ] ; Mark true ; Update the maximum length ; Return length of LPS ; Driver Code ; Given String str ; Function Call
import java . util . * ; class GFG { static int longestPalSubstr ( String str ) { int n = str . length ( ) ; boolean [ ] [ ] table = new boolean [ n ] [ n ] ; int maxLength = 1 ; for ( int i = 0 ; i < n ; ++ i ) table [ i ] [ i ] = true ; int start = 0 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( str . charAt ( i ) == str . charAt ( i + 1 ) ) { table [ i ] [ i + 1 ] = true ; start = i ; maxLength = 2 ; } } for ( int k = 3 ; k <= n ; ++ k ) { for ( int i = 0 ; i < n - k + 1 ; ++ i ) { int j = i + k - 1 ; if ( table [ i + 1 ] [ j - 1 ] && str . charAt ( i ) == str . charAt ( j ) ) { table [ i ] [ j ] = true ; if ( k > maxLength ) { start = i ; maxLength = k ; } } } } return maxLength ; } public static void main ( String [ ] args ) { String str = " forgeeksskeegfor " ; System . out . print ( longestPalSubstr ( str ) ) ; } }
Maximize sum of an Array by flipping sign of all elements of a single subarray | Java program for the above approach ; Function to find the maximum sum after flipping a subarray ; Stores the total sum of array ; Initialize the maximum sum ; Iterate over all possible subarrays ; Initialize sum of the subarray before flipping sign ; Initialize sum of subarray after flipping sign ; Calculate the sum of original subarray ; Subtract the original subarray sum and add the flipped subarray sum to the total sum ; Return the max_sum ; Driver Code ; Function call
import java . io . * ; public class GFG { public static int maxSumFlip ( int a [ ] , int n ) { int total_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) total_sum += a [ i ] ; int max_sum = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; int flip_sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += a [ j ] ; max_sum = Math . max ( max_sum , total_sum - 2 * sum ) ; } } return Math . max ( max_sum , total_sum ) ; } public static void main ( String args [ ] ) { int arr [ ] = { - 2 , 3 , - 1 , - 4 , - 2 } ; int N = arr . length ; System . out . println ( maxSumFlip ( arr , N ) ) ; } }
Minimum repeated addition of even divisors of N required to convert N to M | Java program for the above approach ; INF is the maximum value which indicates Impossible state ; Stores the dp states ; Recursive Function that considers all possible even divisors of cur ; Indicates impossible state ; Check dp [ cur ] is already calculated or not ; Initially it is set to INF that meanswe cur can 't be transform to M ; Loop to find even divisors of cur ; If i is divisor of cur ; If i is even ; Find recursively for cur + i ; Check another divisor ; Find recursively for cur + ( cur / i ) ; Finally store the current state result and return the answer ; Function that counts the minimum operation to reduce N to M ; Initialise dp state ; Function call ; Driver Code ; Given N and M ; Function call ; INF indicates impossible state
import java . util . * ; class GFG { static int INF = ( int ) 1e7 ; static int max_size = 100007 ; static int [ ] dp = new int [ max_size ] ; static int min_op ( int cur , int M ) { if ( cur > M ) return INF ; if ( cur == M ) return 0 ; if ( dp [ cur ] != - 1 ) return dp [ cur ] ; int op = INF ; for ( int i = 2 ; i * i <= cur ; i ++ ) { if ( cur % i == 0 ) { if ( i % 2 == 0 ) { op = Math . min ( op , 1 + min_op ( cur + i , M ) ) ; } if ( ( cur / i ) != i && ( cur / i ) % 2 == 0 ) { op = Math . min ( op , 1 + min_op ( cur + ( cur / i ) , M ) ) ; } } } return dp [ cur ] = op ; } static int min_operations ( int N , int M ) { for ( int i = N ; i <= M ; i ++ ) { dp [ i ] = - 1 ; } return min_op ( N , M ) ; } public static void main ( String [ ] args ) { int N = 6 , M = 24 ; int op = min_operations ( N , M ) ; if ( op >= INF ) System . out . print ( " - 1" ) ; else System . out . print ( op + "NEW_LINE"); } }
Maximize Sum possible from an Array by the given moves | Java Program to implement the above approach ; Function to find the maximum sum possible by given moves from the array ; Checking for boundary ; If previously computed subproblem occurs ; If element can be moved left ; Calculate maximum possible sum by moving left from current index ; If element can be moved right ; Calculate maximum possible sum by moving right from current index and update the maximum sum ; Store the maximum sum ; Driver Code ; Function call
import java . io . * ; import java . util . * ; public class GFG { public static int maxValue ( int a [ ] , int n , int pos , int moves , int left , int dp [ ] [ ] ) { if ( moves == 0 || ( pos > n - 1 pos < 0 ) ) return 0 ; if ( dp [ pos ] [ left ] != - 1 ) return dp [ pos ] [ left ] ; int value = 0 ; if ( left > 0 && pos >= 1 ) value = Math . max ( value , a [ pos ] + maxValue ( a , n , pos - 1 , moves - 1 , left - 1 , dp ) ) ; if ( pos <= n - 1 ) value = Math . max ( value , a [ pos ] + maxValue ( a , n , pos + 1 , moves - 1 , left , dp ) ) ; return dp [ pos ] [ left ] = value ; } public static void main ( String args [ ] ) { int n = 5 ; int a [ ] = { 1 , 5 , 4 , 3 , 2 } ; int k = 1 ; int m = 4 ; int dp [ ] [ ] = new int [ n + 1 ] [ k + 1 ] ; for ( int i [ ] : dp ) Arrays . fill ( i , - 1 ) ; System . out . println ( ( a [ 0 ] + maxValue ( a , n , 1 , m , k , dp ) ) ) ; } }
Maximize the Sum of a Subsequence from an Array based on given conditions | Java program to implement the above approach ; Function to select the array elements to maximize the sum of the selected elements ; If the entire array is solved ; Memoized subproblem ; Calculate sum considering the current element in the subsequence ; Calculate sum without considering the current element in the subsequence ; Update the maximum of the above sums in the dp [ ] [ ] table ; Driver Code ; Initialize the dp array ; Function call
import java . util . * ; public class GFG { public static int maximumSum ( int [ ] a , int count , int index , int n , int [ ] [ ] dp ) { if ( index == n ) return 0 ; if ( dp [ index ] [ count ] != - 1 ) return dp [ index ] [ count ] ; int take_element = a [ index ] * count + maximumSum ( a , count + 1 , index + 1 , n , dp ) ; int dont_take = maximumSum ( a , count , index + 1 , n , dp ) ; return dp [ index ] [ count ] = Math . max ( take_element , dont_take ) ; } public static void main ( String args [ ] ) { int n = 5 ; int a [ ] = { - 1 , - 9 , 0 , 5 , - 7 } ; int dp [ ] [ ] = new int [ n + 1 ] [ n + 1 ] ; for ( int i [ ] : dp ) Arrays . fill ( i , - 1 ) ; System . out . println ( maximumSum ( a , 1 , 0 , n , dp ) ) ; } }
Minimum number of Nodes to be removed such that no subtree has more than K nodes | Java program for the above approach ; Variables used to store data globally ; Adjacency list representation of tree ; Function to perform DFS Traversal ; Mark the node as true ; Traverse adjacency list of child node ; If already visited then omit the node ; Add number of nodes in subtree ; Increment the count ; Return the nodes ; Function to add edges in graph ; Function that finds the number of nodes to be removed such that every subtree has size at most K ; Function Call to find the number of nodes to remove ; Print Removed Nodes ; Driver Code ; Creating list for all nodes ; Insert of nodes in graph ; Required subtree size ; Function Call
import java . util . * ; class GFG { static final int N = 20 ; static boolean visited [ ] = new boolean [ N ] ; static int K ; static int removals = 0 ; static ArrayList < Integer > removed_nodes = new ArrayList < > ( ) ; static ArrayList < ArrayList < Integer > > adj = new ArrayList < > ( ) ; static int dfs ( int s ) { visited [ s ] = true ; int nodes = 1 ; for ( Integer child : adj . get ( s ) ) { if ( visited [ child ] ) continue ; nodes += dfs ( child ) ; } if ( nodes > K ) { removals ++ ; removed_nodes . add ( s ) ; nodes = 0 ; } return nodes ; } static void addEdge ( int a , int b ) { adj . get ( a ) . add ( b ) ; adj . get ( b ) . add ( a ) ; } public static void findRemovedNodes ( int K ) { dfs ( 1 ) ; System . out . println ( " Number ▁ of ▁ nodes " + " ▁ removed : ▁ " + removals ) ; System . out . print ( " Removed ▁ Nodes : ▁ " ) ; for ( int node : removed_nodes ) System . out . print ( node + " ▁ " ) ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < N ; i ++ ) adj . add ( new ArrayList < > ( ) ) ; addEdge ( 1 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 2 , 4 ) ; addEdge ( 2 , 5 ) ; addEdge ( 3 , 6 ) ; K = 3 ; findRemovedNodes ( K ) ; } }
Queries to find sum of distance of a given node to every leaf node in a Weighted Tree | Java program for the above problem ; MAX size ; Graph with { destination , weight } ; ; For storing the sum for ith node ; Leaves in subtree of ith . ; dfs to find sum of distance of leaves in the subtree of a node ; Flag is the node is leaf or not ; ; Skipping if parent ; Setting flag to false ; Doing dfs call ; Doing calculation in postorder . ; If the node is leaf then we just increment the no . of leaves under the subtree of a node ; Adding num of leaves ; Calculating answer for the sum in the subtree ; dfs function to find the sum of distance of leaves outside the subtree ; Number of leaves other than the leaves in the subtree of i ; Adding the contribution of leaves outside to the ith node ; Adding the leafs outside to ith node 's leaves. ; Calculating the sum of distance of leaves in the subtree of a node assuming the root of the tree is 1 ; Calculating the sum of distance of leaves outside the subtree of node assuming the root of the tree is 1 ; Answering the queries ; ; Driver code ; 1 ( 4 ) / \ ( 2 ) / \ 4 2 ( 5 ) / \ ( 3 ) / \ 5 3 ; Initialising tree ; System . out . println ( v ) ;
import java . util . * ; import java . lang . * ; class GFG { static class pair { int first , second ; pair ( int f , int s ) { this . first = f ; this . second = s ; } } static final int N = ( int ) 1e5 + 5 ; static ArrayList < ArrayList < pair > > v ; static int [ ] dp = new int [ N ] ; static int [ ] leaves = new int [ N ] ; static int n ; static void dfs ( int a , int par ) { int leaf = 1 ; for ( pair i : v . get ( a ) ) { if ( i . first == par ) continue ; leaf = 0 ; dfs ( i . first , a ) ; } if ( leaf == 1 ) { leaves [ a ] += 1 ; } else { for ( pair i : v . get ( a ) ) { if ( i . first == par ) continue ; leaves [ a ] += leaves [ i . first ] ; dp [ a ] = dp [ a ] + dp [ i . first ] + leaves [ i . first ] * i . second ; } } } static void dfs2 ( int a , int par ) { for ( pair i : v . get ( a ) ) { if ( i . first == par ) continue ; int leafOutside = leaves [ a ] - leaves [ i . first ] ; dp [ i . first ] += ( dp [ a ] - dp [ i . first ] ) ; dp [ i . first ] += i . second * ( leafOutside - leaves [ i . first ] ) ; leaves [ i . first ] += leafOutside ; dfs2 ( i . first , a ) ; } } static void answerQueries ( int [ ] queries ) { dfs ( 1 , 0 ) ; dfs2 ( 1 , 0 ) ; for ( int i = 0 ; i < queries . length ; i ++ ) { System . out . println ( dp [ queries [ i ] ] ) ; } } public static void main ( String [ ] args ) { n = 5 ; v = new ArrayList < > ( ) ; for ( int i = 0 ; i <= n ; i ++ ) v . add ( new ArrayList < pair > ( ) ) ; v . get ( 1 ) . add ( new pair ( 4 , 4 ) ) ; v . get ( 4 ) . add ( new pair ( 1 , 4 ) ) ; v . get ( 1 ) . add ( new pair ( 2 , 2 ) ) ; v . get ( 2 ) . add ( new pair ( 1 , 2 ) ) ; v . get ( 2 ) . add ( new pair ( 3 , 3 ) ) ; v . get ( 3 ) . add ( new pair ( 2 , 3 ) ) ; v . get ( 2 ) . add ( new pair ( 5 , 5 ) ) ; v . get ( 5 ) . add ( new pair ( 2 , 5 ) ) ; int [ ] queries = { 1 , 3 , 5 } ; answerQueries ( queries ) ; } }
Minimum changes required to make each path in a matrix palindrome | Java program to implement the above approach ; Function for counting changes ; Maximum distance possible is ( n - 1 + m - 1 ) ; Stores the maximum element ; Update the maximum ; Stores frequencies of values for respective distances ; Initialize frequencies of cells as 0 ; Count frequencies of cell values in the matrix ; Increment frequency of value at distance i + j ; Store the most frequent value at i - th distance from ( 0 , 0 ) and ( N - 1 , M - 1 ) ; Calculate max frequency and total cells at distance i ; Count changes required to convert all cells at i - th distance to most frequent value ; Driver Code
import java . util . * ; class GFG { static int N = 7 ; static int countChanges ( int matrix [ ] [ ] , int n , int m ) { int i , j , dist = n + m - 1 ; int Max_element = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < m ; j ++ ) { Max_element = Math . max ( Max_element , matrix [ i ] [ j ] ) ; } } int freq [ ] [ ] = new int [ dist ] [ Max_element + 1 ] ; for ( i = 0 ; i < dist ; i ++ ) { for ( j = 0 ; j < Max_element + 1 ; j ++ ) freq [ i ] [ j ] = 0 ; } for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < m ; j ++ ) { freq [ i + j ] [ matrix [ i ] [ j ] ] ++ ; } } int min_changes_sum = 0 ; for ( i = 0 ; i < dist / 2 ; i ++ ) { int maximum = 0 ; int total_values = 0 ; for ( j = 0 ; j < Max_element + 1 ; j ++ ) { maximum = Math . max ( maximum , freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ) ; total_values += freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ; } min_changes_sum += total_values - maximum ; } return min_changes_sum ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 7 , 0 , 3 , 1 , 8 , 1 , 3 } , { 0 , 4 , 0 , 1 , 0 , 4 , 0 } , { 3 , 1 , 8 , 3 , 1 , 0 , 7 } } ; int minChanges = countChanges ( mat , 3 , 7 ) ; System . out . print ( minChanges ) ; } }
Count of numbers upto N having absolute difference of at most K between any two adjacent digits | Java program to get the count of numbers upto N having absolute difference at most K between any two adjacent digits ; Table to store solution of each subproblem ; Function to calculate all possible numbers ; Check if position reaches end that is equal to length of N ; Check if the result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is false , means number has already become smaller so we can place any digit , otherwise N [ pos ] ; Check if start is false the number has not started yet ; Check if we do not start the number at pos then recur forward ; If we start the number we can place any digit from 1 to upper_limit ; Finding the new tight ; Condition if the number has already started ; We can place digit upto upperbound & absolute difference with previous digit much be atmost K ; Absolute difference atmost K ; Store the solution to this subproblem ; Driver code ; Initialising the table with - 1 ; Function call
import java . util . * ; class GFG { static int [ ] [ ] [ ] [ ] dp = new int [ 1002 ] [ 10 ] [ 2 ] [ 2 ] ; static int possibleNumbers ( int pos , int previous , int tight , int start , String N , int K ) { if ( pos == N . length ( ) ) return 1 ; if ( dp [ pos ] [ previous ] [ tight ] [ start ] != - 1 ) return dp [ pos ] [ previous ] [ tight ] [ start ] ; int res = 0 ; int upper_limit = ( tight == 1 ) ? ( N . charAt ( pos ) - '0' ) : 9 ; int new_tight ; if ( start == 0 ) { res = possibleNumbers ( pos + 1 , previous , 0 , 0 , N , K ) ; for ( int i = 1 ; i <= upper_limit ; i ++ ) { new_tight = ( tight > 0 && i == upper_limit ) ? 1 : 0 ; res += possibleNumbers ( pos + 1 , i , new_tight , 1 , N , K ) ; } } else { for ( int i = 0 ; i <= upper_limit ; i ++ ) { new_tight = ( tight > 0 && i == upper_limit ) ? 1 : 0 ; if ( Math . abs ( i - previous ) <= K ) res += possibleNumbers ( pos + 1 , i , new_tight , 1 , N , K ) ; } } dp [ pos ] [ previous ] [ tight ] [ start ] = res ; return dp [ pos ] [ previous ] [ tight ] [ start ] ; } public static void main ( String [ ] args ) { String N = "20" ; int K = 2 ; for ( int i = 0 ; i < 1002 ; i ++ ) for ( int j = 0 ; j < 10 ; j ++ ) for ( int k = 0 ; k < 2 ; k ++ ) for ( int l = 0 ; l < 2 ; l ++ ) dp [ i ] [ j ] [ k ] [ l ] = - 1 ; System . out . print ( possibleNumbers ( 0 , 0 , 1 , 0 , N , K ) + "NEW_LINE"); } }