text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Count lexicographically increasing K | Function to count K - length strings from first N alphabets ; To keep track of column sum in dp ; Auxiliary 2d dp array ; Initialize dp [ 0 ] [ i ] = 1 and update the column_sum ; Iterate for K times ; Iterate for N times ; dp [ i ] [ j ] : Stores the number of ways to form i - length strings consisting of j letters ; Update the column_sum ; Print number of ways to arrange K - length strings with N alphabets ; Driver Code ; Given N and K ; Function Call
def waysToArrangeKLengthStrings ( N , K ) : NEW_LINE INDENT column_sum = [ 0 for i in range ( N + 1 ) ] NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE dp = [ [ 0 for i in range ( N + 1 ) ] for j in range ( K + 1 ) ] NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 NEW_LINE column_sum [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , K + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] += column_sum [ j - 1 ] NEW_LINE column_sum [ j ] += dp [ i ] [ j ] NEW_LINE DEDENT DEDENT print ( dp [ K ] [ N ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 2 NEW_LINE waysToArrangeKLengthStrings ( N , K ) NEW_LINE DEDENT
Count N | Function to count N - length strings consisting of vowels only sorted lexicographically ; Stores count of strings consisting of vowels sorted lexicographically of all possible lengths ; Initialize DP [ 1 ] [ 1 ] ; Traverse the matrix row - wise ; Base Case ; Return the result ; Driver Code ; Function Call
def findNumberOfStrings ( n ) : NEW_LINE INDENT DP = [ [ 0 for i in range ( 6 ) ] for i in range ( n + 1 ) ] NEW_LINE DP [ 1 ] [ 1 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , 6 ) : NEW_LINE INDENT if ( i == 1 ) : NEW_LINE INDENT DP [ i ] [ j ] = DP [ i ] [ j - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT DP [ i ] [ j ] = DP [ i ] [ j - 1 ] + DP [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return DP [ n ] [ 5 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE print ( findNumberOfStrings ( N ) ) NEW_LINE DEDENT
Largest subtree sum for each vertex of given N | Python3 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 ; Add Edegs to the list ; Calculate answer ; Prthe result ; Driver Code ; Given nodes ; Give N edges ; Given values ; Function Call
V = 3 NEW_LINE M = 2 NEW_LINE def dfs ( v , p ) : NEW_LINE INDENT isLeaf = 1 NEW_LINE ans [ v ] = - 10 ** 9 NEW_LINE for u in adj [ v ] : NEW_LINE INDENT if ( u == p ) : NEW_LINE INDENT continue NEW_LINE DEDENT isLeaf = 0 NEW_LINE dfs ( u , v ) NEW_LINE ans [ v ] = max ( ans [ u ] + vals [ v ] , max ( ans [ u ] , vals [ u ] ) ) NEW_LINE DEDENT if ( isLeaf ) : NEW_LINE INDENT ans [ v ] = vals [ v ] NEW_LINE DEDENT DEDENT def printAnswer ( n , edges , vals ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT u = edges [ i ] [ 0 ] - 1 NEW_LINE v = edges [ i ] [ 1 ] - 1 NEW_LINE adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT dfs ( 0 , - 1 ) NEW_LINE for x in ans : NEW_LINE INDENT print ( x , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 3 , 4 ] ] NEW_LINE adj = [ [ ] for i in range ( N ) ] NEW_LINE ans = [ 0 for i in range ( N ) ] NEW_LINE vals = [ 1 , - 1 , 0 , 1 ] NEW_LINE printAnswer ( N , edges , vals ) NEW_LINE DEDENT
Queries to count frequencies of a given character in a given range of indices | Function to prcount 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
def noOfChars ( s , queries ) : NEW_LINE INDENT n = len ( s ) NEW_LINE dp = [ [ 0 for i in range ( 26 ) ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i + 1 ] [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT dp [ i + 1 ] [ j ] += dp [ i ] [ j ] NEW_LINE DEDENT DEDENT q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT l = queries [ i ] [ 0 ] NEW_LINE r = queries [ i ] [ 1 ] NEW_LINE c = ord ( queries [ i ] [ 2 ] ) - ord ( ' a ' ) NEW_LINE print ( dp [ r ] - dp [ l - 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " aabv " NEW_LINE queries = [ [ 1 , 2 , ' a ' ] , [ 2 , 3 , ' b ' ] ] NEW_LINE noOfChars ( S , queries ) NEW_LINE DEDENT
Minimum cost required to rearrange a given array to make it equal to another given array | 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 ; Given array A [ ] ; Given C ; Size of arr A ; Size of arr B ; Function call
def LowerBound ( a , k , x ) : NEW_LINE INDENT l = - 1 NEW_LINE r = k NEW_LINE while ( l + 1 < r ) : NEW_LINE INDENT m = ( l + r ) >> 1 NEW_LINE if ( a [ m ] >= x ) : NEW_LINE INDENT r = m NEW_LINE DEDENT else : NEW_LINE INDENT l = m NEW_LINE DEDENT DEDENT return r NEW_LINE DEDENT def findLCS ( nums , N ) : NEW_LINE INDENT k = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT pos = LowerBound ( nums , k , nums [ i ] ) NEW_LINE nums [ pos ] = nums [ i ] NEW_LINE if ( k == pos ) : NEW_LINE INDENT k = pos + 1 NEW_LINE DEDENT DEDENT return k NEW_LINE DEDENT def minimumCost ( A , B , M , N , C ) : NEW_LINE INDENT nums = [ 0 ] * 100000 NEW_LINE index = [ - 1 ] * 100000 NEW_LINE for i in range ( N ) : NEW_LINE INDENT index [ B [ i ] ] = i NEW_LINE DEDENT k = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT if ( index [ A [ i ] ] != - 1 ) : NEW_LINE INDENT k += 1 NEW_LINE nums [ k ] = index [ A [ i ] ] NEW_LINE DEDENT DEDENT lcs_length = findLCS ( nums , k ) NEW_LINE elements_to_be_added = N - lcs_length NEW_LINE min_cost = elements_to_be_added * C NEW_LINE print ( min_cost ) NEW_LINE DEDENT A = [ 1 , 6 , 3 , 5 , 10 ] NEW_LINE B = [ 3 , 1 , 5 ] NEW_LINE C = 2 NEW_LINE M = len ( A ) NEW_LINE N = len ( B ) NEW_LINE minimumCost ( A , B , M , N , C ) NEW_LINE
Maximize count of array elements required to obtain given sum | 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
def maxCount ( arr , m , V ) : NEW_LINE INDENT table = [ 0 for i in range ( V + 1 ) ] NEW_LINE table [ 0 ] = 0 NEW_LINE for i in range ( 1 , V + 1 , 1 ) : NEW_LINE INDENT table [ i ] = - 1 NEW_LINE for i in range ( 1 , V + 1 , 1 ) : NEW_LINE INDENT for j in range ( 0 , m , 1 ) : NEW_LINE INDENT if ( arr [ j ] <= i ) : NEW_LINE INDENT sub_res = table [ i - arr [ j ] ] NEW_LINE if ( sub_res != - 1 and sub_res + 1 > table [ i ] ) : NEW_LINE INDENT table [ i ] = sub_res + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return table [ V ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 25 , 10 , 5 ] NEW_LINE m = len ( arr ) NEW_LINE V = 30 NEW_LINE print ( f ' Maximum number of array elements required : { maxCount ( arr , m , V ) } ' ) NEW_LINE DEDENT
Maximize path sum from top | Function to get the maximum path sum from top - left cell to all other cells of the given matrix ; Store the maximum path sum Initialize the value of dp [ i ] [ j ] to 0. ; Base case ; Compute the value of dp [ i ] [ j ] using the recurrence relation ; Print maximum path sum from the top - left cell ; Driver code
def pathSum ( mat , N , M ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( M ) ] for y in range ( N ) ] NEW_LINE dp [ 0 ] [ 0 ] = mat [ 0 ] [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = ( mat [ i ] [ 0 ] + dp [ i - 1 ] [ 0 ] ) NEW_LINE DEDENT for j in range ( 1 , M ) : NEW_LINE INDENT dp [ 0 ] [ j ] = ( mat [ 0 ] [ j ] + dp [ 0 ] [ j - 1 ] ) NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 1 , M ) : NEW_LINE INDENT dp [ i ] [ j ] = ( mat [ i ] [ j ] + max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ) NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT print ( dp [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 3 , 2 , 1 ] , [ 6 , 5 , 4 ] , [ 7 , 8 , 9 ] ] NEW_LINE N = 3 NEW_LINE M = 3 NEW_LINE pathSum ( mat , N , M ) NEW_LINE DEDENT
Length of Longest Palindrome Substring | 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
def longestPalSubstr ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE table = [ [ False for i in range ( n ) ] for j in range ( n ) ] ; NEW_LINE maxLength = 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT table [ i ] [ i ] = True ; NEW_LINE DEDENT start = 0 ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( str [ i ] == str [ i + 1 ] ) : NEW_LINE INDENT table [ i ] [ i + 1 ] = True ; NEW_LINE start = i ; NEW_LINE maxLength = 2 ; NEW_LINE DEDENT DEDENT for k in range ( 3 , n + 1 ) : NEW_LINE INDENT for i in range ( n - k + 1 ) : NEW_LINE INDENT j = i + k - 1 ; NEW_LINE if ( table [ i + 1 ] [ j - 1 ] and str [ i ] == str [ j ] ) : NEW_LINE INDENT table [ i ] [ j ] = True ; NEW_LINE if ( k > maxLength ) : NEW_LINE INDENT start = i ; NEW_LINE maxLength = k ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return maxLength ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " forgeeksskeegfor " ; NEW_LINE print ( longestPalSubstr ( str ) ) ; NEW_LINE DEDENT
Maximize sum of an Array by flipping sign of all elements of a single subarray | Python3 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 sys NEW_LINE def maxSumFlip ( a , n ) : NEW_LINE INDENT total_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT total_sum += a [ i ] NEW_LINE DEDENT max_sum = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE flip_sum = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT sum += a [ j ] NEW_LINE max_sum = max ( max_sum , total_sum - 2 * sum ) NEW_LINE DEDENT DEDENT return max ( max_sum , total_sum ) NEW_LINE DEDENT arr = [ - 2 , 3 , - 1 , - 4 , - 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maxSumFlip ( arr , N ) ) NEW_LINE
Minimum repeated addition of even divisors of N required to convert N to M | 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
INF = 10000007 ; NEW_LINE max_size = 100007 ; NEW_LINE dp = [ 0 for i in range ( max_size ) ] ; NEW_LINE def min_op ( cur , M ) : NEW_LINE INDENT if ( cur > M ) : NEW_LINE INDENT return INF ; NEW_LINE DEDENT if ( cur == M ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ cur ] != - 1 ) : NEW_LINE INDENT return dp [ cur ] ; NEW_LINE DEDENT op = INF ; NEW_LINE i = 2 NEW_LINE while ( i * i <= cur ) : NEW_LINE INDENT if ( cur % i == 0 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT op = min ( op , 1 + min_op ( cur + i , M ) ) ; NEW_LINE DEDENT if ( ( cur // i ) != i and ( cur // i ) % 2 == 0 ) : NEW_LINE INDENT op = min ( op , 1 + min_op ( cur + ( cur // i ) , M ) ) NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT dp [ cur ] = op ; NEW_LINE return op NEW_LINE DEDENT def min_operations ( N , M ) : NEW_LINE INDENT for i in range ( N , M + 1 ) : NEW_LINE INDENT dp [ i ] = - 1 ; NEW_LINE DEDENT return min_op ( N , M ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE M = 24 NEW_LINE op = min_operations ( N , M ) ; NEW_LINE if ( op >= INF ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( op ) NEW_LINE DEDENT DEDENT
Maximize Sum possible from an Array by the given moves | 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
def maxValue ( a , n , pos , moves , left , dp ) : NEW_LINE INDENT if ( moves == 0 or ( pos > n - 1 or pos < 0 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ pos ] [ left ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ left ] NEW_LINE DEDENT value = 0 NEW_LINE if ( left > 0 and pos >= 1 ) : NEW_LINE INDENT value = max ( value , a [ pos ] + maxValue ( a , n , pos - 1 , moves - 1 , left - 1 , dp ) ) NEW_LINE DEDENT if ( pos <= n - 1 ) : NEW_LINE INDENT value = max ( value , a [ pos ] + maxValue ( a , n , pos + 1 , moves - 1 , left , dp ) ) NEW_LINE DEDENT dp [ pos ] [ left ] = value NEW_LINE return dp [ pos ] [ left ] NEW_LINE DEDENT n = 5 NEW_LINE a = [ 1 , 5 , 4 , 3 , 2 ] NEW_LINE k = 1 NEW_LINE m = 4 NEW_LINE dp = [ [ - 1 for x in range ( k + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE print ( a [ 0 ] + maxValue ( a , n , 1 , m , k , dp ) ) NEW_LINE
Maximize the Sum of a Subsequence from an Array based on given conditions | 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
def maximumSum ( a , count , index , n , dp ) : NEW_LINE INDENT if ( index == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ index ] [ count ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ count ] NEW_LINE DEDENT take_element = ( a [ index ] * count + maximumSum ( a , count + 1 , index + 1 , n , dp ) ) NEW_LINE dont_take = maximumSum ( a , count , index + 1 , n , dp ) NEW_LINE dp [ index ] [ count ] = max ( take_element , dont_take ) NEW_LINE return dp [ index ] [ count ] NEW_LINE DEDENT n = 5 NEW_LINE a = [ - 1 , - 9 , 0 , 5 , - 7 ] NEW_LINE dp = [ [ - 1 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE print ( maximumSum ( a , 1 , 0 , n , dp ) ) NEW_LINE
Minimum number of Nodes to be removed such that no subtree has more than K nodes | 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 ; ; Insert of nodes in graph ; Required subtree size ; Function Call
N = 20 NEW_LINE visited = [ False for i in range ( N ) ] NEW_LINE K = 0 NEW_LINE removals = 0 NEW_LINE removed_nodes = [ ] NEW_LINE adj = [ [ ] for i in range ( N ) ] NEW_LINE def dfs ( s ) : NEW_LINE INDENT global removals NEW_LINE visited [ s ] = True NEW_LINE nodes = 1 NEW_LINE for child in adj [ s ] : NEW_LINE INDENT if ( visited [ child ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT nodes += dfs ( child ) NEW_LINE DEDENT if ( nodes > K ) : NEW_LINE INDENT removals += 1 NEW_LINE removed_nodes . append ( s ) NEW_LINE nodes = 0 NEW_LINE DEDENT return nodes NEW_LINE DEDENT def addEdge ( a , b ) : NEW_LINE INDENT adj [ a ] . append ( b ) NEW_LINE adj [ b ] . append ( a ) NEW_LINE DEDENT def findRemovedNodes ( K ) : NEW_LINE INDENT dfs ( 1 ) NEW_LINE print ( " Number ▁ of ▁ nodes ▁ removed : ▁ " , removals ) NEW_LINE print ( " Removed ▁ Nodes : ▁ " , end = ' ▁ ' ) NEW_LINE for node in removed_nodes : NEW_LINE INDENT print ( node , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE / * Creating list for all nodes * / NEW_LINE INDENT addEdge ( 1 , 2 ) NEW_LINE addEdge ( 1 , 3 ) NEW_LINE addEdge ( 2 , 4 ) NEW_LINE addEdge ( 2 , 5 ) NEW_LINE addEdge ( 3 , 6 ) NEW_LINE K = 3 NEW_LINE findRemovedNodes ( K ) NEW_LINE DEDENT
Queries to find sum of distance of a given node to every leaf node in a Weighted Tree | 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
N = 10 ** 5 + 5 NEW_LINE v = [ [ ] for i in range ( N ) ] NEW_LINE dp = [ 0 ] * N NEW_LINE leaves = [ 0 ] * ( N ) NEW_LINE n = 0 NEW_LINE def dfs ( a , par ) : NEW_LINE INDENT leaf = 1 NEW_LINE for i in v [ a ] : NEW_LINE INDENT if ( i [ 0 ] == par ) : NEW_LINE INDENT continue NEW_LINE DEDENT leaf = 0 NEW_LINE dfs ( i [ 0 ] , a ) NEW_LINE DEDENT if ( leaf == 1 ) : NEW_LINE INDENT leaves [ a ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT for i in v [ a ] : NEW_LINE INDENT if ( i [ 0 ] == par ) : NEW_LINE INDENT continue NEW_LINE DEDENT leaves [ a ] += leaves [ i [ 0 ] ] NEW_LINE dp [ a ] = ( dp [ a ] + dp [ i [ 0 ] ] + leaves [ i [ 0 ] ] * i [ 1 ] ) NEW_LINE DEDENT DEDENT DEDENT def dfs2 ( a , par ) : NEW_LINE INDENT for i in v [ a ] : NEW_LINE INDENT if ( i [ 0 ] == par ) : NEW_LINE INDENT continue NEW_LINE DEDENT leafOutside = leaves [ a ] - leaves [ i [ 0 ] ] NEW_LINE dp [ i [ 0 ] ] += ( dp [ a ] - dp [ i [ 0 ] ] ) NEW_LINE dp [ i [ 0 ] ] += i [ 1 ] * ( leafOutside - leaves [ i [ 0 ] ] ) NEW_LINE leaves [ i [ 0 ] ] += leafOutside NEW_LINE dfs2 ( i [ 0 ] , a ) NEW_LINE DEDENT DEDENT def answerQueries ( queries ) : NEW_LINE INDENT dfs ( 1 , 0 ) NEW_LINE dfs2 ( 1 , 0 ) NEW_LINE for i in range ( len ( queries ) ) : NEW_LINE INDENT print ( dp [ queries [ i ] ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE v [ 1 ] . append ( [ 4 , 4 ] ) NEW_LINE v [ 4 ] . append ( [ 1 , 4 ] ) NEW_LINE v [ 1 ] . append ( [ 2 , 2 ] ) NEW_LINE v [ 2 ] . append ( [ 1 , 2 ] ) NEW_LINE v [ 2 ] . append ( [ 3 , 3 ] ) NEW_LINE v [ 3 ] . append ( [ 2 , 3 ] ) NEW_LINE v [ 2 ] . append ( [ 5 , 5 ] ) NEW_LINE v [ 5 ] . append ( [ 2 , 5 ] ) NEW_LINE queries = [ 1 , 3 , 5 ] NEW_LINE answerQueries ( queries ) NEW_LINE DEDENT
Minimum changes required to make each path in a matrix palindrome | 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
def countChanges ( matrix , n , m ) : NEW_LINE INDENT dist = n + m - 1 NEW_LINE Max_element = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT Max_element = max ( Max_element , matrix [ i ] [ j ] ) NEW_LINE DEDENT DEDENT freq = [ [ 0 for i in range ( Max_element + 1 ) ] for j in range ( dist ) ] NEW_LINE for i in range ( dist ) : NEW_LINE INDENT for j in range ( Max_element + 1 ) : NEW_LINE INDENT freq [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT freq [ i + j ] [ matrix [ i ] [ j ] ] += 1 NEW_LINE DEDENT DEDENT min_changes_sum = 0 NEW_LINE for i in range ( dist // 2 ) : NEW_LINE INDENT maximum = 0 NEW_LINE total_values = 0 NEW_LINE for j in range ( Max_element + 1 ) : NEW_LINE INDENT maximum = max ( maximum , freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ) NEW_LINE total_values += ( freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ) NEW_LINE DEDENT min_changes_sum += total_values - maximum NEW_LINE DEDENT return min_changes_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 7 , 0 , 3 , 1 , 8 , 1 , 3 ] , [ 0 , 4 , 0 , 1 , 0 , 4 , 0 ] , [ 3 , 1 , 8 , 3 , 1 , 0 , 7 ] ] NEW_LINE minChanges = countChanges ( mat , 3 , 7 ) NEW_LINE print ( minChanges ) NEW_LINE DEDENT
Count of numbers upto N having absolute difference of 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 ] ; Chekc 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 ; Function call
dp = [ [ [ [ - 1 for i in range ( 2 ) ] for j in range ( 2 ) ] for i in range ( 10 ) ] for j in range ( 1002 ) ] NEW_LINE def possibleNumber ( pos , previous , tight , start , N , K ) : NEW_LINE INDENT if ( pos == len ( N ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ pos ] [ previous ] [ tight ] [ start ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ previous ] [ tight ] [ start ] NEW_LINE DEDENT res = 0 NEW_LINE if ( tight ) : NEW_LINE INDENT upper_limit = ord ( N [ pos ] ) - ord ( '0' ) NEW_LINE DEDENT else : NEW_LINE INDENT upper_limit = 9 NEW_LINE DEDENT if ( not start ) : NEW_LINE INDENT res = possibleNumber ( pos + 1 , previous , False , False , N , K ) NEW_LINE for i in range ( 1 , upper_limit + 1 ) : NEW_LINE INDENT if ( tight and i == upper_limit ) : NEW_LINE INDENT new_tight = 1 NEW_LINE DEDENT else : NEW_LINE INDENT new_tight = 0 NEW_LINE DEDENT res += possibleNumber ( pos + 1 , i , new_tight , True , N , K ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( upper_limit + 1 ) : NEW_LINE INDENT if ( tight and i == upper_limit ) : NEW_LINE INDENT new_tight = 1 NEW_LINE DEDENT else : NEW_LINE INDENT new_tight = 0 NEW_LINE DEDENT if ( abs ( i - previous ) <= K ) : NEW_LINE INDENT res += possibleNumber ( pos + 1 , i , new_tight , True , N , K ) NEW_LINE DEDENT DEDENT DEDENT dp [ pos ] [ previous ] [ tight ] [ start ] = res NEW_LINE return dp [ pos ] [ previous ] [ tight ] [ start ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = "20" NEW_LINE K = 2 NEW_LINE print ( possibleNumber ( 0 , 0 , True , False , N , K ) ) NEW_LINE DEDENT
Minimum cost of reducing Array by merging any adjacent elements repetitively | Python3 program for the above approach ; Function to find the total minimum cost of merging two consecutive numbers ; Find the size of numbers [ ] ; If array is empty , return 0 ; To store the prefix Sum of numbers array numbers [ ] ; Traverse numbers [ ] to find the prefix sum ; dp table to memoised the value ; For single numbers cost is zero ; Iterate for length >= 1 ; Find sum in range [ i . . j ] ; Initialise dp [ i ] [ j ] to _MAX ; Iterate for all possible K to find the minimum cost ; Update the minimum sum ; Return the final minimum cost ; Given set of numbers ; Function call
import sys NEW_LINE def mergeTwoNumbers ( numbers ) : NEW_LINE INDENT n = len ( numbers ) NEW_LINE if ( len ( numbers ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT prefixSum = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT prefixSum [ i ] = ( prefixSum [ i - 1 ] + numbers [ i - 1 ] ) NEW_LINE DEDENT dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ i ] = 0 NEW_LINE DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT for i in range ( 1 , n - p + 2 ) : NEW_LINE INDENT j = i + p - 1 NEW_LINE sum = prefixSum [ j ] - prefixSum [ i - 1 ] NEW_LINE dp [ i ] [ j ] = sys . maxsize NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i ] [ j ] , ( dp [ i ] [ k ] + dp [ k + 1 ] [ j ] + sum ) ) NEW_LINE DEDENT DEDENT DEDENT return dp [ 1 ] [ n ] NEW_LINE DEDENT arr1 = [ 6 , 4 , 4 , 6 ] NEW_LINE print ( mergeTwoNumbers ( arr1 ) ) NEW_LINE
Maximum sum possible for every node by including it in a segment of N | Stores the maximum sum possible for every node by including them in a segment with their successors ; Stores the maximum sum possible for every node by including them in a segment with their ancestors ; Store the maximum sum for every node by including it in a segment with its successors ; Update the maximum sums for each node by including them in a sequence with their ancestors ; Condition to check , if current node is not root ; Add edges ; Function to find the maximum answer for each node ; Compute the maximum sums with successors ; Store the computed maximums ; Update the maximum sums by including their ancestors ; Print the desired result ; Driver code ; Number of nodes ; Graph ; Add edges ; Weight of each node ; Compute the max sum of segments for each node ; Print the answer for every node
dp1 = [ 0 for i in range ( 100005 ) ] NEW_LINE dp2 = [ 0 for i in range ( 100005 ) ] NEW_LINE def dfs1 ( u , par , g , weight ) : NEW_LINE INDENT dp1 [ u ] = weight [ u ] NEW_LINE for c in g [ u ] : NEW_LINE INDENT if ( c != par ) : NEW_LINE INDENT dfs1 ( c , u , g , weight ) NEW_LINE dp1 [ u ] += max ( 0 , dp1 ) NEW_LINE DEDENT DEDENT DEDENT def dfs2 ( u , par , g , weight ) : NEW_LINE INDENT if ( par != 0 ) : NEW_LINE INDENT maxSumAncestors = dp2 [ par ] - max ( 0 , dp1 [ u ] ) NEW_LINE dp2 [ u ] = dp1 [ u ] + max ( 0 , maxSumAncestors ) NEW_LINE DEDENT for c in g [ u ] : NEW_LINE INDENT if ( c != par ) : NEW_LINE INDENT dfs2 ( c , u , g , weight ) NEW_LINE DEDENT DEDENT DEDENT def addEdge ( u , v , g ) : NEW_LINE INDENT g [ u ] . append ( v ) NEW_LINE g [ v ] . append ( u ) NEW_LINE DEDENT def maxSumSegments ( g , weight , n ) : NEW_LINE INDENT dfs1 ( 1 , 0 , g , weight ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp2 [ i ] = dp1 [ i ] NEW_LINE DEDENT dfs2 ( 1 , 0 , g , weight ) NEW_LINE DEDENT def printAns ( n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT print ( dp2 [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 NEW_LINE u = 0 NEW_LINE v = 0 NEW_LINE g = [ [ ] for i in range ( 100005 ) ] NEW_LINE addEdge ( 1 , 2 , g ) NEW_LINE addEdge ( 1 , 3 , g ) NEW_LINE addEdge ( 2 , 4 , g ) NEW_LINE addEdge ( 2 , 5 , g ) NEW_LINE addEdge ( 3 , 6 , g ) NEW_LINE addEdge ( 4 , 7 , g ) NEW_LINE weight = [ 0 for i in range ( n + 1 ) ] NEW_LINE weight [ 1 ] = - 8 NEW_LINE weight [ 2 ] = 9 NEW_LINE weight [ 3 ] = 7 NEW_LINE weight [ 4 ] = - 4 NEW_LINE weight [ 5 ] = 5 NEW_LINE weight [ 6 ] = - 10 NEW_LINE weight [ 7 ] = - 6 NEW_LINE maxSumSegments ( g , weight , n ) NEW_LINE printAns ( n ) NEW_LINE DEDENT
Count array elements that can be maximized by adding any permutation of first N natural numbers | Function to get the count of values that can have the maximum value ; Sort array in decreasing order ; Stores the answer ; mark stores the maximum value till each index i ; Check if arr [ i ] can be maximum ; Update the mark ; Print the total count ; Driver Code ; Given array arr ; Function call
def countMaximum ( a , n ) : NEW_LINE INDENT a . sort ( reverse = True ) ; NEW_LINE count = 0 ; NEW_LINE mark = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( a [ i ] + n >= mark ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT mark = max ( mark , a [ i ] + i + 1 ) ; NEW_LINE DEDENT print ( count ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 9 , 6 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE countMaximum ( arr , N ) ; NEW_LINE DEDENT
Count of pairs in an Array with same number of set bits | Function to return the count of Pairs ; Get the maximum element ; Array to store count of bits of all elements upto maxm ; Store the set bits for powers of 2 ; Compute the set bits for the remaining elements ; Store the frequency of respective counts of set bits ; Driver Code
def countPairs ( arr , N ) : NEW_LINE INDENT maxm = max ( arr ) NEW_LINE i = 0 NEW_LINE k = 0 NEW_LINE bitscount = [ 0 for i in range ( maxm + 1 ) ] NEW_LINE i = 1 NEW_LINE while i <= maxm : NEW_LINE INDENT bitscount [ i ] = 1 NEW_LINE i *= 2 NEW_LINE DEDENT for i in range ( 1 , maxm + 1 ) : NEW_LINE INDENT if ( bitscount [ i ] == 1 ) : NEW_LINE INDENT k = i NEW_LINE DEDENT if ( bitscount [ i ] == 0 ) : NEW_LINE INDENT bitscount [ i ] = ( bitscount [ k ] + bitscount [ i - k ] ) NEW_LINE DEDENT DEDENT setbits = dict ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if bitscount [ arr [ i ] ] in setbits : NEW_LINE INDENT setbits [ bitscount [ arr [ i ] ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT setbits [ bitscount [ arr [ i ] ] ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for it in setbits . values ( ) : NEW_LINE INDENT ans += it * ( it - 1 ) // 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 ] NEW_LINE print ( countPairs ( arr , N ) ) NEW_LINE DEDENT
Largest subarray sum of all connected components in undirected graph | Python3 implementation to find largest subarray sum among all connected components ; Function to traverse the undirected graph using the Depth first traversal ; Marking the visited vertex as true ; Store the connected chain ; Recursive call to the DFS algorithm ; Function to return maximum subarray sum of each connected component using Kadane 's Algorithm ; Following loop finds maximum subarray sum based on Kadane 's algorithm ; Global maximum subarray sum ; Returning the sum ; Function to find the maximum subarray sum among all connected components ; Initializing boolean array to mark visited vertices ; maxSum stores the maximum subarray sum ; Following loop invokes DFS algorithm ; Variable to hold temporary length ; Variable to hold temporary maximum subarray sum values ; Container to store each chain ; DFS algorithm ; Variable to hold each chain size ; Container to store values of vertices of individual chains ; Storing the values of each chain ; Function call to find maximum subarray sum of current connection ; Conditional to store current maximum subarray sum ; Printing global maximum subarray sum ; Initializing graph in the form of adjacency list ; Defining the number of edges and vertices ; Assigning the values for each vertex of the undirected graph ; Constructing the undirected graph
import sys NEW_LINE def depthFirst ( v , graph , visited , storeChain ) : NEW_LINE INDENT visited [ v ] = True ; NEW_LINE storeChain . append ( v ) ; NEW_LINE for i in graph [ v ] : NEW_LINE INDENT if ( visited [ i ] == False ) : NEW_LINE INDENT depthFirst ( i , graph , visited , storeChain ) ; NEW_LINE DEDENT DEDENT DEDENT def subarraySum ( arr , n ) : NEW_LINE INDENT maxSubarraySum = arr [ 0 ] ; NEW_LINE currentMax = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT currentMax = max ( arr [ i ] , arr [ i ] + currentMax ) NEW_LINE maxSubarraySum = max ( maxSubarraySum , currentMax ) ; NEW_LINE DEDENT return maxSubarraySum ; NEW_LINE DEDENT def maxSubarraySum ( graph , vertices , values ) : NEW_LINE INDENT visited = [ False for i in range ( 1001 ) ] NEW_LINE maxSum = - sys . maxsize ; NEW_LINE for i in range ( 1 , vertices + 1 ) : NEW_LINE INDENT if ( visited [ i ] == False ) : NEW_LINE INDENT sizeChain = 0 NEW_LINE tempSum = 0 ; NEW_LINE storeChain = [ ] ; NEW_LINE depthFirst ( i , graph , visited , storeChain ) ; NEW_LINE sizeChain = len ( storeChain ) NEW_LINE chainValues = [ 0 for i in range ( sizeChain + 1 ) ] ; NEW_LINE for i in range ( sizeChain ) : NEW_LINE INDENT temp = values [ storeChain [ i ] - 1 ] ; NEW_LINE chainValues [ i ] = temp ; NEW_LINE DEDENT tempSum = subarraySum ( chainValues , sizeChain ) ; NEW_LINE if ( tempSum > maxSum ) : NEW_LINE INDENT maxSum = tempSum ; NEW_LINE DEDENT DEDENT DEDENT print ( " Maximum ▁ subarray ▁ sum ▁ among ▁ all ▁ " , end = ' ' ) ; NEW_LINE print ( " connected ▁ components ▁ = ▁ " , end = ' ' ) NEW_LINE print ( maxSum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT graph = [ [ ] for i in range ( 1001 ) ] NEW_LINE E = 4 ; NEW_LINE V = 7 ; NEW_LINE values = [ ] ; NEW_LINE values . append ( 3 ) ; NEW_LINE values . append ( 2 ) ; NEW_LINE values . append ( 4 ) ; NEW_LINE values . append ( - 2 ) ; NEW_LINE values . append ( 0 ) ; NEW_LINE values . append ( - 1 ) ; NEW_LINE values . append ( - 5 ) ; NEW_LINE graph [ 1 ] . append ( 2 ) ; NEW_LINE graph [ 2 ] . append ( 1 ) ; NEW_LINE graph [ 3 ] . append ( 4 ) ; NEW_LINE graph [ 4 ] . append ( 3 ) ; NEW_LINE graph [ 4 ] . append ( 5 ) ; NEW_LINE graph [ 5 ] . append ( 4 ) ; NEW_LINE graph [ 6 ] . append ( 7 ) ; NEW_LINE graph [ 7 ] . append ( 6 ) ; NEW_LINE maxSubarraySum ( graph , V , values ) ; NEW_LINE DEDENT
Count of Binary strings of length N having atmost M consecutive 1 s or 0 s alternatively exactly K times | List to contain the final result ; Function to get the number of desirable binary strings ; If we reach end of string and groups are exhausted , return 1 ; If length is exhausted but groups are still to be made , return 0 ; If length is not exhausted but groups are exhausted , return 0 ; If both are negative just return 0 ; If already calculated , return it ; Initialise answer for each state ; Loop through every possible m ; Driver code
rows , cols = ( 1000 , 1000 ) NEW_LINE dp = [ [ 0 for i in range ( cols ) ] for j in range ( rows ) ] NEW_LINE def solve ( n , k , m ) : NEW_LINE INDENT if n == 0 and k == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n == 0 and k != 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n != 0 and k == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n < 0 or k < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if dp [ n ] [ k ] : NEW_LINE INDENT return dp [ n ] [ k ] NEW_LINE DEDENT ans = 0 NEW_LINE for j in range ( 1 , m + 1 ) : NEW_LINE INDENT ans = ans + solve ( n - j , k - 1 , m ) NEW_LINE DEDENT dp [ n ] [ k ] = ans NEW_LINE return dp [ n ] [ k ] NEW_LINE DEDENT N = 7 NEW_LINE K = 4 NEW_LINE M = 3 NEW_LINE print ( solve ( N , K , M ) ) NEW_LINE
Maximum neighbor element in a matrix within distance K | Function to print the matrix ; Loop to iterate over the matrix ; Function to find the maximum neighbor within the distance of less than equal to K ; Loop to find the maximum element within the distance of less than K ; Driver Code
def printMatrix ( A ) : NEW_LINE INDENT for i in range ( len ( A ) ) : NEW_LINE INDENT for j in range ( len ( A [ 0 ] ) ) : NEW_LINE INDENT print ( A [ i ] [ j ] , end = ' ▁ ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def getMaxNeighbour ( A , K ) : NEW_LINE INDENT ans = A ; NEW_LINE for q in range ( 1 , K + 1 ) : NEW_LINE INDENT for i in range ( len ( A ) ) : NEW_LINE INDENT for j in range ( len ( A [ 0 ] ) ) : NEW_LINE INDENT maxi = ans [ i ] [ j ] ; NEW_LINE if ( i > 0 ) : NEW_LINE INDENT maxi = max ( maxi , ans [ i - 1 ] [ j ] ) ; NEW_LINE DEDENT if ( j > 0 ) : NEW_LINE INDENT maxi = max ( maxi , ans [ i ] [ j - 1 ] ) ; NEW_LINE DEDENT if ( i < len ( A ) - 1 ) : NEW_LINE INDENT maxi = max ( maxi , ans [ i + 1 ] [ j ] ) ; NEW_LINE DEDENT if ( j < len ( A [ 0 ] ) - 1 ) : NEW_LINE INDENT maxi = max ( maxi , ans [ i ] [ j + 1 ] ) ; NEW_LINE DEDENT A [ i ] [ j ] = maxi ; NEW_LINE DEDENT DEDENT ans = A ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT B = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE printMatrix ( getMaxNeighbour ( B , 2 ) ) ; NEW_LINE DEDENT
Number of distinct ways to represent a number as sum of K unique primes | Prime list ; Sieve array of prime ; DP array ; Sieve of Eratosthenes . ; Push all the primes into prime vector ; Function to get the number of distinct ways to get sum as K different primes ; If index went out of prime array size or the sum became larger than n return 0 ; If sum becomes equal to n and j becomes exactly equal to k . Return 1 , else if j is still not equal to k , return 0 ; If sum != n and still j as exceeded , return 0 ; If that state is already calculated , return directly the ans ; Include the current prime ; Exclude the current prime ; Return by memoizing the ans ; Driver code ; Precompute primes by sieve
prime = [ ] NEW_LINE isprime = [ True ] * 1000 NEW_LINE dp = [ [ [ '0' for col in range ( 200 ) ] for col in range ( 20 ) ] for row in range ( 1000 ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT for i in range ( 2 , 1000 ) : NEW_LINE INDENT if ( isprime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , 1000 , i ) : NEW_LINE INDENT isprime [ j ] = False NEW_LINE DEDENT DEDENT DEDENT for i in range ( 2 , 1000 ) : NEW_LINE INDENT if ( isprime [ i ] ) : NEW_LINE INDENT prime . append ( i ) NEW_LINE DEDENT DEDENT DEDENT def CountWays ( i , j , sums , n , k ) : NEW_LINE INDENT if ( i >= len ( prime ) or sums > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( sums == n ) : NEW_LINE INDENT if ( j == k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if j == k : NEW_LINE INDENT return 0 NEW_LINE DEDENT if dp [ i ] [ j ] [ sums ] == 0 : NEW_LINE INDENT return dp [ i ] [ j ] [ sums ] NEW_LINE DEDENT inc = 0 NEW_LINE exc = 0 NEW_LINE inc = CountWays ( i + 1 , j + 1 , sums + prime [ i ] , n , k ) NEW_LINE exc = CountWays ( i + 1 , j , sums , n , k ) NEW_LINE dp [ i ] [ j ] [ sums ] = inc + exc NEW_LINE return dp [ i ] [ j ] [ sums ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT sieve ( ) NEW_LINE N = 100 NEW_LINE K = 5 NEW_LINE print ( CountWays ( 0 , 0 , 0 , N , K ) ) NEW_LINE DEDENT
Count minimum factor jumps required to reach the end of an Array | Vector to store factors of each integer ; Initialize the dp array ; Precompute all the factors of every integer ; Function to count the minimum factor jump ; 0 jumps required to reach the first cell ; Iterate over all cells ; calculating for each jump ; If a cell is in bound ; Return minimum jumps to reach last cell ; Driver code ; Pre - calculating the factors ; Function call
factors = [ [ ] for i in range ( 100005 ) ] ; NEW_LINE dp = [ 1000000000 for i in range ( 100005 ) ] ; NEW_LINE def precompute ( ) : NEW_LINE INDENT for i in range ( 1 , 100001 ) : NEW_LINE INDENT for j in range ( i , 100001 , i ) : NEW_LINE INDENT factors [ j ] . append ( i ) ; NEW_LINE DEDENT DEDENT DEDENT def solve ( arr , n ) : NEW_LINE INDENT dp [ 0 ] = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in factors [ arr [ i ] ] : NEW_LINE INDENT if ( i + j < n ) : NEW_LINE INDENT dp [ i + j ] = min ( dp [ i + j ] , 1 + dp [ i ] ) ; NEW_LINE DEDENT DEDENT DEDENT return dp [ n - 1 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT precompute ( ) ; NEW_LINE arr = [ 2 , 8 , 16 , 55 , 99 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE print ( solve ( arr , n ) ) NEW_LINE DEDENT
Find the length of the Largest subset such that all elements are Pairwise Coprime | Dynamic programming table ; Function to obtain the mask for any integer ; List of prime numbers till 50 ; Iterate through all prime numbers to obtain the mask ; Set this prime 's bit ON in the mask ; Return the mask value ; Function to count the number of ways ; Check if subproblem has been solved ; Excluding current element in the subset ; Check if there are no common prime factors then only this element can be included ; Calculate the new mask if this element is included ; Store and return the answer ; Function to find the count of subarray with all digits unique ; Driver code
dp = [ [ - 1 ] * ( ( 1 << 10 ) + 5 ) ] * 5000 NEW_LINE def getmask ( val ) : NEW_LINE INDENT mask = 0 NEW_LINE prime = [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 ] NEW_LINE for i in range ( 1 , 15 ) : NEW_LINE INDENT if val % prime [ i ] == 0 : NEW_LINE INDENT mask = mask | ( 1 << i ) NEW_LINE DEDENT DEDENT return mask NEW_LINE DEDENT def calculate ( pos , mask , a , n ) : NEW_LINE INDENT if ( ( pos == n ) or ( mask == ( 1 << n - 1 ) ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if dp [ pos ] [ mask ] != - 1 : NEW_LINE INDENT return dp [ pos ] [ mask ] NEW_LINE DEDENT size = 0 NEW_LINE size = max ( size , calculate ( pos + 1 , mask , a , n ) ) NEW_LINE if ( getmask ( a [ pos ] ) & mask ) == 0 : NEW_LINE INDENT new_mask = ( mask | ( getmask ( a [ pos ] ) ) ) NEW_LINE size = max ( size , 1 + calculate ( pos + 1 , new_mask , a , n ) ) NEW_LINE DEDENT dp [ pos ] [ mask ] = size NEW_LINE return dp [ pos ] [ mask ] NEW_LINE DEDENT def largestSubset ( A , n ) : NEW_LINE INDENT return calculate ( 0 , 0 , A , n ) ; NEW_LINE DEDENT A = [ 2 , 3 , 13 , 5 , 14 , 6 , 7 , 11 ] NEW_LINE N = len ( A ) NEW_LINE print ( largestSubset ( A , N ) ) NEW_LINE
Maximum sum such that exactly half of the elements are selected and no two adjacent | Function return the maximum sum possible under given condition ; Base case ; When i is odd ; When i is even ; Maximum of if we pick last element or not ; Driver code
def MaximumSum ( a , n ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( 2 ) ] for y in range ( n + 1 ) ] NEW_LINE dp [ 2 ] [ 1 ] = a [ 1 ] NEW_LINE dp [ 2 ] [ 0 ] = a [ 0 ] NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT temp = max ( [ dp [ i - 3 ] [ 1 ] , dp [ i - 3 ] [ 0 ] , dp [ i - 2 ] [ 1 ] , dp [ i - 2 ] [ 0 ] ] ) NEW_LINE dp [ i ] [ 1 ] = a [ i - 1 ] + temp NEW_LINE dp [ i ] [ 0 ] = max ( [ a [ i - 2 ] + dp [ i - 2 ] [ 0 ] , a [ i - 2 ] + dp [ i - 3 ] [ 1 ] , a [ i - 2 ] + dp [ i - 3 ] [ 0 ] , a [ i - 3 ] + dp [ i - 3 ] [ 0 ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ 1 ] = ( a [ i - 1 ] + max ( [ dp [ i - 2 ] [ 1 ] , dp [ i - 2 ] [ 0 ] , dp [ i - 1 ] [ 0 ] ] ) ) NEW_LINE dp [ i ] [ 0 ] = a [ i - 2 ] + dp [ i - 2 ] [ 0 ] NEW_LINE DEDENT DEDENT return max ( dp [ n ] [ 1 ] , dp [ n ] [ 0 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE N = len ( A ) NEW_LINE print ( MaximumSum ( A , N ) ) NEW_LINE DEDENT
Optimal Strategy for the Divisor game using Dynamic Programming | Python3 program for implementation of Optimal Strategy for the Divisor Game using Dynamic Programming ; Recursive function to find the winner ; check if N = 1 or N = 3 then player B wins ; check if N = 2 then player A wins ; check if current state already visited then return the previously obtained ans ; check if currently it is player A 's turn then initialise the ans to 0 ; Traversing across all the divisors of N which are less than N ; check if current value of i is a divisor of N ; check if it is player A 's turn then we need at least one true ; Else if it is player B 's turn then we need at least one false ; Return the current ans ; Driver code ; initialise N
from math import sqrt NEW_LINE def divisorGame ( N , A , dp ) : NEW_LINE INDENT if ( N == 1 or N == 3 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( dp [ N ] [ A ] != - 1 ) : NEW_LINE INDENT return dp [ N ] [ A ] NEW_LINE DEDENT if ( A == 1 ) : NEW_LINE INDENT ans = 0 NEW_LINE DEDENT else : NEW_LINE INDENT ans = 1 NEW_LINE DEDENT for i in range ( 1 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( A ) : NEW_LINE INDENT ans |= divisorGame ( N - i , 0 , dp ) NEW_LINE DEDENT else : NEW_LINE INDENT ans &= divisorGame ( N - i , 1 , dp ) NEW_LINE DEDENT DEDENT DEDENT dp [ N ] [ A ] = ans NEW_LINE return dp [ N ] [ A ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE dp = [ [ - 1 for i in range ( 2 ) ] for j in range ( N + 1 ) ] NEW_LINE if ( divisorGame ( N , 1 , dp ) == True ) : NEW_LINE INDENT print ( " Player ▁ A ▁ wins " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Player ▁ B ▁ wins " ) NEW_LINE DEDENT DEDENT
Find the count of mountains in a given Matrix | Python3 program find the count of mountains in a given Matrix ; Function to count number of mountains in a given matrix of size n ; form another matrix with one extra layer of border elements . Border elements will contain INT_MIN value . ; For border elements , set value as INT_MIN ; For rest elements , just copy it into new matrix ; Check for mountains in the modified matrix ; check for all directions ; Driver code
MAX = 100 NEW_LINE def countMountains ( a , n ) : NEW_LINE INDENT A = [ [ 0 for i in range ( n + 2 ) ] for i in range ( n + 2 ) ] NEW_LINE count = 0 NEW_LINE for i in range ( n + 2 ) : NEW_LINE INDENT for j in range ( n + 2 ) : NEW_LINE INDENT if ( ( i == 0 ) or ( j == 0 ) or ( i == n + 1 ) or ( j == n + 1 ) ) : NEW_LINE INDENT A [ i ] [ j ] = float ( ' - inf ' ) NEW_LINE DEDENT else : NEW_LINE INDENT A [ i ] [ j ] = a [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( ( A [ i ] [ j ] > A [ i - 1 ] [ j ] ) and ( A [ i ] [ j ] > A [ i + 1 ] [ j ] ) and ( A [ i ] [ j ] > A [ i ] [ j - 1 ] ) and ( A [ i ] [ j ] > A [ i ] [ j + 1 ] ) and ( A [ i ] [ j ] > A [ i - 1 ] [ j - 1 ] ) and ( A [ i ] [ j ] > A [ i + 1 ] [ j + 1 ] ) and ( A [ i ] [ j ] > A [ i - 1 ] [ j + 1 ] ) and ( A [ i ] [ j ] > A [ i + 1 ] [ j - 1 ] ) ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT a = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE n = 3 NEW_LINE print ( countMountains ( a , n ) ) NEW_LINE
Minimum length of the reduced Array formed using given operations | Python3 implementation to find the minimum length of the array ; Function to find the length of minimized array ; Creating the required dp tables Initialising the dp table by - 1 ; base case ; Check if the two subarray can be combined ; Initialising dp1 table with max value ; Check if the subarray can be reduced to a single element ; Minimal partition of [ 1 : j - 1 ] + 1 ; Driver code
import numpy as np NEW_LINE def minimalLength ( a , n ) : NEW_LINE INDENT dp = np . ones ( ( n + 1 , n + 1 ) ) * - 1 ; NEW_LINE dp1 = [ 0 ] * n ; NEW_LINE for size in range ( 1 , n + 1 ) : NEW_LINE INDENT for i in range ( n - size + 1 ) : NEW_LINE INDENT j = i + size - 1 ; NEW_LINE if ( i == j ) : NEW_LINE INDENT dp [ i ] [ j ] = a [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT for k in range ( i , j ) : NEW_LINE INDENT if ( dp [ i ] [ k ] != - 1 and dp [ i ] [ k ] == dp [ k + 1 ] [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i ] [ k ] + 1 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT dp1 [ i ] = int ( 1e7 ) ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT if ( dp [ j ] [ i ] != - 1 ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT dp1 [ i ] = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT dp1 [ i ] = min ( dp1 [ i ] , dp1 [ j - 1 ] + 1 ) ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return dp1 [ n - 1 ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 7 ; NEW_LINE a = [ 3 , 3 , 4 , 4 , 4 , 3 , 3 ] ; NEW_LINE print ( minimalLength ( a , n ) ) ; NEW_LINE DEDENT
Maximum score possible after performing given operations on an Array | Memoizing by the use of a table ; Function to calculate maximum score ; Bse case ; If the same state has already been computed ; Sum of array in range ( l , r ) ; If the operation is even - numbered the score is decremented ; Exploring all paths , and storing maximum value in DP table to avoid further repetitive recursive calls ; Function to find the max score ; Prefix sum array ; Calculating prefix_sum ; Initialising the DP table , - 1 represents the subproblem hasn 't been solved yet ; Driver code
dp = [ [ [ - 1 for x in range ( 100 ) ] for y in range ( 100 ) ] for z in range ( 100 ) ] NEW_LINE def MaximumScoreDP ( l , r , prefix_sum , num ) : NEW_LINE INDENT if ( l > r ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ l ] [ r ] [ num ] != - 1 ) : NEW_LINE INDENT return dp [ l ] [ r ] [ num ] NEW_LINE DEDENT current_sum = prefix_sum [ r ] NEW_LINE if ( l - 1 >= 0 ) : NEW_LINE INDENT current_sum -= prefix_sum [ l - 1 ] NEW_LINE DEDENT if ( num % 2 == 0 ) : NEW_LINE INDENT current_sum *= - 1 NEW_LINE DEDENT dp [ l ] [ r ] [ num ] = ( current_sum + max ( MaximumScoreDP ( l + 1 , r , prefix_sum , num + 1 ) , MaximumScoreDP ( l , r - 1 , prefix_sum , num + 1 ) ) ) NEW_LINE return dp [ l ] [ r ] [ num ] NEW_LINE DEDENT def findMaxScore ( a , n ) : NEW_LINE INDENT prefix_sum = [ 0 ] * n NEW_LINE prefix_sum [ 0 ] = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix_sum [ i ] = prefix_sum [ i - 1 ] + a [ i ] NEW_LINE DEDENT global dp NEW_LINE return MaximumScoreDP ( 0 , n - 1 , prefix_sum , 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 NEW_LINE A = [ 1 , 2 , 3 , 4 , 2 , 6 ] NEW_LINE print ( findMaxScore ( A , n ) ) NEW_LINE DEDENT
Count number of binary strings without consecutive 1 Γ’ €ℒ s : Set 2 | Table to store the solution of every sub problem ; Here , pos : keeps track of current position . f1 : is the flag to check if current number is less than N or not . pr : represents the previous digit ; Base case ; Check if this subproblem has already been solved ; Placing 0 at the current position as it does not violate the condition ; Here flag will be 1 for the next recursive call ; Placing 1 at this position only if the previously inserted number is 0 ; If the number is smaller than N ; If the digit at current position is 1 ; Storing the solution to this subproblem ; Function to find the number of integers less than or equal to N with no consecutive 1 aTMs in binary representation ; Convert N to binary form ; Loop to convert N from Decimal to binary ; Calling the function ; Driver code
memo = [ [ [ - 1 for i in range ( 2 ) ] for j in range ( 2 ) ] for k in range ( 32 ) ] NEW_LINE def dp ( pos , fl , pr , bin ) : NEW_LINE INDENT if ( pos == len ( bin ) ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( memo [ pos ] [ fl ] [ pr ] != - 1 ) : NEW_LINE INDENT return memo [ pos ] [ fl ] [ pr ] ; NEW_LINE DEDENT val = 0 NEW_LINE if ( bin [ pos ] == '0' ) : NEW_LINE INDENT val = val + dp ( pos + 1 , fl , 0 , bin ) NEW_LINE DEDENT elif ( bin [ pos ] == '1' ) : NEW_LINE INDENT val = val + dp ( pos + 1 , 1 , 0 , bin ) NEW_LINE DEDENT if ( pr == 0 ) : NEW_LINE INDENT if ( fl == 1 ) : NEW_LINE INDENT val += dp ( pos + 1 , fl , 1 , bin ) NEW_LINE DEDENT elif ( bin [ pos ] == '1' ) : NEW_LINE INDENT val += dp ( pos + 1 , fl , 1 , bin ) NEW_LINE DEDENT DEDENT memo [ pos ] [ fl ] [ pr ] = val NEW_LINE return val NEW_LINE DEDENT def findIntegers ( num ) : NEW_LINE INDENT bin = " " NEW_LINE while ( num > 0 ) : NEW_LINE INDENT if ( num % 2 ) : NEW_LINE INDENT bin += "1" NEW_LINE DEDENT else : NEW_LINE INDENT bin += "0" NEW_LINE DEDENT num //= 2 NEW_LINE DEDENT bin = bin [ : : - 1 ] ; NEW_LINE return dp ( 0 , 0 , 0 , bin ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 12 NEW_LINE print ( findIntegers ( N ) ) NEW_LINE DEDENT
Count ways to reach end from start stone with at most K jumps at each step | Function which returns total no . of ways to reach nth step from sth steps ; Initialize dp array ; Initialize ( s - 1 ) th index to 1 ; Iterate a loop from s to n ; starting range for counting ranges ; Calculate Maximum moves to Reach ith step ; For nth step return dp [ n - 1 ] ; Driver Code ; no of steps ; Atmost steps allowed ; starting range
def TotalWays ( n , s , k ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE dp [ s - 1 ] = 1 NEW_LINE for i in range ( s , n ) : NEW_LINE INDENT idx = max ( s - 1 , i - k ) NEW_LINE for j in range ( idx , i ) : NEW_LINE INDENT dp [ i ] += dp [ j ] NEW_LINE DEDENT DEDENT return dp [ n - 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE k = 2 NEW_LINE s = 2 NEW_LINE print ( " Total ▁ Ways ▁ = ▁ " , TotalWays ( n , s , k ) ) NEW_LINE DEDENT
Maximum subsequence sum with adjacent elements having atleast K difference in index | Function to find the maximum sum subsequence such that two adjacent element have atleast difference of K in their indices ; DP Array to store the maximum sum obtained till now ; Either select the first element or Nothing ; Either Select the ( i - 1 ) element or let the previous best answer be the current best answer ; Either select the best sum till previous_index or select the current element + best_sum till index - k ; Driver Code
def max_sum ( arr , n , k ) : NEW_LINE INDENT dp = [ 0 ] * n ; NEW_LINE dp [ 0 ] = max ( 0 , arr [ 0 ] ) ; NEW_LINE i = 1 ; NEW_LINE while ( i < k ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i - 1 ] , arr [ i ] ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT i = k ; NEW_LINE while ( i < n ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i - 1 ] , arr [ i ] + dp [ i - k ] ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT return dp [ n - 1 ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , - 2 , 4 , 3 , 1 ] ; NEW_LINE n = len ( arr ) NEW_LINE k = 4 ; NEW_LINE print ( max_sum ( arr , n , k ) ) ; NEW_LINE DEDENT
Number of binary strings such that there is no substring of length Γ’ ‰Β₯ 3 | Python3 implementation of the approach ; Function to return the count of all possible binary strings ; Base cases ; dp [ i ] [ j ] is the number of possible strings such that '1' just appeared consecutively j times upto ith index ; Taking previously calculated value ; Taking all the possible cases that can appear at the Nth position ; Driver code
MOD = 1000000007 NEW_LINE def countStr ( N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 3 ) ] for i in range ( N + 1 ) ] NEW_LINE dp [ 1 ] [ 0 ] = 1 NEW_LINE dp [ 1 ] [ 1 ] = 1 NEW_LINE dp [ 1 ] [ 2 ] = 0 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] + dp [ i - 1 ] [ 2 ] ) % MOD NEW_LINE dp [ i ] [ 1 ] = dp [ i - 1 ] [ 0 ] % MOD NEW_LINE dp [ i ] [ 2 ] = dp [ i - 1 ] [ 1 ] % MOD NEW_LINE DEDENT ans = ( dp [ N ] [ 0 ] + dp [ N ] [ 1 ] + dp [ N ] [ 2 ] ) % MOD NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE print ( countStr ( N ) ) NEW_LINE DEDENT
Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | Python program to find the maximum count of 1 s ; If arr [ i - 2 ] = = 1 then we increment the count of occurences of 1 's ; Else we initialise the count with 0 ; If arr [ i + 2 ] = = 1 then we increment the count of occurences of 1 's ; Else we initialise the count with 0 ; We get the maximum count by skipping the current and the next element . ; Driver code
def maxLengthOf1s ( arr , n ) : NEW_LINE INDENT prefix = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( arr [ i - 2 ] == 1 ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT prefix [ i ] = 0 NEW_LINE DEDENT DEDENT suffix = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n - 3 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i + 2 ] == 1 ) : NEW_LINE INDENT suffix [ i ] = suffix [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT suffix [ i ] = 0 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT ans = max ( ans , prefix [ i + 1 ] + suffix [ i ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT n = 6 NEW_LINE arr = [ 1 , 1 , 1 , 0 , 1 , 1 ] NEW_LINE maxLengthOf1s ( arr , n ) NEW_LINE
Count number of ways to get Odd Sum | Count the ways to sum up with odd by choosing one element form each pair ; Initialize two array with 0 ; if element is even ; store count of even number in i 'th pair ; if the element is odd ; store count of odd number in i 'th pair ; Initial state of dp array ; dp [ i ] [ 0 ] = total number of ways to get even sum upto i 'th pair ; dp [ i ] [ 1 ] = total number of ways to odd even sum upto i 'th pair ; dp [ n - 1 ] [ 1 ] = total number of ways to get odd sum upto n 'th pair ; Driver code
def CountOfOddSum ( a , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for i in range ( n ) ] NEW_LINE cnt = [ [ 0 for i in range ( 2 ) ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT if ( a [ i ] [ j ] % 2 == 0 ) : NEW_LINE INDENT cnt [ i ] [ 0 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt [ i ] [ 1 ] += 1 NEW_LINE DEDENT DEDENT DEDENT dp [ 0 ] [ 0 ] = cnt [ 0 ] [ 0 ] NEW_LINE dp [ 0 ] [ 1 ] = cnt [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] * cnt [ i ] [ 0 ] + dp [ i - 1 ] [ 1 ] * cnt [ i ] [ 1 ] ) NEW_LINE dp [ i ] [ 1 ] = ( dp [ i - 1 ] [ 0 ] * cnt [ i ] [ 1 ] + dp [ i - 1 ] [ 1 ] * cnt [ i ] [ 0 ] ) NEW_LINE DEDENT return dp [ n - 1 ] [ 1 ] NEW_LINE DEDENT a = [ [ 1 , 2 ] , [ 3 , 6 ] ] NEW_LINE n = len ( a ) NEW_LINE ans = CountOfOddSum ( a , n ) NEW_LINE print ( ans ) NEW_LINE
Longest Consecuetive Subsequence when only one insert operation is allowed | Function to return the length of longest consecuetive subsequence after inserting an element ; Variable to find maximum value of the array ; Calculating maximum value of the array ; Declaring the DP table ; Variable to store the maximum length ; Iterating for every value present in the array ; Recurrence for dp [ val ] [ 0 ] ; No value can be inserted before 1 , hence the element value should be greater than 1 for this recurrance relation ; Recurrence for dp [ val ] [ 1 ] ; Maximum length of consecutive sequence ending at 1 is equal to 1 ; Update the ans variable with the new maximum length possible ; Return the ans ; Input array
def LongestConsSeq ( arr , N ) : NEW_LINE INDENT maxval = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT maxval = max ( maxval , arr [ i ] ) NEW_LINE DEDENT dp = [ [ 0 for i in range ( 2 ) ] for i in range ( maxval + 1 ) ] NEW_LINE ans = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT dp [ arr [ i ] ] [ 0 ] = 1 + dp [ arr [ i ] - 1 ] [ 0 ] NEW_LINE if ( arr [ i ] >= 2 ) : NEW_LINE INDENT dp [ arr [ i ] ] [ 1 ] = max ( 1 + dp [ arr [ i ] - 1 ] [ 1 ] , 2 + dp [ arr [ i ] - 2 ] [ 0 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ arr [ i ] ] [ 1 ] = 1 NEW_LINE DEDENT ans = max ( ans , dp [ arr [ i ] ] [ 1 ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 1 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( LongestConsSeq ( arr , N ) ) NEW_LINE
Stepping Numbers | This function checks if an integer n is a Stepping Number ; Initalize prevDigit with - 1 ; Iterate through all digits of n and compare difference between value of previous and current digits ; Get Current digit ; Single digit is consider as a Stepping Number ; Check if absolute difference between prev digit and current digit is 1 ; A brute force approach based function to find all stepping numbers . ; Iterate through all the numbers from [ N , M ] and check if its a stepping number . ; Driver code ; Display Stepping Numbers in the range [ n , m ]
def isStepNum ( n ) : NEW_LINE INDENT prevDigit = - 1 NEW_LINE while ( n ) : NEW_LINE INDENT curDigit = n % 10 NEW_LINE if ( prevDigit == - 1 ) : NEW_LINE INDENT prevDigit = curDigit NEW_LINE DEDENT else : NEW_LINE INDENT if ( abs ( prevDigit - curDigit ) != 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT prevDigit = curDigit NEW_LINE n //= 10 NEW_LINE DEDENT return True NEW_LINE DEDENT def displaySteppingNumbers ( n , m ) : NEW_LINE INDENT for i in range ( n , m + 1 ) : NEW_LINE INDENT if ( isStepNum ( i ) ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n , m = 0 , 21 NEW_LINE displaySteppingNumbers ( n , m ) NEW_LINE DEDENT
Count numbers in given range such that sum of even digits is greater than sum of odd digits | Python code to count number in the range having the sum of even digits greater than the sum of odd digits ; Base Case ; check if condition satisfied or not ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 0 , means number has already become smaller so we can place any digit , otherwise num [ index ] ; if current digit is odd ; if current digit is even ; Function to convert n into its digit vector and uses memo ( ) function to return the required count ; Initialize dp ; Driver Code
def memo ( index , evenSum , oddSum , tight ) : NEW_LINE INDENT if index == len ( v ) : NEW_LINE INDENT if evenSum > oddSum : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if dp [ index ] [ evenSum ] [ oddSum ] [ tight ] != - 1 : NEW_LINE INDENT return dp [ index ] [ evenSum ] [ oddSum ] [ tight ] NEW_LINE DEDENT limit = v [ index ] if tight else 9 NEW_LINE ans = 0 NEW_LINE for d in range ( limit + 1 ) : NEW_LINE INDENT currTight = 0 NEW_LINE if d == v [ index ] : NEW_LINE INDENT currTight = tight NEW_LINE DEDENT if d % 2 != 0 : NEW_LINE INDENT ans += memo ( index + 1 , evenSum , oddSum + d , currTight ) NEW_LINE DEDENT else : NEW_LINE INDENT ans += memo ( index + 1 , evenSum + d , oddSum , currTight ) NEW_LINE DEDENT DEDENT dp [ index ] [ evenSum ] [ oddSum ] [ tight ] = ans NEW_LINE return ans NEW_LINE DEDENT def countNum ( n ) : NEW_LINE INDENT global dp , v NEW_LINE v . clear ( ) NEW_LINE num = [ ] NEW_LINE while n : NEW_LINE INDENT v . append ( n % 10 ) NEW_LINE n //= 10 NEW_LINE DEDENT v . reverse ( ) NEW_LINE dp = [ [ [ [ - 1 , - 1 ] for i in range ( 180 ) ] for j in range ( 180 ) ] for k in range ( 18 ) ] NEW_LINE return memo ( 0 , 0 , 0 , 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT dp = [ ] NEW_LINE v = [ ] NEW_LINE L = 2 NEW_LINE R = 10 NEW_LINE print ( countNum ( R ) - countNum ( L - 1 ) ) NEW_LINE DEDENT
Maximum sub | Function to return the maximum sum of the sub - sequence such that two consecutive elements have a difference of at least 3 in their indices in the given array ; If there is a single element in the array ; Either select it or don 't ; If there are two elements ; Either select the first element or don 't ; Either select the first or the second element or don 't select any element ; Either select the first element or don 't ; Either select the first or the second element or don 't select any element ; Either select first , second , third or nothing ; For the rest of the elements ; Either select the best sum till previous_index or select the current element + best_sum till index - 3 ; Driver code
def max_sum ( a , n ) : NEW_LINE INDENT dp = [ 0 ] * n ; NEW_LINE if ( n == 1 ) : NEW_LINE INDENT dp [ 0 ] = max ( 0 , a [ 0 ] ) ; NEW_LINE DEDENT elif ( n == 2 ) : NEW_LINE INDENT dp [ 0 ] = max ( 0 , a [ 0 ] ) ; NEW_LINE dp [ 1 ] = max ( a [ 1 ] , dp [ 0 ] ) ; NEW_LINE DEDENT elif ( n >= 3 ) : NEW_LINE INDENT dp [ 0 ] = max ( 0 , a [ 0 ] ) ; NEW_LINE dp [ 1 ] = max ( a [ 1 ] , max ( 0 , a [ 0 ] ) ) ; NEW_LINE dp [ 2 ] = max ( a [ 2 ] , max ( a [ 1 ] , max ( 0 , a [ 0 ] ) ) ) ; NEW_LINE i = 3 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i - 1 ] , a [ i ] + dp [ i - 3 ] ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT DEDENT return dp [ n - 1 ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , - 2 , 4 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( max_sum ( arr , n ) ) ; NEW_LINE DEDENT
Minimum count of elements that sums to a given number | Python3 implementation of the above approach ; we will only store min counts of sum upto 100 ; memo [ 0 ] = 0 as 0 is made from 0 elements ; fill memo array with min counts of elements that will constitute sum upto 100 ; min_count will store min count of elements chosen ; starting from end iterate over each 2 digits and add min count of elements to min_count ; Driver code
def minCount ( K ) : NEW_LINE INDENT memo = [ 10 ** 9 for i in range ( 100 ) ] NEW_LINE memo [ 0 ] = 0 NEW_LINE for i in range ( 1 , 100 ) : NEW_LINE INDENT memo [ i ] = min ( memo [ i - 1 ] + 1 , memo [ i ] ) NEW_LINE DEDENT for i in range ( 10 , 100 ) : NEW_LINE INDENT memo [ i ] = min ( memo [ i - 10 ] + 1 , memo [ i ] ) NEW_LINE DEDENT for i in range ( 25 , 100 ) : NEW_LINE INDENT memo [ i ] = min ( memo [ i - 25 ] + 1 , memo [ i ] ) NEW_LINE DEDENT min_count = 0 NEW_LINE while ( K > 0 ) : NEW_LINE INDENT min_count += memo [ K % 100 ] NEW_LINE K //= 100 NEW_LINE DEDENT return min_count NEW_LINE DEDENT K = 69 NEW_LINE print ( minCount ( K ) ) NEW_LINE
Number of sub | Python3 implementation of the approach ; Function to return the number of subsequences which have at least one consecutive pair with difference less than or equal to 1 ; Not required sub - sequences which turn required on adding i ; Required sub - sequence till now will be required sequence plus sub - sequence which turns required ; Similarly for not required ; Also updating total required and not required sub - sequences ; Also , storing values in dp ; Driver code
import numpy as np ; NEW_LINE N = 10000 ; NEW_LINE def count_required_sequence ( n , arr ) : NEW_LINE INDENT total_required_subsequence = 0 ; NEW_LINE total_n_required_subsequence = 0 ; NEW_LINE dp = np . zeros ( ( N , 2 ) ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT turn_required = 0 ; NEW_LINE for j in range ( - 1 , 2 , 1 ) : NEW_LINE INDENT turn_required += dp [ arr [ i ] + j ] [ 0 ] ; NEW_LINE DEDENT required_end_i = ( total_required_subsequence + turn_required ) ; NEW_LINE n_required_end_i = ( 1 + total_n_required_subsequence - turn_required ) ; NEW_LINE total_required_subsequence += required_end_i ; NEW_LINE total_n_required_subsequence += n_required_end_i ; NEW_LINE dp [ arr [ i ] ] [ 1 ] += required_end_i ; NEW_LINE dp [ arr [ i ] ] [ 0 ] += n_required_end_i ; NEW_LINE DEDENT return total_required_subsequence ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 6 , 2 , 1 , 9 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( count_required_sequence ( n , arr ) ) ; NEW_LINE DEDENT
Number of ways to choose elements from the array such that their average is K | Python implementation of above approach ; Initialize dp array by - 1 ; Base cases Index can 't be less than 0 ; No element is picked hence average cannot be calculated ; If remainder is non zero , we cannot divide the sum by count i . e . the average will not be an integer ; If we find an average return 1 ; If we have already calculated this function simply return it instead of calculating it again ; If we don 't pick the current element simple recur for index -1 ; If we pick the current element add it to our current sum and increment count by 1 ; Store the value for the current function ; Function to return the number of ways ; Push - 1 at the beginning to make it 1 - based indexing ; Call recursive function waysutil to calculate total ways ; Driver code
import numpy as np NEW_LINE MAX_INDEX = 51 NEW_LINE MAX_SUM = 2505 NEW_LINE dp = np . ones ( ( MAX_INDEX , MAX_SUM , MAX_INDEX ) ) * - 1 ; NEW_LINE def waysutil ( index , sum , count , arr , K ) : NEW_LINE INDENT if ( index < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( index == 0 ) : NEW_LINE INDENT if ( count == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT remainder = sum % count ; NEW_LINE if ( remainder != 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT average = sum // count ; NEW_LINE if ( average == K ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT DEDENT if ( dp [ index ] [ sum ] [ count ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ sum ] [ count ] ; NEW_LINE DEDENT dontpick = waysutil ( index - 1 , sum , count , arr , K ) ; NEW_LINE pick = waysutil ( index - 1 , sum + arr [ index ] , count + 1 , arr , K ) ; NEW_LINE total = pick + dontpick ; NEW_LINE dp [ index ] [ sum ] [ count ] = total ; NEW_LINE return total ; NEW_LINE DEDENT def ways ( N , K , arr ) : NEW_LINE INDENT Arr = [ ] ; NEW_LINE Arr . append ( - 1 ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT Arr . append ( arr [ i ] ) ; NEW_LINE DEDENT answer = waysutil ( N , 0 , 0 , Arr , K ) ; NEW_LINE return answer ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 6 , 2 , 8 , 7 , 6 , 5 , 9 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 5 ; NEW_LINE print ( ways ( N , K , arr ) ) ; NEW_LINE DEDENT
Subset with sum closest to zero | Python3 Code for above implementation ; Variable to store states of dp ; Function to return the number closer to integer s ; To find the sum closest to zero Since sum can be negative , we will add MAX to it to make it positive ; Base cases ; Checks if a state is already solved ; Recurrence relation ; Returning the value ; Function to calculate the closest sum value ; Calculate the Closest value for every subarray arr [ i - 1 : n ] ; Driver function ; Input array
import numpy as np NEW_LINE arrSize = 51 NEW_LINE maxSum = 201 NEW_LINE MAX = 100 NEW_LINE inf = 999999 NEW_LINE dp = np . zeros ( ( arrSize , maxSum ) ) ; NEW_LINE visit = np . zeros ( ( arrSize , maxSum ) ) ; NEW_LINE def RetClose ( a , b , s ) : NEW_LINE INDENT if ( abs ( a - s ) < abs ( b - s ) ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT else : NEW_LINE INDENT return b ; NEW_LINE DEDENT DEDENT def MinDiff ( i , sum , arr , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( visit [ i ] [ sum + MAX ] ) : NEW_LINE INDENT return dp [ i ] [ sum + MAX ] ; NEW_LINE DEDENT visit [ i ] [ sum + MAX ] = 1 ; NEW_LINE dp [ i ] [ sum + MAX ] = RetClose ( arr [ i ] + MinDiff ( i + 1 , sum + arr [ i ] , arr , n ) , MinDiff ( i + 1 , sum , arr , n ) , - 1 * sum ) ; NEW_LINE return dp [ i ] [ sum + MAX ] ; NEW_LINE DEDENT def FindClose ( arr , n ) : NEW_LINE INDENT ans = inf ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = RetClose ( arr [ i - 1 ] + MinDiff ( i , arr [ i - 1 ] , arr , n ) , ans , 0 ) ; NEW_LINE DEDENT print ( ans ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 25 , - 9 , - 10 , - 4 , - 7 , - 33 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE FindClose ( arr , n ) ; NEW_LINE DEDENT
Paths from entry to exit in matrix and maximum path sum | Recursive function to return the total paths from grid [ i ] [ j ] to grid [ n - 1 ] [ n - 1 ] ; Out of bounds ; If the current state hasn 't been solved before ; Only valid move is right ; Only valid move is down ; Right and down , both are valid moves ; Recursive function to return the maximum sum along the path from grid [ i , j ] to grid [ n - 1 , n - 1 ] ; Out of bounds ; If the current state hasn 't been solved before ; Only valid move is right ; Only valid move is down ; Right and down , both are valid moves ; Driver code ; Fill the dp [ n ] [ n ] array with - 1 ; When source and destination are same then there is only 1 path ; Print the count of paths from grid [ 0 , 0 ] to grid [ n - 1 ] [ n - 1 ] ; Fill the dp [ n ] [ n ] array again with - 1 ; When source and destination are same then the sum is grid [ n - 1 ] [ n - 1 ] ; Print the maximum sum among all the paths from grid [ 0 , 0 ] to grid [ n - 1 ] [ n - 1 ]
def totalPaths ( i , j , n , grid , dp ) : NEW_LINE INDENT if ( i < 0 or j < 0 or i >= n or j >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] == - 1 ) : NEW_LINE INDENT if ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = totalPaths ( i , j + 1 , n , grid , dp ) NEW_LINE DEDENT elif ( grid [ i ] [ j ] == 2 ) : NEW_LINE INDENT dp [ i ] [ j ] = totalPaths ( i + 1 , j , n , grid , dp ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = totalPaths ( i , j + 1 , n , grid , dp ) + totalPaths ( i + 1 , j , n , grid , dp ) NEW_LINE DEDENT DEDENT return dp [ i ] [ j ] NEW_LINE DEDENT def maxSumPath ( i , j , n , grid , dp ) : NEW_LINE INDENT if ( i < 0 or j < 0 or i >= n or j >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] == - 1 ) : NEW_LINE INDENT if ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = grid [ i ] [ j ] + maxSumPath ( i , j + 1 , n , grid , dp ) NEW_LINE DEDENT elif ( grid [ i ] [ j ] == 2 ) : NEW_LINE INDENT dp [ i ] [ j ] = grid [ i ] [ j ] + maxSumPath ( i + 1 , j , n , grid , dp ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = grid [ i ] [ j ] + max ( maxSumPath ( i , j + 1 , n , grid , dp ) , maxSumPath ( i + 1 , j , n , grid , dp ) ) NEW_LINE DEDENT DEDENT return dp [ i ] [ j ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT grid = [ [ 1 , 1 , 3 , 2 , 1 ] , [ 3 , 2 , 2 , 1 , 2 ] , [ 1 , 3 , 3 , 1 , 3 ] , [ 1 , 2 , 3 , 1 , 2 ] , [ 1 , 1 , 1 , 3 , 1 ] ] NEW_LINE n = len ( grid [ 0 ] ) NEW_LINE dp = [ [ - 1 ] * n ] * n NEW_LINE dp [ n - 1 ] [ n - 1 ] = 1 NEW_LINE print ( " Total ▁ paths : " , totalPaths ( 0 , 0 , n , grid , dp ) ) NEW_LINE dp = [ [ - 1 ] * n ] * n NEW_LINE dp [ n - 1 ] [ n - 1 ] = grid [ n - 1 ] [ n - 1 ] NEW_LINE print ( " Maximum ▁ sum : " , maxSumPath ( 0 , 0 , n , grid , dp ) ) NEW_LINE DEDENT
Queries for bitwise OR in the index range [ L , R ] of the given array | Python3 implementation of the approach ; Array to store bit - wise prefix count ; Function to find the prefix sum ; Loop for each bit ; Loop to find prefix count ; Function to answer query ; To store the answer ; Loop for each bit ; To store the number of variables with ith bit set ; Condition for ith bit of answer to be set ; Driver code
import numpy as np NEW_LINE MAX = 100000 NEW_LINE bitscount = 32 NEW_LINE prefix_count = np . zeros ( ( bitscount , MAX ) ) ; NEW_LINE def findPrefixCount ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , bitscount ) : NEW_LINE INDENT prefix_count [ i ] [ 0 ] = ( ( arr [ 0 ] >> i ) & 1 ) ; NEW_LINE for j in range ( 1 , n ) : NEW_LINE INDENT prefix_count [ i ] [ j ] = ( ( arr [ j ] >> i ) & 1 ) ; NEW_LINE prefix_count [ i ] [ j ] += prefix_count [ i ] [ j - 1 ] ; NEW_LINE DEDENT DEDENT DEDENT def rangeOr ( l , r ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( bitscount ) : NEW_LINE INDENT x = 0 ; NEW_LINE if ( l == 0 ) : NEW_LINE INDENT x = prefix_count [ i ] [ r ] ; NEW_LINE DEDENT else : NEW_LINE INDENT x = prefix_count [ i ] [ r ] - prefix_count [ i ] [ l - 1 ] ; NEW_LINE DEDENT if ( x != 0 ) : NEW_LINE INDENT ans = ( ans | ( 1 << i ) ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 5 , 3 , 5 , 2 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findPrefixCount ( arr , n ) ; NEW_LINE queries = [ [ 1 , 3 ] , [ 4 , 5 ] ] ; NEW_LINE q = len ( queries ) ; NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( rangeOr ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) ; NEW_LINE DEDENT DEDENT
Distinct palindromic sub | Python3 implementation of the approach ; Function to return the count of distinct palindromic sub - strings of the given string s ; To store the positions of palindromic sub - strings ; Map to store the sub - strings ; Sub - strings of length 1 are palindromes ; Store continuous palindromic sub - strings ; Store palindromes of size 2 ; If str [ i ... ( i + 1 ) ] is not a palindromic then set dp [ i ] [ i + 1 ] = 0 ; Find palindromic sub - strings of length >= 3 ; End of palindromic substring ; If s [ start ] = = s [ end ] and dp [ start + 1 ] [ end - 1 ] is already palindrome then s [ start ... . end ] is also a palindrome ; Set dp [ start ] [ end ] = 1 ; Not a palindrome ; Return the count of distinct palindromes ; Driver code
import numpy as np ; NEW_LINE def palindromeSubStrs ( s ) : NEW_LINE INDENT dp = np . zeros ( ( len ( s ) , len ( s ) ) ) ; NEW_LINE m = { } ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT dp [ i ] [ i ] = 1 ; NEW_LINE m [ s [ i : i + 1 ] ] = 1 ; NEW_LINE DEDENT for i in range ( len ( s ) - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT dp [ i ] [ i + 1 ] = 1 ; NEW_LINE m [ s [ i : i + 2 ] ] = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ i + 1 ] = 0 ; NEW_LINE DEDENT DEDENT for length in range ( 3 , len ( s ) + 1 ) : NEW_LINE INDENT for st in range ( len ( s ) - length + 1 ) : NEW_LINE INDENT end = st + length - 1 ; NEW_LINE if ( s [ st ] == s [ end ] and dp [ st + 1 ] [ end - 1 ] ) : NEW_LINE INDENT dp [ st ] [ end ] = 1 ; NEW_LINE m [ s [ st : end + 1 ] ] = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ st ] [ end ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT return len ( m ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abaaa " ; NEW_LINE print ( palindromeSubStrs ( s ) ) ; NEW_LINE DEDENT
Maximum sum path in a matrix from top to bottom and back | Python 3 implementation of the approach ; Input matrix ; DP matrix ; Function to return the sum of the cells arr [ i1 ] [ j1 ] and arr [ i2 ] [ j2 ] ; Recursive function to return the required maximum cost path ; Column number of second path ; Base Case ; If already calculated , return from DP matrix ; Recurring for neighbouring cells of both paths together ; Saving result to the DP matrix for current state ; Driver code ; set initial value
import sys NEW_LINE n = 4 NEW_LINE m = 4 NEW_LINE arr = [ [ 1 , 0 , 3 , - 1 ] , [ 3 , 5 , 1 , - 2 ] , [ - 2 , 0 , 1 , 1 ] , [ 2 , 1 , - 1 , 1 ] ] NEW_LINE cache = [ [ [ - 1 for i in range ( 5 ) ] for j in range ( 5 ) ] for k in range ( 5 ) ] NEW_LINE def sum ( i1 , j1 , i2 , j2 ) : NEW_LINE INDENT if ( i1 == i2 and j1 == j2 ) : NEW_LINE INDENT return arr [ i1 ] [ j1 ] NEW_LINE DEDENT return arr [ i1 ] [ j1 ] + arr [ i2 ] [ j2 ] NEW_LINE DEDENT def maxSumPath ( i1 , j1 , i2 ) : NEW_LINE INDENT j2 = i1 + j1 - i2 NEW_LINE if ( i1 >= n or i2 >= n or j1 >= m or j2 >= m ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( cache [ i1 ] [ j1 ] [ i2 ] != - 1 ) : NEW_LINE INDENT return cache [ i1 ] [ j1 ] [ i2 ] NEW_LINE DEDENT ans = - sys . maxsize - 1 NEW_LINE ans = max ( ans , maxSumPath ( i1 + 1 , j1 , i2 + 1 ) + sum ( i1 , j1 , i2 , j2 ) ) NEW_LINE ans = max ( ans , maxSumPath ( i1 , j1 + 1 , i2 ) + sum ( i1 , j1 , i2 , j2 ) ) NEW_LINE ans = max ( ans , maxSumPath ( i1 , j1 + 1 , i2 + 1 ) + sum ( i1 , j1 , i2 , j2 ) ) NEW_LINE ans = max ( ans , maxSumPath ( i1 + 1 , j1 , i2 ) + sum ( i1 , j1 , i2 , j2 ) ) NEW_LINE cache [ i1 ] [ j1 ] [ i2 ] = ans NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( maxSumPath ( 0 , 0 , 0 ) ) NEW_LINE DEDENT
Bellman Ford Algorithm ( Simple Implementation ) | Python3 program for Bellman - Ford 's single source shortest path algorithm. ; The main function that finds shortest distances from src to all other vertices using Bellman - Ford algorithm . The function also detects negative weight cycle The row graph [ i ] represents i - th edge with three values u , v and w . ; Initialize distance of all vertices as infinite . ; initialize distance of source as 0 ; Relax all edges | V | - 1 times . A simple shortest path from src to any other vertex can have at - most | V | - 1 edges ; check for negative - weight cycles . The above step guarantees shortest distances if graph doesn 't contain negative weight cycle. If we get a shorter path, then there is a cycle. ; Driver Code ; Every edge has three values ( u , v , w ) where the edge is from vertex u to v . And weight of the edge is w .
from sys import maxsize NEW_LINE def BellmanFord ( graph , V , E , src ) : NEW_LINE INDENT dis = [ maxsize ] * V NEW_LINE dis [ src ] = 0 NEW_LINE for i in range ( V - 1 ) : NEW_LINE INDENT for j in range ( E ) : NEW_LINE INDENT if dis [ graph [ j ] [ 0 ] ] + graph [ j ] [ 2 ] < dis [ graph [ j ] [ 1 ] ] : NEW_LINE INDENT dis [ graph [ j ] [ 1 ] ] = dis [ graph [ j ] [ 0 ] ] + graph [ j ] [ 2 ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( E ) : NEW_LINE INDENT x = graph [ i ] [ 0 ] NEW_LINE y = graph [ i ] [ 1 ] NEW_LINE weight = graph [ i ] [ 2 ] NEW_LINE if dis [ x ] != maxsize and dis [ x ] + weight < dis [ y ] : NEW_LINE INDENT print ( " Graph ▁ contains ▁ negative ▁ weight ▁ cycle " ) NEW_LINE DEDENT DEDENT print ( " Vertex ▁ Distance ▁ from ▁ Source " ) NEW_LINE for i in range ( V ) : NEW_LINE INDENT print ( " % d TABSYMBOL TABSYMBOL % d " % ( i , dis [ i ] ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT graph = [ [ 0 , 1 , - 1 ] , [ 0 , 2 , 4 ] , [ 1 , 2 , 3 ] , [ 1 , 3 , 2 ] , [ 1 , 4 , 2 ] , [ 3 , 2 , 5 ] , [ 3 , 1 , 1 ] , [ 4 , 3 , - 3 ] ] NEW_LINE BellmanFord ( graph , V , E , 0 ) NEW_LINE DEDENT
Find number of edges that can be broken in a tree such that Bitwise OR of resulting two trees are equal | Python3 implementation of the approach ; Function to perform simple DFS ; Finding the number of times each bit is set in all the values of a subtree rooted at v ; Checking for each bit whether the numbers with that particular bit as set are either zero in both the resulting trees or greater than zero in both the resulting trees ; Driver code ; Number of nodes ; ArrayList to store the tree ; Array to store the value of nodes ; Array to store the number of times each bit is set in all the values in complete tree ; Finding the set bits in the value of node i ; append edges
m , x = [ 0 ] * 1000 , [ 0 ] * 22 NEW_LINE a = [ [ 0 for i in range ( 22 ) ] for j in range ( 1000 ) ] NEW_LINE ans = 0 NEW_LINE def dfs ( u , p ) : NEW_LINE INDENT global ans NEW_LINE for i in range ( 0 , len ( g [ u ] ) ) : NEW_LINE INDENT v = g [ u ] [ i ] NEW_LINE if v != p : NEW_LINE INDENT dfs ( v , u ) NEW_LINE for i in range ( 0 , 22 ) : NEW_LINE INDENT a [ u ] [ i ] += a [ v ] [ i ] NEW_LINE DEDENT DEDENT DEDENT pp = 0 NEW_LINE for i in range ( 0 , 22 ) : NEW_LINE INDENT if ( not ( ( a [ u ] [ i ] > 0 and x [ i ] - a [ u ] [ i ] > 0 ) or ( a [ u ] [ i ] == 0 and x [ i ] == 0 ) ) ) : NEW_LINE INDENT pp = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if pp == 0 : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE g = [ [ ] for i in range ( n + 1 ) ] NEW_LINE m [ 1 ] = 1 NEW_LINE m [ 2 ] = 3 NEW_LINE m [ 3 ] = 2 NEW_LINE m [ 4 ] = 3 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT y , k = m [ i ] , 0 NEW_LINE while y != 0 : NEW_LINE INDENT p = y % 2 NEW_LINE if p == 1 : NEW_LINE INDENT x [ k ] += 1 NEW_LINE a [ i ] [ k ] += 1 NEW_LINE DEDENT y = y // 2 NEW_LINE k += 1 NEW_LINE DEDENT DEDENT g [ 1 ] . append ( 2 ) NEW_LINE g [ 2 ] . append ( 1 ) NEW_LINE g [ 1 ] . append ( 3 ) NEW_LINE g [ 3 ] . append ( 1 ) NEW_LINE g [ 1 ] . append ( 4 ) NEW_LINE g [ 4 ] . append ( 1 ) NEW_LINE dfs ( 1 , 0 ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Find the maximum number of composite summands of a number | Python 3 implementation of the above approach ; Function to generate the dp array ; combination of three integers ; take the maximum number of summands ; Function to find the maximum number of summands ; If n is a smaller number , less than 16 , return dp [ n ] ; Else , find a minimal number t as explained in solution ; Driver code ; Generate dp array
global maxn NEW_LINE maxn = 16 NEW_LINE def precompute ( ) : NEW_LINE INDENT dp = [ - 1 for i in range ( maxn ) ] NEW_LINE dp [ 0 ] = 0 NEW_LINE v = [ 4 , 6 , 9 ] NEW_LINE for i in range ( 1 , maxn , 1 ) : NEW_LINE INDENT for k in range ( 3 ) : NEW_LINE INDENT j = v [ k ] NEW_LINE if ( i >= j and dp [ i - j ] != - 1 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , dp [ i - j ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT return dp NEW_LINE DEDENT def Maximum_Summands ( dp , n ) : NEW_LINE INDENT if ( n < maxn ) : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT else : NEW_LINE INDENT t = int ( ( n - maxn ) / 4 ) + 1 NEW_LINE return t + dp [ n - 4 * t ] NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 NEW_LINE dp = precompute ( ) NEW_LINE print ( Maximum_Summands ( dp , n ) ) NEW_LINE DEDENT
Minimum cost to reach end of array array when a maximum jump of K index is allowed | Python3 implementation of the approach ; for calculating the number of elements ; Allocating Memo table and initializing with INT_MAX ; Base case ; For every element relax every reachable element ie relax next k elements ; reaching next k element ; Relaxing the element ; return the last element in the array ; Driver Code
import sys NEW_LINE def minCostJumpsDP ( A , k ) : NEW_LINE INDENT size = len ( A ) NEW_LINE x = [ sys . maxsize ] * ( size ) NEW_LINE x [ 0 ] = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT j = i + 1 NEW_LINE while j < i + k + 1 and j < size : NEW_LINE INDENT x [ j ] = min ( x [ j ] , x [ i ] + abs ( A [ i ] - A [ j ] ) ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return x [ size - 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input_ = [ 83 , 26 , 37 , 35 , 33 , 35 , 56 ] NEW_LINE print ( minCostJumpsDP ( input_ , 3 ) ) NEW_LINE DEDENT
DP on Trees | Set | Function to find the diameter of the tree using Dynamic Programming ; Store the first maximum and secondmax ; Traverse for all children of node ; Call DFS function again ; Find first max ; Secondmaximum ; elif dp1 [ i ] > secondmax : Find secondmaximum ; Base case for every node ; if firstmax != - 1 : Add ; Find dp [ 2 ] ; Return maximum of both ; Driver Code ; Constructed tree is 1 / \ 2 3 / \ 4 5 ; create undirected edges ; Find diameter by calling function
def dfs ( node , parent , dp1 , dp2 , adj ) : NEW_LINE INDENT firstmax , secondmax = - 1 , - 1 NEW_LINE for i in adj [ node ] : NEW_LINE INDENT if i == parent : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( i , node , dp1 , dp2 , adj ) NEW_LINE if firstmax == - 1 : NEW_LINE INDENT firstmax = dp1 [ i ] NEW_LINE DEDENT DEDENT elif dp1 [ i ] >= firstmax : NEW_LINE INDENT secondmax = firstmax NEW_LINE firstmax = dp1 [ i ] NEW_LINE secondmax = dp1 [ i ] NEW_LINE DEDENT dp1 [ node ] = 1 NEW_LINE INDENT dp1 [ node ] += firstmax NEW_LINE DEDENT if secondmax != - 1 : NEW_LINE INDENT dp2 [ node ] = 1 + firstmax + secondmax NEW_LINE DEDENT return max ( dp1 [ node ] , dp2 [ node ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , diameter = 5 , - 1 NEW_LINE adj = [ [ ] for i in range ( n + 1 ) ] NEW_LINE adj [ 1 ] . append ( 2 ) NEW_LINE adj [ 2 ] . append ( 1 ) NEW_LINE adj [ 1 ] . append ( 3 ) NEW_LINE adj [ 3 ] . append ( 1 ) NEW_LINE adj [ 2 ] . append ( 4 ) NEW_LINE adj [ 4 ] . append ( 2 ) NEW_LINE adj [ 2 ] . append ( 5 ) NEW_LINE adj [ 5 ] . append ( 2 ) NEW_LINE dp1 = [ 0 ] * ( n + 1 ) NEW_LINE dp2 = [ 0 ] * ( n + 1 ) NEW_LINE print ( " Diameter ▁ of ▁ the ▁ given ▁ tree ▁ is " , dfs ( 1 , 1 , dp1 , dp2 , adj ) ) NEW_LINE DEDENT
Find sub | Python implementation of the approach ; Function to return the sum of the sub - matrix ; Function that returns true if it is possible to find the sub - matrix with required sum ; 2 - D array to store the sum of all the sub - matrices ; Filling of dp [ ] [ ] array ; Checking for each possible sub - matrix of size k X k ; Sub - matrix with the given sum not found ; Driver code ; Function call
N = 4 NEW_LINE def getSum ( r1 , r2 , c1 , c2 , dp ) : NEW_LINE INDENT return dp [ r2 ] [ c2 ] - dp [ r2 ] [ c1 ] - dp [ r1 ] [ c2 ] + dp [ r1 ] [ c1 ] NEW_LINE DEDENT def sumFound ( K , S , grid ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( N + 1 ) ] for j in range ( N + 1 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT dp [ i + 1 ] [ j + 1 ] = dp [ i + 1 ] [ j ] + dp [ i ] [ j + 1 ] - dp [ i ] [ j ] + grid [ i ] [ j ] NEW_LINE DEDENT DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT sum = getSum ( i , i + K , j , j + K , dp ) NEW_LINE if ( sum == S ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT grid = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] NEW_LINE K = 2 NEW_LINE S = 14 NEW_LINE if ( sumFound ( K , S , grid ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Stepping Numbers | Prints all stepping numbers reachable from num and in range [ n , m ] ; Queue will contain all the stepping Numbers ; Get the front element and pop from the queue ; If the Stepping Number is in the range [ n , m ] then display ; If Stepping Number is 0 or greater than m , no need to explore the neighbors ; Get the last digit of the currently visited Stepping Number ; There can be 2 cases either digit to be appended is lastDigit + 1 or lastDigit - 1 ; If lastDigit is 0 then only possible digit after 0 can be 1 for a Stepping Number ; If lastDigit is 9 then only possible digit after 9 can be 8 for a Stepping Number ; Prints all stepping numbers in range [ n , m ] using BFS . ; For every single digit Number ' i ' find all the Stepping Numbers starting with i ; Driver code ; Display Stepping Numbers in the range [ n , m ]
def bfs ( n , m , num ) : NEW_LINE INDENT q = [ ] NEW_LINE q . append ( num ) NEW_LINE while len ( q ) > 0 : NEW_LINE INDENT stepNum = q [ 0 ] NEW_LINE q . pop ( 0 ) ; NEW_LINE if ( stepNum <= m and stepNum >= n ) : NEW_LINE INDENT print ( stepNum , end = " ▁ " ) NEW_LINE DEDENT if ( num == 0 or stepNum > m ) : NEW_LINE INDENT continue NEW_LINE DEDENT lastDigit = stepNum % 10 NEW_LINE stepNumA = stepNum * 10 + ( lastDigit - 1 ) NEW_LINE stepNumB = stepNum * 10 + ( lastDigit + 1 ) NEW_LINE if ( lastDigit == 0 ) : NEW_LINE INDENT q . append ( stepNumB ) NEW_LINE DEDENT elif ( lastDigit == 9 ) : NEW_LINE INDENT q . append ( stepNumA ) NEW_LINE DEDENT else : NEW_LINE INDENT q . append ( stepNumA ) NEW_LINE q . append ( stepNumB ) NEW_LINE DEDENT DEDENT DEDENT def displaySteppingNumbers ( n , m ) : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT bfs ( n , m , i ) NEW_LINE DEDENT DEDENT n , m = 0 , 21 NEW_LINE displaySteppingNumbers ( n , m ) NEW_LINE
Minimum distance to the end of a grid from source | Python3 implementation of the approach ; Global variables for grid , minDistance and visited array ; Queue for BFS ; Function to find whether the move is valid or not ; Function to return the minimum distance from source to the end of the grid ; If source is one of the destinations ; Set minimum value ; Precalculate minDistance of each grid with R * C ; Insert source position in queue ; Update minimum distance to visit source ; Set source to visited ; BFS approach for calculating the minDistance of each cell from source ; Iterate over all four cells adjacent to current cell ; Initialize position of current cell ; Cell below the current cell ; Push new cell to the queue ; Update one of its neightbor 's distance ; Above the current cell ; Right cell ; Left cell ; Minimum distance in the first row ; Minimum distance in the last row ; Minimum distance in the first column ; Minimum distance in the last column ; If no path exists ; Return the minimum distance ; Driver code
from collections import deque as queue NEW_LINE row = 5 NEW_LINE col = 5 NEW_LINE minDistance = [ [ 0 for i in range ( col + 1 ) ] for i in range ( row + 1 ) ] NEW_LINE visited = [ [ 0 for i in range ( col + 1 ) ] for i in range ( row + 1 ) ] NEW_LINE que = queue ( ) NEW_LINE def isValid ( grid , i , j ) : NEW_LINE INDENT if ( i < 0 or j < 0 or j >= col or i >= row or grid [ i ] [ j ] or visited [ i ] [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def findMinPathminDistance ( grid , sourceRow , sourceCol ) : NEW_LINE INDENT if ( sourceCol == 0 or sourceCol == col - 1 or sourceRow == 0 or sourceRow == row - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT minFromSource = row * col NEW_LINE for i in range ( row ) : NEW_LINE INDENT for j in range ( col ) : NEW_LINE INDENT minDistance [ i ] [ j ] = row * col NEW_LINE DEDENT DEDENT que . appendleft ( [ sourceRow , sourceCol ] ) NEW_LINE minDistance [ sourceRow ] [ sourceCol ] = 0 ; NEW_LINE visited [ sourceRow ] [ sourceCol ] = 1 ; NEW_LINE while ( len ( que ) > 0 ) : NEW_LINE INDENT cell = que . pop ( ) NEW_LINE cellRow = cell [ 0 ] NEW_LINE cellCol = cell [ 1 ] NEW_LINE if ( isValid ( grid , cellRow + 1 , cellCol ) ) : NEW_LINE INDENT que . appendleft ( [ cellRow + 1 , cellCol ] ) NEW_LINE minDistance [ cellRow + 1 ] [ cellCol ] = min ( minDistance [ cellRow + 1 ] [ cellCol ] , minDistance [ cellRow ] [ cellCol ] + 1 ) NEW_LINE visited [ cellRow + 1 ] [ cellCol ] = 1 NEW_LINE DEDENT if ( isValid ( grid , cellRow - 1 , cellCol ) ) : NEW_LINE INDENT que . appendleft ( [ cellRow - 1 , cellCol ] ) NEW_LINE minDistance [ cellRow - 1 ] [ cellCol ] = min ( minDistance [ cellRow - 1 ] [ cellCol ] , minDistance [ cellRow ] [ cellCol ] + 1 ) NEW_LINE visited [ cellRow - 1 ] [ cellCol ] = 1 NEW_LINE DEDENT if ( isValid ( grid , cellRow , cellCol + 1 ) ) : NEW_LINE INDENT que . appendleft ( [ cellRow , cellCol + 1 ] ) NEW_LINE minDistance [ cellRow ] [ cellCol + 1 ] = min ( minDistance [ cellRow ] [ cellCol + 1 ] , minDistance [ cellRow ] [ cellCol ] + 1 ) NEW_LINE visited [ cellRow ] [ cellCol + 1 ] = 1 ; NEW_LINE DEDENT if ( isValid ( grid , cellRow , cellCol - 1 ) ) : NEW_LINE INDENT que . appendleft ( [ cellRow , cellCol - 1 ] ) NEW_LINE minDistance [ cellRow ] [ cellCol - 1 ] = min ( minDistance [ cellRow ] [ cellCol - 1 ] , minDistance [ cellRow ] [ cellCol ] + 1 ) NEW_LINE visited [ cellRow ] [ cellCol - 1 ] = 1 NEW_LINE DEDENT DEDENT for i in range ( col ) : NEW_LINE INDENT minFromSource = min ( minFromSource , minDistance [ 0 ] [ i ] ) ; NEW_LINE DEDENT for i in range ( col ) : NEW_LINE INDENT minFromSource = min ( minFromSource , minDistance [ row - 1 ] [ i ] ) ; NEW_LINE DEDENT for i in range ( row ) : NEW_LINE INDENT minFromSource = min ( minFromSource , minDistance [ i ] [ 0 ] ) ; NEW_LINE DEDENT for i in range ( row ) : NEW_LINE INDENT minFromSource = min ( minFromSource , minDistance [ i ] [ col - 1 ] ) ; NEW_LINE DEDENT if ( minFromSource == row * col ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return minFromSource NEW_LINE DEDENT sourceRow = 3 NEW_LINE sourceCol = 3 NEW_LINE grid = [ [ 1 , 1 , 1 , 1 , 0 ] , [ 0 , 0 , 1 , 0 , 1 ] , [ 0 , 0 , 1 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 1 ] , [ 1 , 1 , 0 , 1 , 0 ] ] NEW_LINE print ( findMinPathminDistance ( grid , sourceRow , sourceCol ) ) NEW_LINE
Minimum number of operations required to sum to binary string S | Function to return the minimum operations required to sum to a number reprented by the binary string S ; Reverse the string to consider it from LSB to MSB ; initialise the dp table ; If S [ 0 ] = '0' , there is no need to perform any operation ; If S [ 0 ] = '1' , just perform a single operation ( i . e Add 2 ^ 0 ) ; Irrespective of the LSB , dp [ 0 ] [ 1 ] is always 1 as there is always the need of making the suffix of the binary string of the form "11 . . . . 1" as suggested by the definition of dp [ i ] [ 1 ] ; Transition from dp [ i - 1 ] [ 0 ] ; 1. Transition from dp [ i - 1 ] [ 1 ] by just doing 1 extra operation of subtracting 2 ^ i 2. Transition from dp [ i - 1 ] [ 0 ] by just doing 1 extra operation of subtracting 2 ^ ( i + 1 ) ; Transition from dp [ i - 1 ] [ 1 ] ; 1. Transition from dp [ i - 1 ] [ 1 ] by just doing 1 extra operation of adding 2 ^ ( i + 1 ) 2. Transition from dp [ i - 1 ] [ 0 ] by just doing 1 extra operation of adding 2 ^ i ; Driver Code
def findMinOperations ( S ) : NEW_LINE INDENT S = S [ : : - 1 ] NEW_LINE n = len ( S ) NEW_LINE dp = [ [ 0 ] * 2 ] * ( n + 1 ) NEW_LINE if ( S [ 0 ] == '0' ) : NEW_LINE INDENT dp [ 0 ] [ 0 ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE DEDENT dp [ 0 ] [ 1 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] NEW_LINE dp [ i ] [ 1 ] = 1 + min ( dp [ i - 1 ] [ 1 ] , dp [ i - 1 ] [ 0 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ 1 ] = dp [ i - 1 ] [ 1 ] ; NEW_LINE dp [ i ] [ 0 ] = 1 + min ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) NEW_LINE DEDENT DEDENT return dp [ n - 1 ] [ 0 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "100" NEW_LINE print ( findMinOperations ( S ) ) NEW_LINE S = "111" ; NEW_LINE print ( findMinOperations ( S ) ) NEW_LINE DEDENT
K | Function that finds the Nth element of K - Fibonacci series ; If N is less than K then the element is '1 ; first k elements are 1 ; ( K + 1 ) th element is K ; find the elements of the K - Fibonacci series ; subtract the element at index i - k - 1 and add the element at index i - i from the sum ( sum contains the sum of previous ' K ' elements ) ; set the new sum ; Driver code ; get the Nth value of K - Fibonacci series
def solve ( N , K ) : NEW_LINE INDENT Array = [ 0 ] * ( N + 1 ) NEW_LINE DEDENT ' NEW_LINE INDENT if ( N <= K ) : NEW_LINE INDENT print ( "1" ) NEW_LINE return NEW_LINE DEDENT i = 0 NEW_LINE sm = K NEW_LINE for i in range ( 1 , K + 1 ) : NEW_LINE INDENT Array [ i ] = 1 NEW_LINE DEDENT Array [ i + 1 ] = sm NEW_LINE for i in range ( K + 2 , N + 1 ) : NEW_LINE INDENT Array [ i ] = sm - Array [ i - K - 1 ] + Array [ i - 1 ] NEW_LINE sm = Array [ i ] NEW_LINE DEDENT print ( Array [ N ] ) NEW_LINE DEDENT N = 4 NEW_LINE K = 2 NEW_LINE solve ( N , K ) NEW_LINE
Minimum sum possible of any bracket sequence of length N | Python 3 program to find the Minimum sum possible of any bracket sequence of length N using the given values for brackets ; DP array ; Recursive function to check for correct bracket expression ; Not a proper bracket expression ; If reaches at end ; If proper bracket expression ; if not , return max ; If already visited ; To find out minimum sum ; Driver Code
MAX_VAL = 10000000 NEW_LINE dp = [ [ - 1 for i in range ( 100 ) ] for i in range ( 100 ) ] NEW_LINE def find ( index , openbrk , n , adj ) : NEW_LINE INDENT if ( openbrk < 0 ) : NEW_LINE INDENT return MAX_VAL NEW_LINE DEDENT if ( index == n ) : NEW_LINE INDENT if ( openbrk == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return MAX_VAL NEW_LINE DEDENT DEDENT if ( dp [ index ] [ openbrk ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ openbrk ] NEW_LINE DEDENT dp [ index ] [ openbrk ] = min ( adj [ index ] [ 1 ] + find ( index + 1 , openbrk + 1 , n , adj ) , adj [ index ] [ 0 ] + find ( index + 1 , openbrk - 1 , n , adj ) ) NEW_LINE return dp [ index ] [ openbrk ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE adj = [ [ 5000 , 3000 ] , [ 6000 , 2000 ] , [ 8000 , 1000 ] , [ 9000 , 6000 ] ] NEW_LINE print ( find ( 1 , 1 , n , adj ) + adj [ 0 ] [ 1 ] ) NEW_LINE DEDENT
Understanding The Coin Change Problem With Dynamic Programming | We have input values of N and an array Coins that holds all of the coins . We use data type of because long we want to be able to test large values without integer overflow ; Create the ways array to 1 plus the amount to stop overflow ; Set the first way to 1 because its 0 and there is 1 way to make 0 with 0 coins ; Go through all of the coins ; Make a comparison to each index value of ways with the coin value . ; Update the ways array ; return the value at the Nth position of the ways array . ; Driver code
def getNumberOfWays ( N , Coins ) : NEW_LINE INDENT ways = [ 0 ] * ( N + 1 ) ; NEW_LINE ways [ 0 ] = 1 ; NEW_LINE for i in range ( len ( Coins ) ) : NEW_LINE INDENT for j in range ( len ( ways ) ) : NEW_LINE INDENT if ( Coins [ i ] <= j ) : NEW_LINE INDENT ways [ j ] += ways [ ( int ) ( j - Coins [ i ] ) ] ; NEW_LINE DEDENT DEDENT DEDENT return ways [ N ] ; NEW_LINE DEDENT def printArray ( coins ) : NEW_LINE INDENT for i in coins : NEW_LINE INDENT print ( i ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Coins = [ 1 , 5 , 10 ] ; NEW_LINE print ( " The ▁ Coins ▁ Array : " ) ; NEW_LINE printArray ( Coins ) ; NEW_LINE print ( " Solution : " , end = " " ) ; NEW_LINE print ( getNumberOfWays ( 12 , Coins ) ) ; NEW_LINE DEDENT
Minimum cost to buy N kilograms of sweet for M persons | Function to find the minimum cost of sweets ; Defining the sweet array ; DP array to store the values ; Since index starts from 1 we reassign the array into sweet ; Assigning base cases for dp array ; At 0 it is free ; Package not available for desirable amount of sweets ; Buying the ' k ' kg package and assigning it to dp array ; If no solution , select from previous k - 1 packages ; If solution does not exist ; Print the solution ; Driver Function ; Calling the desired function
def find ( m , n , adj ) : NEW_LINE INDENT sweet = [ 0 ] * ( n + 1 ) NEW_LINE dp = [ [ [ 0 for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE sweet [ 0 ] = 0 NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT sweet [ i ] = adj [ i - 1 ] NEW_LINE DEDENT for i in range ( m + 1 ) : NEW_LINE INDENT for k in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] [ k ] = 0 NEW_LINE DEDENT for k in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ k ] [ 0 ] = - 1 NEW_LINE DEDENT DEDENT for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT for k in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = - 1 NEW_LINE if ( i > 0 and j >= k and sweet [ k ] > 0 and dp [ i - 1 ] [ j - k ] [ k ] != - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = dp [ i - 1 ] [ j - k ] [ k ] + sweet [ k ] NEW_LINE DEDENT if ( dp [ i ] [ j ] [ k ] == - 1 or ( dp [ i ] [ j ] [ k - 1 ] != - 1 and dp [ i ] [ j ] [ k ] > dp [ i ] [ j ] [ k - 1 ] ) ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = dp [ i ] [ j ] [ k - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( dp [ m ] [ n ] [ n ] == - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return dp [ m ] [ n ] [ n ] NEW_LINE DEDENT DEDENT m = 3 NEW_LINE adj = [ 2 , 1 , 3 , 0 , 4 , 10 ] NEW_LINE n = len ( adj ) NEW_LINE print ( find ( m , n , adj ) ) NEW_LINE
Maximum length of segments of 0 ' s ▁ and ▁ 1' s | Recursive Function to find total length of the array where 1 is greater than zero ; If reaches till end ; If dp is saved ; Finding for each length ; If the character scanned is 1 ; If one is greater than zero , add total length scanned till now ; Continue with next length ; Return the value for start index ; Driver Code ; Size of string ; Calling the function to find the value of function
def find ( start , adj , n , dp ) : NEW_LINE INDENT if ( start == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ start ] != - 1 ) : NEW_LINE INDENT return dp [ start ] NEW_LINE DEDENT dp [ start ] = 0 NEW_LINE one = 0 NEW_LINE zero = 0 NEW_LINE for k in range ( start , n , 1 ) : NEW_LINE INDENT if ( adj [ k ] == '1' ) : NEW_LINE INDENT one += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT if ( one > zero ) : NEW_LINE INDENT dp [ start ] = max ( dp [ start ] , find ( k + 1 , adj , n , dp ) + k - start + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ start ] = max ( dp [ start ] , find ( k + 1 , adj , n , dp ) ) NEW_LINE DEDENT DEDENT return dp [ start ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT adj = "100110001010001" NEW_LINE n = len ( adj ) NEW_LINE dp = [ - 1 for i in range ( n + 1 ) ] NEW_LINE print ( find ( 0 , adj , n , dp ) ) NEW_LINE DEDENT
Length of longest common subsequence containing vowels | function to check whether ' ch ' is a vowel or not ; function to find the length of longest common subsequence which contains all vowel characters ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] which contains all vowel characters ; Driver Code
def isVowel ( ch ) : NEW_LINE INDENT if ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def lcs ( X , Y , m , n ) : NEW_LINE INDENT L = [ [ 0 for i in range ( n + 1 ) ] for j in range ( m + 1 ) ] NEW_LINE i , j = 0 , 0 NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT L [ i ] [ j ] = 0 NEW_LINE DEDENT elif ( ( X [ i - 1 ] == Y [ j - 1 ] ) and isVowel ( X [ i - 1 ] ) ) : NEW_LINE INDENT L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return L [ m ] [ n ] NEW_LINE DEDENT X = " aieef " NEW_LINE Y = " klaief " NEW_LINE m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE print ( " Length ▁ of ▁ LCS ▁ = " , lcs ( X , Y , m , n ) ) NEW_LINE
Minimum number of single digit primes required whose sum is equal to N | function to check if i - th index is valid or not ; function to find the minimum number of single digit prime numbers required which when summed up equals to a given number N . ; Not possible ; Driver Code
def check ( i , val ) : NEW_LINE INDENT if i - val < 0 : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def MinimumPrimes ( n ) : NEW_LINE INDENT dp = [ 10 ** 9 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = dp [ 2 ] = dp [ 3 ] = dp [ 5 ] = dp [ 7 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if check ( i , 2 ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , 1 + dp [ i - 2 ] ) NEW_LINE DEDENT if check ( i , 3 ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , 1 + dp [ i - 3 ] ) NEW_LINE DEDENT if check ( i , 5 ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , 1 + dp [ i - 5 ] ) NEW_LINE DEDENT if check ( i , 7 ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , 1 + dp [ i - 7 ] ) NEW_LINE DEDENT DEDENT if dp [ n ] == 10 ** 9 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 12 NEW_LINE minimal = MinimumPrimes ( n ) NEW_LINE if minimal != - 1 : NEW_LINE INDENT print ( " Minimum ▁ number ▁ of ▁ single ▁ digit ▁ primes ▁ required ▁ : ▁ " , minimal ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ possible " ) NEW_LINE DEDENT DEDENT
Find all distinct subset ( or subsequence ) sums of an array | Set | Function to print all th distinct sum ; Declare a boolean array of size equal to total sum of the array ; Fill the first row beforehand ; dp [ j ] will be true only if sum j can be formed by any possible addition of numbers in given array upto index i , otherwise false ; Iterate from maxSum to 1 and avoid lookup on any other row ; Do not change the dp array for j less than arr [ i ] ; If dp [ j ] is true then print ; Function to find the total sum and print the distinct sum ; find the sum of array elements ; Function to print all the distinct sum ; Driver Code
def subsetSum ( arr , n , maxSum ) : NEW_LINE INDENT dp = [ False for i in range ( maxSum + 1 ) ] NEW_LINE dp [ arr [ 0 ] ] = True NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT j = maxSum NEW_LINE while ( j >= 1 ) : NEW_LINE INDENT if ( arr [ i ] <= j ) : NEW_LINE INDENT if ( arr [ i ] == j or dp [ j ] or dp [ ( j - arr [ i ] ) ] ) : NEW_LINE INDENT dp [ j ] = True NEW_LINE DEDENT else : NEW_LINE INDENT dp [ j ] = False NEW_LINE DEDENT DEDENT j -= 1 NEW_LINE DEDENT DEDENT print ( 0 , end = " ▁ " ) NEW_LINE for j in range ( maxSum + 1 ) : NEW_LINE INDENT if ( dp [ j ] == True ) : NEW_LINE INDENT print ( j , end = " ▁ " ) NEW_LINE DEDENT DEDENT print ( "21" ) NEW_LINE DEDENT def printDistinct ( a , n ) : NEW_LINE INDENT maxSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxSum += a [ i ] NEW_LINE DEDENT subsetSum ( a , n , maxSum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE printDistinct ( arr , n ) NEW_LINE DEDENT
Sudo Placement [ 1.5 ] | Wolfish | Python program for SP - Wolfish ; Function to find the maxCost of path from ( n - 1 , n - 1 ) to ( 0 , 0 ) | recursive approach ; base condition ; reaches the point ; i + j ; check if it is a power of 2 , then only move diagonally ; if not a power of 2 then move side - wise ; Function to return the maximum cost ; calling dp function to get the answer ; Driver Code ; Function calling to get the answer
size = 1000 NEW_LINE def maxCost ( a : list , m : int , n : int ) -> int : NEW_LINE INDENT if n < 0 or m < 0 : NEW_LINE INDENT return int ( - 1e9 ) NEW_LINE DEDENT elif m == 0 and n == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT num = m + n NEW_LINE if ( num & ( num - 1 ) ) == 0 : NEW_LINE INDENT return a [ m ] [ n ] + maxCost ( a , m - 1 , n - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return a [ m ] [ n ] + max ( maxCost ( a , m - 1 , n ) , maxCost ( a , m , n - 1 ) ) NEW_LINE DEDENT DEDENT DEDENT def answer ( a : list , n : int ) -> int : NEW_LINE INDENT return maxCost ( a , n - 1 , n - 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ [ 1 , 2 , 3 , 1 ] , [ 4 , 5 , 6 , 1 ] , [ 7 , 8 , 9 , 1 ] , [ 1 , 1 , 1 , 1 ] ] NEW_LINE n = 4 NEW_LINE print ( answer ( a , n ) ) NEW_LINE DEDENT
Longest Common Subsequence | DP using Memoization | Python3 program to memoize recursive implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] memoization applied in recursive solution ; base case ; if the same state has already been computed ; if equal , then we store the value of the function call ; store it in arr to avoid further repetitive work in future function calls ; store it in arr to avoid further repetitive work in future function calls ; Driver Code ; assign - 1 to all positions
maximum = 1000 NEW_LINE def lcs ( X , Y , m , n , dp ) : NEW_LINE INDENT if ( m == 0 or n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ m - 1 ] [ n - 1 ] != - 1 ) : NEW_LINE INDENT return dp [ m - 1 ] [ n - 1 ] NEW_LINE DEDENT if ( X [ m - 1 ] == Y [ n - 1 ] ) : NEW_LINE INDENT dp [ m - 1 ] [ n - 1 ] = 1 + lcs ( X , Y , m - 1 , n - 1 , dp ) NEW_LINE return dp [ m - 1 ] [ n - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ m - 1 ] [ n - 1 ] = max ( lcs ( X , Y , m , n - 1 , dp ) , lcs ( X , Y , m - 1 , n , dp ) ) NEW_LINE return dp [ m - 1 ] [ n - 1 ] NEW_LINE DEDENT DEDENT X = " AGGTAB " NEW_LINE Y = " GXTXAYB " NEW_LINE m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE dp = [ [ - 1 for i in range ( maximum ) ] for i in range ( m ) ] NEW_LINE print ( " Length ▁ of ▁ LCS : " , lcs ( X , Y , m , n , dp ) ) NEW_LINE
Stepping Numbers | Prints all stepping numbers reachable from num and in range [ n , m ] ; If Stepping Number is in the range [ n , m ] then display ; If Stepping Number is 0 or greater than m , then return ; Get the last digit of the currently visited Stepping Number ; There can be 2 cases either digit to be appended is lastDigit + 1 or lastDigit - 1 ; If lastDigit is 0 then only possible digit after 0 can be 1 for a Stepping Number ; If lastDigit is 9 then only possible digit after 9 can be 8 for a Stepping Number ; Method displays all the stepping numbers in range [ n , m ] ; For every single digit Number ' i ' find all the Stepping Numbers starting with i ; Driver code ; Display Stepping Numbers in the range [ n , m ]
def dfs ( n , m , stepNum ) : NEW_LINE INDENT if ( stepNum <= m and stepNum >= n ) : NEW_LINE INDENT print ( stepNum , end = " ▁ " ) NEW_LINE DEDENT if ( stepNum == 0 or stepNum > m ) : NEW_LINE INDENT return NEW_LINE DEDENT lastDigit = stepNum % 10 NEW_LINE stepNumA = stepNum * 10 + ( lastDigit - 1 ) NEW_LINE stepNumB = stepNum * 10 + ( lastDigit + 1 ) NEW_LINE if ( lastDigit == 0 ) : NEW_LINE INDENT dfs ( n , m , stepNumB ) NEW_LINE DEDENT elif ( lastDigit == 9 ) : NEW_LINE INDENT dfs ( n , m , stepNumA ) NEW_LINE DEDENT else : NEW_LINE INDENT dfs ( n , m , stepNumA ) NEW_LINE dfs ( n , m , stepNumB ) NEW_LINE DEDENT DEDENT def displaySteppingNumbers ( n , m ) : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT dfs ( n , m , i ) NEW_LINE DEDENT DEDENT n , m = 0 , 21 NEW_LINE displaySteppingNumbers ( n , m ) NEW_LINE
Memoization ( 1D , 2D and 3D ) | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] memoization applied in recursive solution ; base case ; if the same state has already been computed ; if equal , then we store the value of the function call ; store it in arr to avoid further repetitive work in future function calls ; store it in arr to avoid further repetitive work in future function calls ; ; Driver code
def lcs ( X , Y , m , n ) : NEW_LINE INDENT global arr NEW_LINE if ( m == 0 or n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( arr [ m - 1 ] [ n - 1 ] != - 1 ) : NEW_LINE INDENT return arr [ m - 1 ] [ n - 1 ] NEW_LINE DEDENT if ( X [ m - 1 ] == Y [ n - 1 ] ) : NEW_LINE INDENT arr [ m - 1 ] [ n - 1 ] = 1 + lcs ( X , Y , m - 1 , n - 1 ) NEW_LINE return arr [ m - 1 ] [ n - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT arr [ m - 1 ] [ n - 1 ] = max ( lcs ( X , Y , m , n - 1 ) , lcs ( X , Y , m - 1 , n ) ) NEW_LINE return arr [ m - 1 ] [ n - 1 ] NEW_LINE DEDENT DEDENT / * Utility function to get max of 2 integers * / NEW_LINE arr = [ [ 0 ] * 1000 ] * 1000 NEW_LINE for i in range ( 0 , 1000 ) : NEW_LINE INDENT for j in range ( 0 , 1000 ) : NEW_LINE INDENT arr [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT X = " AGGTAB " NEW_LINE Y = " GXTXAYB " NEW_LINE m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE print ( " Length ▁ of ▁ LCS ▁ is ▁ " , lcs ( X , Y , m , n ) ) NEW_LINE
Number of Unique BST with a given key | Dynamic Programming | Function to find number of unique BST ; DP to store the number of unique BST with key i ; Base case ; fill the dp table in top - down approach . ; n - i in right * i - 1 in left ; Driver Code
def numberOfBST ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] , dp [ 1 ] = 1 , 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , i + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i ] + ( dp [ i - j ] * dp [ j - 1 ] ) NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE print ( " Number ▁ of ▁ structurally ▁ Unique ▁ BST ▁ with " , n , " keys ▁ are ▁ : " , numberOfBST ( n ) ) NEW_LINE DEDENT
Minimum splits in a binary string such that every substring is a power of 4 or 6. | Python 3 program for Minimum splits in a string such that substring is a power of 4 or 6. ; Function to find if given number is power of another number or not . ; Divide given number repeatedly by base value . ; return False not a power ; Function to find minimum number of partitions of given binary string so that each partition is power of 4 or 6. ; DP table to store results of partitioning done at differentindices . ; If the last digit is 1 , hence 4 ^ 0 = 1 and 6 ^ 0 = 1 ; Fix starting position for partition ; Binary representation with leading zeroes is not allowed . ; Iterate for all different partitions starting from i ; Find integer value of current binary partition . ; Check if the value is a power of 4 or 6 or not apply recurrence relation ; If no partitions are possible , then make dp [ i ] = - 1 to represent this . ; Driver code
import sys NEW_LINE def isPowerOf ( val , base ) : NEW_LINE INDENT while ( val > 1 ) : NEW_LINE INDENT if ( val % base != 0 ) : NEW_LINE val //= base NEW_LINE DEDENT return True NEW_LINE DEDENT def numberOfPartitions ( binaryNo ) : NEW_LINE INDENT n = len ( binaryNo ) NEW_LINE dp = [ 0 ] * n NEW_LINE if ( ( ord ( binaryNo [ n - 1 ] ) - ord ( '0' ) ) == 0 ) : NEW_LINE INDENT dp [ n - 1 ] = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ n - 1 ] = 1 NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT val = 0 NEW_LINE if ( ( ord ( binaryNo [ i ] ) - ord ( '0' ) ) == 0 ) : NEW_LINE INDENT dp [ i ] = - 1 NEW_LINE continue NEW_LINE DEDENT dp [ i ] = sys . maxsize NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT val = ( val * 2 ) + ( ord ( binaryNo [ j ] ) - ord ( '0' ) ) NEW_LINE if ( isPowerOf ( val , 4 ) or isPowerOf ( val , 6 ) ) : NEW_LINE INDENT if ( j == n - 1 ) : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( dp [ j + 1 ] != - 1 ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , dp [ j + 1 ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( dp [ i ] == sys . maxsize ) : NEW_LINE INDENT dp [ i ] = - 1 NEW_LINE DEDENT DEDENT return dp [ 0 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT binaryNo = "100110110" NEW_LINE print ( numberOfPartitions ( binaryNo ) ) NEW_LINE DEDENT
Sum of product of r and rth Binomial Coefficient ( r * nCr ) | Return summation of r * nCr ; Driver Code
def summation ( n ) : NEW_LINE INDENT return n << ( n - 1 ) ; NEW_LINE DEDENT n = 2 ; NEW_LINE print ( summation ( n ) ) ; NEW_LINE
Integers from the range that are composed of a single distinct digit | Function to return the count of digits of a number ; Function to return a number that contains only digit ' d ' repeated exactly count times ; Function to return the count of integers that are composed of a single distinct digit only ; Count of digits in L and R ; First digits of L and R ; If L has lesser number of digits than R ; If the number that starts with firstDigitL and has number of digits = countDigitsL is within the range include the number ; Exclude the number ; If the number that starts with firstDigitR and has number of digits = countDigitsR is within the range include the number ; Exclude the number ; If both L and R have equal number of digits ; Include the number greater than L upto the maximum number whose digit = coutDigitsL ; Exclude the numbers which are greater than R ; Return the count ; Driver code
def countDigits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += 1 NEW_LINE n //= 10 NEW_LINE DEDENT return count NEW_LINE DEDENT def getDistinct ( d , count ) : NEW_LINE INDENT num = 0 NEW_LINE count = pow ( 10 , count - 1 ) NEW_LINE while ( count > 0 ) : NEW_LINE INDENT num += ( count * d ) NEW_LINE count //= 10 NEW_LINE DEDENT return num NEW_LINE DEDENT def findCount ( L , R ) : NEW_LINE INDENT count = 0 NEW_LINE countDigitsL = countDigits ( L ) NEW_LINE countDigitsR = countDigits ( R ) NEW_LINE firstDigitL = ( L // pow ( 10 , countDigitsL - 1 ) ) NEW_LINE firstDigitR = ( R // pow ( 10 , countDigitsR - 1 ) ) NEW_LINE if ( countDigitsL < countDigitsR ) : NEW_LINE INDENT count += ( 9 * ( countDigitsR - countDigitsL - 1 ) ) NEW_LINE if ( getDistinct ( firstDigitL , countDigitsL ) >= L ) : NEW_LINE INDENT count += ( 9 - firstDigitL + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT count += ( 9 - firstDigitL ) NEW_LINE DEDENT if ( getDistinct ( firstDigitR , countDigitsR ) <= R ) : NEW_LINE INDENT count += firstDigitR NEW_LINE DEDENT else : NEW_LINE INDENT count += ( firstDigitR - 1 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( getDistinct ( firstDigitL , countDigitsL ) >= L ) : NEW_LINE INDENT count += ( 9 - firstDigitL + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT count += ( 9 - firstDigitL ) NEW_LINE DEDENT if ( getDistinct ( firstDigitR , countDigitsR ) <= R ) : NEW_LINE INDENT count -= ( 9 - firstDigitR ) NEW_LINE DEDENT else : NEW_LINE INDENT count -= ( 9 - firstDigitR + 1 ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT L = 10 NEW_LINE R = 50 NEW_LINE print ( findCount ( L , R ) ) NEW_LINE
Maximum average sum partition of an array | Python3 program for maximum average sum partition ; bottom up approach to calculate score ; storing averages from starting to each i ; ; Driver Code ; atmost partitioning size
MAX = 1000 NEW_LINE memo = [ [ 0.0 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE def score ( n , A , k ) : NEW_LINE INDENT if ( memo [ n ] [ k ] > 0 ) : NEW_LINE INDENT return memo [ n ] [ k ] NEW_LINE DEDENT sum = 0 NEW_LINE i = n - 1 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE memo [ n ] [ k ] = max ( memo [ n ] [ k ] , score ( i , A , k - 1 ) + int ( sum / ( n - i ) ) ) NEW_LINE i -= 1 NEW_LINE DEDENT return memo [ n ] [ k ] NEW_LINE DEDENT def largestSumOfAverages ( A , K ) : NEW_LINE INDENT n = len ( A ) NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE memo [ i + 1 ] [ 1 ] = int ( sum / ( i + 1 ) ) NEW_LINE DEDENT return score ( n , A , K ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 9 , 1 , 2 , 3 , 9 ] NEW_LINE K = 3 NEW_LINE print ( largestSumOfAverages ( A , K ) ) NEW_LINE DEDENT
Maximum and Minimum Values of an Algebraic Expression | Python3 program to find the maximum and minimum values of an Algebraic expression of given form ; Finding sum of array elements ; shifting the integers by 50 so that they become positive ; dp [ i ] [ j ] represents true if sum j can be reachable by choosing i numbers ; if dp [ i ] [ j ] is true , that means it is possible to select i numbers from ( n + m ) numbers to sum upto j ; k can be at max n because the left expression has n numbers ; checking if a particular sum can be reachable by choosing n numbers ; getting the actual sum as we shifted the numbers by 50 to avoid negative indexing in array ; Driver Code
def minMaxValues ( arr , n , m ) : NEW_LINE INDENT sum = 0 NEW_LINE INF = 1000000000 NEW_LINE MAX = 50 NEW_LINE for i in range ( 0 , ( n + m ) ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE arr [ i ] += 50 NEW_LINE DEDENT dp = [ [ 0 for x in range ( MAX * MAX + 1 ) ] for y in range ( MAX + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 0 , ( n + m ) ) : NEW_LINE INDENT for k in range ( min ( n , i + 1 ) , 0 , - 1 ) : NEW_LINE INDENT for j in range ( 0 , MAX * MAX + 1 ) : NEW_LINE INDENT if ( dp [ k - 1 ] [ j ] ) : NEW_LINE INDENT dp [ k ] [ j + arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT max_value = - 1 * INF NEW_LINE min_value = INF NEW_LINE for i in range ( 0 , MAX * MAX + 1 ) : NEW_LINE INDENT if ( dp [ n ] [ i ] ) : NEW_LINE INDENT temp = i - 50 * n NEW_LINE max_value = max ( max_value , temp * ( sum - temp ) ) NEW_LINE min_value = min ( min_value , temp * ( sum - temp ) ) NEW_LINE DEDENT DEDENT print ( " Maximum Value : { } Minimum Value : { } " . format ( max_value , min_value ) ) NEW_LINE DEDENT n = 2 NEW_LINE m = 2 NEW_LINE arr = [ 1 , 2 , 3 , 4 ] NEW_LINE minMaxValues ( arr , n , m ) NEW_LINE
Check if any valid sequence is divisible by M | Python3 program to check if any valid sequence is divisible by M ; Base case ; check if sum is divisible by M ; check if the current state is already computed ; 1. Try placing '+ ; 2. Try placing '- ; calculate value of res for recursive case ; store the value for res for current states and return for parent call ; Driver code
def isPossible ( n , index , Sum , M , arr , dp ) : NEW_LINE INDENT global MAX NEW_LINE if index == n : NEW_LINE INDENT if ( Sum % M ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if dp [ index ] [ Sum ] != - 1 : NEW_LINE INDENT return dp [ index ] [ Sum ] NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT placeAdd = isPossible ( n , index + 1 , Sum + arr [ index ] , M , arr , dp ) NEW_LINE DEDENT ' NEW_LINE INDENT placeMinus = isPossible ( n , index + 1 , Sum - arr [ index ] , M , arr , dp ) NEW_LINE res = placeAdd or placeMinus NEW_LINE dp [ index ] [ Sum ] = res NEW_LINE return res NEW_LINE DEDENT MAX = 1000 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE M = 4 NEW_LINE dp = [ [ - 1 ] * MAX for i in range ( n + 1 ) ] NEW_LINE res = isPossible ( n , 0 , 0 , M , arr , dp ) NEW_LINE if res : NEW_LINE INDENT print ( True ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( False ) NEW_LINE DEDENT
Dynamic Programming on Trees | Set 2 | Python3 code to find the maximum path length considering any node as root ; function to pre - calculate the array inn [ ] which stores the maximum height when travelled via branches ; initially every node has 0 height ; traverse in the subtree of u ; if child is same as parent ; dfs called ; recursively calculate the max height ; function to pre - calculate the array ouut [ ] which stores the maximum height when traveled via parent ; stores the longest and second longest branches ; traverse in the subtress of u ; compare and store the longest and second longest ; traverse in the subtree of u ; if longest branch has the node , then consider the second longest branch ; recursively calculate out [ i ] ; dfs function call ; function to prall the maximum heights from every node ; traversal to calculate inn [ ] array ; traversal to calculate out [ ] array ; prall maximum heights ; Driver Code ; initialize the tree given in the diagram ; function to print the maximum height from every node
inn = [ 0 ] * 100 NEW_LINE out = [ 0 ] * 100 NEW_LINE def dfs1 ( v , u , parent ) : NEW_LINE INDENT global inn , out NEW_LINE inn [ u ] = 0 NEW_LINE for child in v [ u ] : NEW_LINE INDENT if ( child == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs1 ( v , child , u ) NEW_LINE inn [ u ] = max ( inn [ u ] , 1 + inn [ child ] ) NEW_LINE DEDENT DEDENT def dfs2 ( v , u , parent ) : NEW_LINE INDENT global inn , out NEW_LINE mx1 , mx2 = - 1 , - 1 NEW_LINE for child in v [ u ] : NEW_LINE INDENT if ( child == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( inn [ child ] >= mx1 ) : NEW_LINE INDENT mx2 = mx1 NEW_LINE mx1 = inn [ child ] NEW_LINE DEDENT elif ( inn [ child ] > mx2 ) : NEW_LINE INDENT mx2 = inn [ child ] NEW_LINE DEDENT DEDENT for child in v [ u ] : NEW_LINE INDENT if ( child == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT longest = mx1 NEW_LINE if ( mx1 == inn [ child ] ) : NEW_LINE INDENT longest = mx2 NEW_LINE DEDENT out [ child ] = 1 + max ( out [ u ] , 1 + longest ) NEW_LINE dfs2 ( v , child , u ) NEW_LINE DEDENT DEDENT def printHeights ( v , n ) : NEW_LINE INDENT global inn , out NEW_LINE dfs1 ( v , 1 , 0 ) NEW_LINE dfs2 ( v , 1 , 0 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( " The ▁ maximum ▁ height ▁ when ▁ node " , i , " is ▁ considered ▁ as ▁ root ▁ is " , max ( inn [ i ] , out [ i ] ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 11 NEW_LINE v = [ [ ] for i in range ( n + 1 ) ] NEW_LINE v [ 1 ] . append ( 2 ) NEW_LINE v [ 2 ] . append ( 1 ) NEW_LINE v [ 1 ] . append ( 3 ) NEW_LINE v [ 3 ] . append ( 1 ) NEW_LINE v [ 1 ] . append ( 4 ) NEW_LINE v [ 4 ] . append ( 1 ) NEW_LINE v [ 2 ] . append ( 5 ) NEW_LINE v [ 5 ] . append ( 2 ) NEW_LINE v [ 2 ] . append ( 6 ) NEW_LINE v [ 6 ] . append ( 2 ) NEW_LINE v [ 3 ] . append ( 7 ) NEW_LINE v [ 7 ] . append ( 3 ) NEW_LINE v [ 7 ] . append ( 10 ) NEW_LINE v [ 10 ] . append ( 7 ) NEW_LINE v [ 7 ] . append ( 11 ) NEW_LINE v [ 11 ] . append ( 7 ) NEW_LINE v [ 4 ] . append ( 8 ) NEW_LINE v [ 8 ] . append ( 4 ) NEW_LINE v [ 4 ] . append ( 9 ) NEW_LINE v [ 9 ] . append ( 4 ) NEW_LINE printHeights ( v , n ) NEW_LINE DEDENT
Golomb sequence | Return the nth element of Golomb sequence ; base case ; Recursive Step ; Print the first n term of Golomb Sequence ; Finding first n terms of Golomb Sequence . ; Driver Code
def findGolomb ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 1 + findGolomb ( n - findGolomb ( findGolomb ( n - 1 ) ) ) NEW_LINE DEDENT def printGolomb ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( findGolomb ( i ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT n = 9 NEW_LINE printGolomb ( n ) NEW_LINE
Printing Items in 0 / 1 Knapsack | Prints the items which are put in a knapsack of capacity W ; Build table K [ ] [ ] in bottom up manner ; stores the result of Knapsack ; either the result comes from the top ( K [ i - 1 ] [ w ] ) or from ( val [ i - 1 ] + K [ i - 1 ] [ w - wt [ i - 1 ] ] ) as in Knapsack table . If it comes from the latter one / it means the item is included . ; This item is included . ; Since this weight is included its value is deducted ; Driver code
def printknapSack ( W , wt , val , n ) : NEW_LINE INDENT K = [ [ 0 for w in range ( W + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for w in range ( W + 1 ) : NEW_LINE INDENT if i == 0 or w == 0 : NEW_LINE INDENT K [ i ] [ w ] = 0 NEW_LINE DEDENT elif wt [ i - 1 ] <= w : NEW_LINE INDENT K [ i ] [ w ] = max ( val [ i - 1 ] + K [ i - 1 ] [ w - wt [ i - 1 ] ] , K [ i - 1 ] [ w ] ) NEW_LINE DEDENT else : NEW_LINE INDENT K [ i ] [ w ] = K [ i - 1 ] [ w ] NEW_LINE DEDENT DEDENT DEDENT res = K [ n ] [ W ] NEW_LINE print ( res ) NEW_LINE w = W NEW_LINE for i in range ( n , 0 , - 1 ) : NEW_LINE INDENT if res <= 0 : NEW_LINE INDENT break NEW_LINE DEDENT if res == K [ i - 1 ] [ w ] : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT print ( wt [ i - 1 ] ) NEW_LINE res = res - val [ i - 1 ] NEW_LINE w = w - wt [ i - 1 ] NEW_LINE DEDENT DEDENT DEDENT val = [ 60 , 100 , 120 ] NEW_LINE wt = [ 10 , 20 , 30 ] NEW_LINE W = 50 NEW_LINE n = len ( val ) NEW_LINE printknapSack ( W , wt , val , n ) NEW_LINE
s | To sort the array and return the answer ; sort the array ; Fill all stated with - 1 when only one element ; As dp [ 0 ] = 0 ( base case ) so min no of elements to be removed are n - 1 elements ; Iterate from 1 to n - 1 ; Driver code
def removals ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE dp = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] = - 1 NEW_LINE DEDENT ans = n - 1 NEW_LINE dp [ 0 ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] = i NEW_LINE j = dp [ i - 1 ] NEW_LINE while ( j != i and arr [ i ] - arr [ j ] > k ) : NEW_LINE j += 1 NEW_LINE dp [ i ] = min ( dp [ i ] , j ) NEW_LINE ans = min ( ans , ( n - ( i - j + 1 ) ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ 1 , 3 , 4 , 9 , 10 , 11 , 12 , 17 , 20 ] NEW_LINE n = len ( a ) NEW_LINE k = 4 NEW_LINE print ( removals ( a , n , k ) ) NEW_LINE
Maximum number of segments of lengths a , b and c | function to find the maximum number of segments ; stores the maximum number of segments each index can have ; ; 0 th index will have 0 segments base case ; traverse for all possible segments till n ; conditions if ( i + a <= n ) : avoid buffer overflow ; if ( i + b <= n ) : avoid buffer overflow ; if ( i + c <= n ) : avoid buffer overflow ; Driver code
def maximumSegments ( n , a , b , c ) : NEW_LINE INDENT dp = [ - 1 ] * ( n + 10 ) NEW_LINE DEDENT / * initialize with - 1 * / NEW_LINE INDENT dp [ 0 ] = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( dp [ i ] != - 1 ) : NEW_LINE INDENT dp [ i + a ] = max ( dp [ i ] + 1 , dp [ i + a ] ) NEW_LINE dp [ i + b ] = max ( dp [ i ] + 1 , dp [ i + b ] ) NEW_LINE dp [ i + c ] = max ( dp [ i ] + 1 , dp [ i + c ] ) NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT n = 7 NEW_LINE a = 5 NEW_LINE b = 2 NEW_LINE c = 5 NEW_LINE print ( maximumSegments ( n , a , b , c ) ) NEW_LINE
Maximize the sum of selected numbers from an array to make it empty | function to maximize the sum of selected numbers ; maximum in the sequence ; stores the occurrences of the numbers ; marks the occurrence of every number in the sequence ; ans to store the result ; Using the above mentioned approach ; if occurence is greater than 0 ; add it to ans ; decrease i - 1 th element by 1 ; decrease ith element by 1 ; decrease i ; Driver code
def maximizeSum ( a , n ) : NEW_LINE INDENT maximum = max ( a ) NEW_LINE ans = dict . fromkeys ( range ( 0 , n + 1 ) , 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans [ a [ i ] ] += 1 NEW_LINE DEDENT result = 0 NEW_LINE i = maximum NEW_LINE while i > 0 : NEW_LINE INDENT if ans [ i ] > 0 : NEW_LINE INDENT result += i ; NEW_LINE ans [ i - 1 ] -= 1 ; NEW_LINE ans [ i ] -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT i -= 1 ; NEW_LINE DEDENT DEDENT return result ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( maximizeSum ( a , n ) ) NEW_LINE DEDENT
Print n terms of Newman | Function to find the n - th element ; Declare array to store sequence ; driver code
def sequence ( n ) : NEW_LINE INDENT f = [ 0 , 1 , 1 ] NEW_LINE print ( f [ 1 ] , end = " ▁ " ) , NEW_LINE print ( f [ 2 ] , end = " ▁ " ) , NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT f . append ( f [ f [ i - 1 ] ] + f [ i - f [ i - 1 ] ] ) NEW_LINE print ( f [ i ] , end = " ▁ " ) , NEW_LINE DEDENT DEDENT n = 13 NEW_LINE sequence ( n ) NEW_LINE
LCS formed by consecutive segments of at least length K | Returns the length of the longest common subsequence with a minimum of length of K consecutive segments ; length of strings ; declare the lcs and cnt array ; iterate from i = 1 to n and j = 1 to j = m ; stores the maximum of lcs [ i - 1 ] [ j ] and lcs [ i ] [ j - 1 ] ; when both the characters are equal of s1 and s2 ; when length of common segment is more than k , then update lcs answer by adding that segment to the answer ; formulate for all length of segments to get the longest subsequence with consecutive Common Segment of length of min k length ; update lcs value by adding segment length ; Driver code
def longestSubsequenceCommonSegment ( k , s1 , s2 ) : NEW_LINE INDENT n = len ( s1 ) NEW_LINE m = len ( s2 ) NEW_LINE lcs = [ [ 0 for x in range ( m + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE cnt = [ [ 0 for x in range ( m + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT lcs [ i ] [ j ] = max ( lcs [ i - 1 ] [ j ] , lcs [ i ] [ j - 1 ] ) NEW_LINE if ( s1 [ i - 1 ] == s2 [ j - 1 ] ) : NEW_LINE INDENT cnt [ i ] [ j ] = cnt [ i - 1 ] [ j - 1 ] + 1 ; NEW_LINE DEDENT if ( cnt [ i ] [ j ] >= k ) : NEW_LINE INDENT for a in range ( k , cnt [ i ] [ j ] + 1 ) : NEW_LINE INDENT lcs [ i ] [ j ] = max ( lcs [ i ] [ j ] , lcs [ i - a ] [ j - a ] + a ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return lcs [ n ] [ m ] NEW_LINE DEDENT k = 4 NEW_LINE s1 = " aggasdfa " NEW_LINE s2 = " aggajasdfa " NEW_LINE print ( longestSubsequenceCommonSegment ( k , s1 , s2 ) ) NEW_LINE
Check for possible path in 2D matrix | Python3 program to find if there is path from top left to right bottom ; to find the path from top left to bottom right ; directions ; queue ; insert the top right corner . ; until queue is empty ; mark as visited ; destination is reached . ; check all four directions ; using the direction array ; not blocked and valid ; Given array ; path from arr [ 0 ] [ 0 ] to arr [ row ] [ col ]
row = 5 NEW_LINE col = 5 NEW_LINE def isPath ( arr ) : NEW_LINE INDENT Dir = [ [ 0 , 1 ] , [ 0 , - 1 ] , [ 1 , 0 ] , [ - 1 , 0 ] ] NEW_LINE q = [ ] NEW_LINE q . append ( ( 0 , 0 ) ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT p = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE arr [ p [ 0 ] ] [ p [ 1 ] ] = - 1 NEW_LINE if ( p == ( row - 1 , col - 1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 4 ) : NEW_LINE INDENT a = p [ 0 ] + Dir [ i ] [ 0 ] NEW_LINE b = p [ 1 ] + Dir [ i ] [ 1 ] NEW_LINE if ( a >= 0 and b >= 0 and a < row and b < col and arr [ a ] [ b ] != - 1 ) : NEW_LINE INDENT q . append ( ( a , b ) ) NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT arr = [ [ 0 , 0 , 0 , - 1 , 0 ] , [ - 1 , 0 , 0 , - 1 , - 1 ] , [ 0 , 0 , 0 , - 1 , 0 ] , [ - 1 , 0 , - 1 , 0 , - 1 ] , [ 0 , 0 , - 1 , 0 , 0 ] ] NEW_LINE if ( isPath ( arr ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Next Smaller Element | prints element and NSE pair for all elements of arr [ ] of size n ; push the first element to stack ; iterate for rest of the elements ; if stack is not empty , then pop an element from stack . If the popped element is greater than next , then a ) print the pair b ) keep popping while elements are greater and stack is not empty ; push next to stack so that we can find next smaller for it ; After iterating over the loop , the remaining elements in stack do not have the next smaller element , so print - 1 for them ;
def printNSE ( arr , n ) : NEW_LINE INDENT s = [ ] NEW_LINE mp = { } NEW_LINE s . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT s . append ( arr [ i ] ) NEW_LINE continue NEW_LINE DEDENT while ( len ( s ) != 0 and s [ - 1 ] > arr [ i ] ) : NEW_LINE INDENT mp [ s [ - 1 ] ] = arr [ i ] NEW_LINE s . pop ( ) NEW_LINE DEDENT s . append ( arr [ i ] ) NEW_LINE DEDENT while ( len ( s ) != 0 ) : NEW_LINE INDENT mp [ s [ - 1 ] ] = - 1 NEW_LINE s . pop ( ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , " - - - > " , mp [ arr [ i ] ] ) NEW_LINE DEDENT DEDENT / * Driver code * / NEW_LINE arr = [ 11 , 13 , 21 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE printNSE ( arr , n ) NEW_LINE
Entringer Number | Return Entringer Number E ( n , k ) ; Base cases ; Finding dp [ i ] [ j ] ; Driven Program
def zigzag ( n , k ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( k + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 0 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , k + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ i - j ] ) NEW_LINE DEDENT DEDENT return dp [ n ] [ k ] NEW_LINE DEDENT n = 4 NEW_LINE k = 3 NEW_LINE print ( zigzag ( n , k ) ) NEW_LINE
Lobb Number | Returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Return the Lm , n Lobb Number . ; Driven Program
def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ [ 0 for j in range ( k + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT for j in range ( 0 , min ( i , k ) + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT C [ i ] [ j ] = ( C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return C [ n ] [ k ] NEW_LINE DEDENT def lobb ( n , m ) : NEW_LINE INDENT return ( ( ( 2 * m + 1 ) * binomialCoeff ( 2 * n , m + n ) ) / ( m + n + 1 ) ) NEW_LINE DEDENT n = 5 NEW_LINE m = 3 NEW_LINE print ( int ( lobb ( n , m ) ) ) NEW_LINE
Count of arrays having consecutive element with different values | Return the number of lists with given constraints . ; Initialising dp [ 0 ] and dp [ 1 ] ; Computing f ( i ) for each 2 <= i <= n . ; Driven code
def countarray ( n , k , x ) : NEW_LINE INDENT dp = list ( ) NEW_LINE dp . append ( 0 ) NEW_LINE dp . append ( 1 ) NEW_LINE i = 2 NEW_LINE while i < n : NEW_LINE INDENT dp . append ( ( k - 2 ) * dp [ i - 1 ] + ( k - 1 ) * dp [ i - 2 ] ) NEW_LINE i = i + 1 NEW_LINE DEDENT return ( ( k - 1 ) * dp [ n - 2 ] if x == 1 else dp [ n - 1 ] ) NEW_LINE DEDENT n = 4 NEW_LINE k = 3 NEW_LINE x = 2 NEW_LINE print ( countarray ( n , k , x ) ) NEW_LINE
Number of palindromic subsequences of length k where k <= 3 | Python3 program to count number of subsequences of given length . ; Precompute the prefix and suffix array . ; Precompute the prefix 2D array ; Precompute the Suffix 2D array . ; Find the number of palindromic subsequence of length k ; If k is 1. ; If k is 2 ; Adding all the products of prefix array ; For k greater than 2. Adding all the products of value of prefix and suffix array . ; Driven Program
MAX = 100 NEW_LINE MAX_CHAR = 26 NEW_LINE def precompute ( s , n , l , r ) : NEW_LINE INDENT l [ ord ( s [ 0 ] ) - ord ( ' a ' ) ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( MAX_CHAR ) : NEW_LINE INDENT l [ j ] [ i ] += l [ j ] [ i - 1 ] NEW_LINE DEDENT l [ ord ( s [ i ] ) - ord ( ' a ' ) ] [ i ] += 1 NEW_LINE DEDENT r [ ord ( s [ n - 1 ] ) - ord ( ' a ' ) ] [ n - 1 ] = 1 NEW_LINE k = n - 2 NEW_LINE while ( k >= 0 ) : NEW_LINE INDENT for j in range ( MAX_CHAR ) : NEW_LINE INDENT r [ j ] [ k ] += r [ j ] [ k + 1 ] NEW_LINE DEDENT r [ ord ( s [ k ] ) - ord ( ' a ' ) ] [ k ] += 1 NEW_LINE k -= 1 NEW_LINE DEDENT DEDENT def countPalindromes ( k , n , l , r ) : NEW_LINE INDENT ans = 0 NEW_LINE if ( k == 1 ) : NEW_LINE INDENT for i in range ( MAX_CHAR ) : NEW_LINE INDENT ans += l [ i ] [ n - 1 ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if ( k == 2 ) : NEW_LINE INDENT for i in range ( MAX_CHAR ) : NEW_LINE INDENT ans += ( ( l [ i ] [ n - 1 ] * ( l [ i ] [ n - 1 ] - 1 ) ) / 2 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT for j in range ( MAX_CHAR ) : NEW_LINE INDENT ans += l [ j ] [ i - 1 ] * r [ j ] [ i + 1 ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT s = " aabab " NEW_LINE k = 2 NEW_LINE n = len ( s ) NEW_LINE l = [ [ 0 for x in range ( MAX ) ] for y in range ( MAX_CHAR ) ] NEW_LINE r = [ [ 0 for x in range ( MAX ) ] for y in range ( MAX_CHAR ) ] NEW_LINE precompute ( s , n , l , r ) NEW_LINE print ( countPalindromes ( k , n , l , r ) ) NEW_LINE
Minimum cost to make Longest Common Subsequence of length k | Python3 program to calculate Minimum cost to make Longest Common Subsequence of length k ; Return Minimum cost to make LCS of length k ; If k is 0 ; If length become less than 0 , return big number ; If state already calculated ; Finding cost ; ; Driver Code
N = 30 NEW_LINE def solve ( X , Y , l , r , k , dp ) : NEW_LINE INDENT if k == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if l < 0 or r < 0 : NEW_LINE INDENT return 1000000000 NEW_LINE DEDENT if dp [ l ] [ r ] [ k ] != - 1 : NEW_LINE INDENT return dp [ l ] [ r ] [ k ] NEW_LINE DEDENT cost = ( ( ord ( X [ l ] ) - ord ( ' a ' ) ) ^ ( ord ( Y [ r ] ) - ord ( ' a ' ) ) ) NEW_LINE DEDENT / * Finding minimum cost and saving the state value * / NEW_LINE INDENT dp [ l ] [ r ] [ k ] = min ( [ cost + solve ( X , Y , l - 1 , r - 1 , k - 1 , dp ) , solve ( X , Y , l - 1 , r , k , dp ) , solve ( X , Y , l , r - 1 , k , dp ) ] ) NEW_LINE return dp [ l ] [ r ] [ k ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = " abble " NEW_LINE Y = " pie " NEW_LINE n = len ( X ) NEW_LINE m = len ( Y ) NEW_LINE k = 2 NEW_LINE dp = [ [ [ - 1 ] * N for __ in range ( N ) ] for ___ in range ( N ) ] NEW_LINE ans = solve ( X , Y , n - 1 , m - 1 , k , dp ) NEW_LINE print ( - 1 if ans == 1000000000 else ans ) NEW_LINE DEDENT
Maximum sum path in a matrix from top to bottom | Python3 implementation to find the maximum sum path in a matrix ; function to find the maximum sum path in a matric ; if there is a single elementif there is a single element only only ; dp [ ] [ ] matrix to store the results of each iteration ; base case , copying elements of last row ; building up the dp [ ] [ ] matrix from bottom to the top row ; finding the maximum diagonal element in the ( i + 1 ) th row if that cell exists ; adding that ' max ' element to the mat [ i ] [ j ] element ; finding the maximum value from the first row of dp [ ] [ ] ; required maximum sum ; Driver program to test above
SIZE = 10 NEW_LINE INT_MIN = - 10000000 NEW_LINE def maxSum ( mat , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return mat [ 0 ] [ 0 ] NEW_LINE DEDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE maxSum = INT_MIN NEW_LINE for j in range ( n ) : NEW_LINE INDENT dp [ n - 1 ] [ j ] = mat [ n - 1 ] [ j ] NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT maxi = INT_MIN NEW_LINE if ( ( ( ( j - 1 ) >= 0 ) and ( maxi < dp [ i + 1 ] [ j - 1 ] ) ) ) : NEW_LINE INDENT maxi = dp [ i + 1 ] [ j - 1 ] NEW_LINE DEDENT if ( ( ( ( j + 1 ) < n ) and ( maxi < dp [ i + 1 ] [ j + 1 ] ) ) ) : NEW_LINE INDENT maxi = dp [ i + 1 ] [ j + 1 ] NEW_LINE DEDENT dp [ i ] [ j ] = mat [ i ] [ j ] + maxi NEW_LINE DEDENT DEDENT for j in range ( n ) : NEW_LINE INDENT if ( maxSum < dp [ 0 ] [ j ] ) : NEW_LINE INDENT maxSum = dp [ 0 ] [ j ] NEW_LINE DEDENT DEDENT return maxSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 5 , 6 , 1 , 7 ] , [ - 2 , 10 , 8 , - 1 ] , [ 3 , - 7 , - 9 , 11 ] , [ 12 , - 4 , 2 , 6 ] ] NEW_LINE n = 4 NEW_LINE print ( " Maximum ▁ Sum = " , maxSum ( mat , n ) ) NEW_LINE DEDENT
Longest Repeated Subsequence | This function mainly returns LCS ( str , str ) with a condition that same characters at same index are not considered . ; This part of code is same as below post it fills dp [ ] [ ] https : www . geeksforgeeks . org / longest - repeating - subsequence / OR the code mentioned above ; This part of code finds the result string using dp [ ] [ ] Initialize result ; Traverse dp [ ] [ ] from bottom right ; If this cell is same as diagonally adjacent cell just above it , then same characters are present at str [ i - 1 ] and str [ j - 1 ] . Append any of them to result . ; Otherwise we move to the side that gave us maximum result . ; Since we traverse dp [ ] [ ] from bottom , we get result in reverse order . ; Driver Program
def longestRepeatedSubSeq ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( str [ i - 1 ] == str [ j - 1 ] and i != j ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT res = ' ' NEW_LINE i = n NEW_LINE j = n NEW_LINE while ( i > 0 and j > 0 ) : NEW_LINE INDENT if ( dp [ i ] [ j ] == dp [ i - 1 ] [ j - 1 ] + 1 ) : NEW_LINE INDENT res += str [ i - 1 ] NEW_LINE i -= 1 NEW_LINE j -= 1 NEW_LINE DEDENT elif ( dp [ i ] [ j ] == dp [ i - 1 ] [ j ] ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT res = ' ' . join ( reversed ( res ) ) NEW_LINE return res NEW_LINE DEDENT str = ' AABEBCDD ' NEW_LINE print ( longestRepeatedSubSeq ( str ) ) NEW_LINE
Sub | Tree traversal to compute minimum difference ; Initial min difference is the color of node ; Traversing its children ; Not traversing the parent ; If the child is Adding positively to difference , we include it in the answer Otherwise , we leave the sub - tree and include 0 ( nothing ) in the answer ; DFS for colour difference : 1 colour - 2 colour ; Minimum colour difference is maximum answer value ; Clearing the current value to check for colour2 as well ; Interchanging the colours ; DFS for colour difference : 2 colour - 1 colour ; Checking if colour2 makes the minimum colour difference ; Nodes ; Adjacency list representation ; Edges ; Index represent the colour of that node There is no Node 0 , so we start from index 1 to N ; Printing the result
def dfs ( node , parent , tree , colour , answer ) : NEW_LINE INDENT answer [ node ] = colour [ node ] NEW_LINE for u in tree [ node ] : NEW_LINE INDENT if ( u == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( u , node , tree , colour , answer ) NEW_LINE answer [ node ] += max ( answer [ u ] , 0 ) NEW_LINE DEDENT DEDENT def maxDiff ( tree , colour , N ) : NEW_LINE INDENT answer = [ 0 for _ in range ( N + 1 ) ] NEW_LINE dfs ( 1 , 0 , tree , colour , answer ) NEW_LINE high = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT high = max ( high , answer [ i ] ) NEW_LINE answer [ i ] = 0 NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if colour [ i ] == - 1 : NEW_LINE INDENT colour [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT colour [ i ] = - 1 NEW_LINE DEDENT DEDENT dfs ( 1 , 0 , tree , colour , answer ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT high = max ( high , answer [ i ] ) NEW_LINE DEDENT return high NEW_LINE DEDENT N = 5 NEW_LINE tree = [ list ( ) for _ in range ( N + 1 ) ] NEW_LINE tree [ 1 ] . append ( 2 ) NEW_LINE tree [ 2 ] . append ( 1 ) NEW_LINE tree [ 1 ] . append ( 3 ) NEW_LINE tree [ 3 ] . append ( 1 ) NEW_LINE tree [ 2 ] . append ( 4 ) NEW_LINE tree [ 4 ] . append ( 2 ) NEW_LINE tree [ 3 ] . append ( 5 ) NEW_LINE tree [ 5 ] . append ( 3 ) NEW_LINE colour = [ 0 , 1 , 1 , - 1 , - 1 , 1 ] NEW_LINE print ( maxDiff ( tree , colour , N ) ) NEW_LINE
Maximum elements that can be made equal with k updates | Function to calculate the maximum number of equal elements possible with atmost K increment of values . Here we have done sliding window to determine that whether there are x number of elements present which on increment will become equal . The loop here will run in fashion like 0. . . x - 1 , 1. . . x , 2. . . x + 1 , ... . , n - x - 1. . . n - 1 ; It can be explained with the reasoning that if for some x number of elements we can update the values then the increment to the segment ( i to j having length -> x ) so that all will be equal is ( x * maxx [ j ] ) this is the total sum of segment and ( pre [ j ] - pre [ i ] ) is present sum So difference of them should be less than k if yes , then that segment length ( x ) can be possible return true ; sort the array in ascending order ; Initializing the prefix array and maximum array ; Calculating prefix sum of the array ; Calculating max value upto that position in the array ; Binary search applied for computation here ; printing result ; Driver Code
def ElementsCalculationFunc ( pre , maxx , x , k , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = x NEW_LINE while j <= n : NEW_LINE INDENT if ( x * maxx [ j ] - ( pre [ j ] - pre [ i ] ) <= k ) : NEW_LINE INDENT return True NEW_LINE DEDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return False NEW_LINE DEDENT def MaxNumberOfElements ( a , n , k ) : NEW_LINE INDENT a . sort ( ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT pre [ i ] = 0 NEW_LINE maxx [ i ] = 0 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + a [ i - 1 ] NEW_LINE maxx [ i ] = max ( maxx [ i - 1 ] , a [ i - 1 ] ) NEW_LINE DEDENT l = 1 NEW_LINE r = n NEW_LINE while ( l < r ) : NEW_LINE INDENT mid = ( l + r ) // 2 NEW_LINE if ( ElementsCalculationFunc ( pre , maxx , mid - 1 , k , n ) ) : NEW_LINE INDENT ans = mid NEW_LINE l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE MaxNumberOfElements ( arr , n , k ) NEW_LINE DEDENT
Remove array end element to maximize the sum of product | Python 3 program to find maximum score we can get by removing elements from either end . ; If only one element left . ; If already calculated , return the value . ; Computing Maximum value when element at index i and index j is to be choosed . ; Driver Code
MAX = 50 NEW_LINE def solve ( dp , a , low , high , turn ) : NEW_LINE INDENT if ( low == high ) : NEW_LINE INDENT return a [ low ] * turn NEW_LINE DEDENT if ( dp [ low ] [ high ] != 0 ) : NEW_LINE INDENT return dp [ low ] [ high ] NEW_LINE DEDENT dp [ low ] [ high ] = max ( a [ low ] * turn + solve ( dp , a , low + 1 , high , turn + 1 ) , a [ high ] * turn + solve ( dp , a , low , high - 1 , turn + 1 ) ) ; NEW_LINE return dp [ low ] [ high ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 1 , 5 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE dp = [ [ 0 for x in range ( MAX ) ] for y in range ( MAX ) ] NEW_LINE print ( solve ( dp , arr , 0 , n - 1 , 1 ) ) NEW_LINE DEDENT
Maximum sum bitonic subarray | function to find the maximum sum bitonic subarray ; ' msis [ ] ' to store the maximum sum increasing subarray up to each index of ' arr ' from the beginning ' msds [ ] ' to store the maximum sum decreasing subarray from each index of ' arr ' up to the end ; to store the maximum sum bitonic subarray ; building up the maximum sum increasing subarray for each array index ; building up the maximum sum decreasing subarray for each array index ; for each array index , calculating the maximum sum of bitonic subarray of which it is a part of ; if true , then update ' max ' bitonic subarray sum ; required maximum sum ; Driver Code
def maxSumBitonicSubArr ( arr , n ) : NEW_LINE INDENT msis = [ None ] * n NEW_LINE msds = [ None ] * n NEW_LINE max_sum = 0 NEW_LINE msis [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT msis [ i ] = msis [ i - 1 ] + arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT msis [ i ] = arr [ i ] NEW_LINE DEDENT DEDENT msds [ n - 1 ] = arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT msds [ i ] = msds [ i + 1 ] + arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT msds [ i ] = arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( max_sum < ( msis [ i ] + msds [ i ] - arr [ i ] ) ) : NEW_LINE INDENT max_sum = ( msis [ i ] + msds [ i ] - arr [ i ] ) NEW_LINE DEDENT DEDENT return max_sum NEW_LINE DEDENT arr = [ 5 , 3 , 9 , 2 , 7 , 6 , 4 ] ; NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum ▁ Sum ▁ = ▁ " + str ( maxSumBitonicSubArr ( arr , n ) ) ) NEW_LINE
Find k | Structure to store the start and end point ; Function to find Kth smallest number in a vector of merged intervals ; Traverse merged [ ] to find Kth smallest element using Linear search . ; To combined both type of ranges , overlapping as well as non - overlapping . ; Sorting intervals according to start time ; Merging all intervals into merged ; To check if starting point of next range is lying between the previous range and ending point of next range is greater than the Ending point of previous range then update ending point of previous range by ending point of next range . ; If starting point of next range is greater than the ending point of previous range then store next range in merged [ ] . ; Driver Code ; Merge all intervals into merged [ ] ; Processing all queries on merged intervals
class Interval : NEW_LINE INDENT def __init__ ( self , s , e ) : NEW_LINE INDENT self . s = s NEW_LINE self . e = e NEW_LINE DEDENT DEDENT def kthSmallestNum ( merged : list , k : int ) -> int : NEW_LINE INDENT n = len ( merged ) NEW_LINE for j in range ( n ) : NEW_LINE INDENT if k <= abs ( merged [ j ] . e - merged [ j ] . s + 1 ) : NEW_LINE INDENT return merged [ j ] . s + k - 1 NEW_LINE DEDENT k = k - abs ( merged [ j ] . e - merged [ j ] . s + 1 ) NEW_LINE DEDENT if k : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT def mergeIntervals ( merged : list , arr : list , n : int ) : NEW_LINE INDENT arr . sort ( key = lambda a : a . s ) NEW_LINE merged . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prev = merged [ - 1 ] NEW_LINE curr = arr [ i ] NEW_LINE if curr . s >= prev . s and curr . s <= prev . e and curr . e > prev . e : NEW_LINE INDENT merged [ - 1 ] . e = curr . e NEW_LINE DEDENT else : NEW_LINE INDENT if curr . s > prev . e : NEW_LINE INDENT merged . append ( curr ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ Interval ( 2 , 6 ) , Interval ( 4 , 7 ) ] NEW_LINE n = len ( arr ) NEW_LINE query = [ 5 , 8 ] NEW_LINE q = len ( query ) NEW_LINE merged = [ ] NEW_LINE mergeIntervals ( merged , arr , n ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( kthSmallestNum ( merged , query [ i ] ) ) NEW_LINE DEDENT DEDENT
Shortest possible combination of two strings | Prints super sequence of a [ 0. . m - 1 ] and b [ 0. . n - 1 ] ; Fill table in bottom up manner ; Below steps follow above recurrence ; Following code is used to print supersequence ; Create a string of size index + 1 to store the result ; Start from the right - most - bottom - most corner and one by one store characters in res [ ] ; If current character in a [ ] and b are same , then current character is part of LCS ; Put current character in result ; reduce values of i , j and indexs ; If not same , then find the larger of two and go in the direction of larger value ; Copy remaining characters of string 'a ; Copy remaining characters of string 'b ; Print the result ; Driver Code
def printSuperSeq ( a , b ) : NEW_LINE INDENT m = len ( a ) NEW_LINE n = len ( b ) NEW_LINE dp = [ [ 0 ] * ( n + 1 ) for i in range ( m + 1 ) ] NEW_LINE for i in range ( 0 , m + 1 ) : NEW_LINE INDENT for j in range ( 0 , n + 1 ) : NEW_LINE INDENT if not i : NEW_LINE INDENT dp [ i ] [ j ] = j ; NEW_LINE DEDENT elif not j : NEW_LINE INDENT dp [ i ] [ j ] = i ; NEW_LINE DEDENT elif ( a [ i - 1 ] == b [ j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 1 + min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ; NEW_LINE DEDENT DEDENT DEDENT index = dp [ m ] [ n ] ; NEW_LINE res = [ " " ] * ( index ) NEW_LINE i = m NEW_LINE j = n ; NEW_LINE while ( i > 0 and j > 0 ) : NEW_LINE INDENT if ( a [ i - 1 ] == b [ j - 1 ] ) : NEW_LINE INDENT res [ index - 1 ] = a [ i - 1 ] ; NEW_LINE i -= 1 NEW_LINE j -= 1 NEW_LINE index -= 1 NEW_LINE DEDENT elif ( dp [ i - 1 ] [ j ] < dp [ i ] [ j - 1 ] ) : NEW_LINE INDENT res [ index - 1 ] = a [ i - 1 ] NEW_LINE i -= 1 NEW_LINE index -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT res [ index - 1 ] = b [ j - 1 ] NEW_LINE j -= 1 NEW_LINE index -= 1 NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT while ( i > 0 ) : NEW_LINE INDENT res [ index - 1 ] = a [ i - 1 ] NEW_LINE i -= 1 NEW_LINE index -= 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT while ( j > 0 ) : NEW_LINE INDENT res [ index - 1 ] = b [ j - 1 ] NEW_LINE j -= 1 NEW_LINE index -= 1 NEW_LINE DEDENT print ( " " . join ( res ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = " algorithm " NEW_LINE b = " rhythm " NEW_LINE printSuperSeq ( a , b ) NEW_LINE DEDENT