text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Length of longest Palindromic Subsequence of even length with no two adjacent characters same | To store the values of subproblems ; Function to find the Longest Palindromic subsequence of even length with no two adjacent characters same ; Base cases If the string length is 1 return 0 ; If the string length is 2 ; Check if the characters match ; If the value with given parameters is previously calculated ; If the first and last character of the string matches with the given character ; Remove the first and last character and call the function for all characters ; If it does not match ; Then find the first and last index of given character in the given string ; Take the substring from i to j and call the function with substring and the given character ; Store the answer for future use ; Driver code ; Check for all starting characters
dp = { } NEW_LINE def solve ( s , c ) : NEW_LINE INDENT if ( len ( s ) == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( len ( s ) == 2 ) : NEW_LINE INDENT if ( s [ 0 ] == s [ 1 ] and s [ 0 ] == c ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( s + " ▁ " + c ) in dp : NEW_LINE INDENT return dp [ s + " ▁ " + c ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( s [ 0 ] == s [ len ( s ) - 1 ] and s [ 0 ] == c ) : NEW_LINE INDENT for c1 in range ( 97 , 123 ) : NEW_LINE INDENT if ( chr ( c1 ) != c ) : NEW_LINE INDENT ans = max ( ans , 1 + solve ( s [ 1 : len ( s ) - 1 ] , chr ( c1 ) ) ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == c ) : NEW_LINE INDENT for j in range ( len ( s ) - 1 , i , - 1 ) : NEW_LINE INDENT if ( s [ j ] == c ) : NEW_LINE INDENT if ( j == i ) : NEW_LINE INDENT break NEW_LINE DEDENT ans = solve ( s [ i : j - i + 2 ] , c ) NEW_LINE break NEW_LINE DEDENT DEDENT break NEW_LINE DEDENT DEDENT DEDENT dp [ s + " ▁ " + c ] = ans NEW_LINE return dp [ s + " ▁ " + c ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abscrcdba " NEW_LINE ma = 0 NEW_LINE for c1 in range ( 97 , 123 ) : NEW_LINE INDENT ma = max ( ma , solve ( s , chr ( c1 ) ) * 2 ) NEW_LINE DEDENT print ( ma ) NEW_LINE DEDENT
Eggs dropping puzzle | Set 2 | Function to return the minimum number of trials needed in the worst case with n eggs and k floors ; Fill all the entries in table using optimal substructure property ; Return the minimum number of moves ; Driver code
def eggDrop ( n , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( k + 1 ) ] NEW_LINE x = 0 ; NEW_LINE while ( dp [ x ] [ n ] < k ) : NEW_LINE INDENT x += 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ x ] [ i ] = dp [ x - 1 ] [ i - 1 ] + dp [ x - 1 ] [ i ] + 1 ; NEW_LINE DEDENT DEDENT return x ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 ; k = 36 ; NEW_LINE print ( eggDrop ( n , k ) ) ; NEW_LINE DEDENT
Maximum length of Strictly Increasing Sub | Function to return the maximum length of strictly increasing subarray after removing atmost one element ; Create two arrays pre and pos ; Find out the contribution of the current element in array [ 0 , i ] and update pre [ i ] ; Find out the contribution of the current element in array [ N - 1 , i ] and update pos [ i ] ; Calculate the maximum length of the stricly increasing subarray without removing any element ; Calculate the maximum length of the strictly increasing subarray after removing the current element ; Driver code
def maxIncSubarr ( a , n ) : NEW_LINE INDENT pre = [ 0 ] * n ; NEW_LINE pos = [ 0 ] * n ; NEW_LINE pre [ 0 ] = 1 ; NEW_LINE pos [ n - 1 ] = 1 ; NEW_LINE l = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] > a [ i - 1 ] ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT pre [ i ] = 1 ; NEW_LINE DEDENT DEDENT l = 1 ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] < a [ i + 1 ] ) : NEW_LINE INDENT pos [ i ] = pos [ i + 1 ] + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT pos [ i ] = 1 ; NEW_LINE DEDENT DEDENT ans = 0 ; NEW_LINE l = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] > a [ i - 1 ] ) : NEW_LINE INDENT l += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT l = 1 ; NEW_LINE DEDENT ans = max ( ans , l ) ; NEW_LINE DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( a [ i - 1 ] < a [ i + 1 ] ) : NEW_LINE INDENT ans = max ( pre [ i - 1 ] + pos [ i + 1 ] , ans ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxIncSubarr ( arr , n ) ) ; NEW_LINE DEDENT
Number of square matrices with all 1 s | Python3 program to return the number of square submatrices with all 1 s ; Function to return the number of square submatrices with all 1 s ; Initialize count variable ; If a [ i ] [ j ] is equal to 0 ; Calculate number of square submatrices ending at ( i , j ) ; Calculate the sum of the array ; Driver code
n = 3 NEW_LINE m = 3 NEW_LINE def countSquareMatrices ( a , N , M ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 1 , M ) : NEW_LINE INDENT if ( a [ i ] [ j ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT a [ i ] [ j ] = min ( [ a [ i - 1 ] [ j ] , a [ i ] [ j - 1 ] , a [ i - 1 ] [ j - 1 ] ] ) + 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT count += a [ i ] [ j ] NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ [ 1 , 0 , 1 ] , [ 1 , 1 , 0 ] , [ 1 , 1 , 0 ] ] NEW_LINE print ( countSquareMatrices ( arr , n , m ) ) NEW_LINE
Count number of increasing sub | Python3 implementation of the approach ; Segment tree array ; Function for point update in segment tree ; Base case ; If l == r == up ; Mid element ; Updating the segment tree ; Function for the range sum - query ; Base case ; Mid element ; CallIng for the left and the right subtree ; Function to return the count ; Copying array arr to sort it ; Sorting array brr ; Map to store the rank of each element ; dp array ; To store the final answer ; Updating the dp array ; Rank of the element ; Solving the dp - states using segment tree ; UpdatIng the final answer ; Updating the segment tree ; Returning the final answer ; Driver code
N = 10000 NEW_LINE seg = [ 0 ] * ( 3 * N ) NEW_LINE def update ( In , l , r , up_In , val ) : NEW_LINE INDENT if ( r < up_In or l > up_In ) : NEW_LINE INDENT return seg [ In ] NEW_LINE DEDENT if ( l == up_In and r == up_In ) : NEW_LINE INDENT seg [ In ] = val NEW_LINE return val NEW_LINE DEDENT m = ( l + r ) // 2 NEW_LINE seg [ In ] = update ( 2 * In + 1 , l , m , up_In , val ) + update ( 2 * In + 2 , m + 1 , r , up_In , val ) NEW_LINE return seg [ In ] NEW_LINE DEDENT def query ( In , l , r , l1 , r1 ) : NEW_LINE INDENT if ( l > r ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( r < l1 or l > r1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( l1 <= l and r <= r1 ) : NEW_LINE INDENT return seg [ In ] NEW_LINE DEDENT m = ( l + r ) // 2 NEW_LINE return query ( 2 * In + 1 , l , m , l1 , r1 ) + query ( 2 * In + 2 , m + 1 , r , l1 , r1 ) NEW_LINE DEDENT def fIndCnt ( arr , n ) : NEW_LINE INDENT brr = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT brr [ i ] = arr [ i ] NEW_LINE DEDENT brr = sorted ( brr ) NEW_LINE r = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT r [ brr [ i ] ] = i + 1 NEW_LINE DEDENT dp = [ 0 ] * n NEW_LINE ans = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT rank = r [ arr [ i ] ] NEW_LINE dp [ i ] = 1 + query ( 0 , 0 , n - 1 , rank , n - 1 ) NEW_LINE ans += dp [ i ] NEW_LINE update ( 0 , 0 , n - 1 , rank - 1 , dp [ i ] + query ( 0 , 0 , n - 1 , rank - 1 , rank - 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 10 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( fIndCnt ( arr , n ) ) NEW_LINE
Minimum cost to build N blocks from one block | Function to calculate min cost to build N blocks ; Initialize base case ; Recurence when i is odd ; Recurence when i is even ; Driver code
def minCost ( n , x , y , z ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = dp [ 1 ] = 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( i % 2 == 1 ) : NEW_LINE INDENT dp [ i ] = min ( dp [ ( i + 1 ) // 2 ] + x + z , dp [ i - 1 ] + y ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = min ( dp [ i // 2 ] + x , dp [ i - 1 ] + y ) NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT n = 5 NEW_LINE x = 2 NEW_LINE y = 1 NEW_LINE z = 3 NEW_LINE print ( minCost ( n , x , y , z ) ) NEW_LINE
Size of the largest divisible subset in an Array | Python3 implementation of the above approach ; Function to find the size of the largest divisible subarray ; Mark all elements of the array ; Traverse reverse ; For all multiples of i ; Return the required answer ; Driver code ; Function call
N = 1000005 NEW_LINE def maximum_set ( a , n ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE for i in a : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE DEDENT ans = 1 NEW_LINE for i in range ( N - 1 , 0 , - 1 ) : NEW_LINE INDENT if ( dp [ i ] != 0 ) : NEW_LINE INDENT for j in range ( 2 * i , N , i ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , 1 + dp [ j ] ) NEW_LINE ans = max ( ans , dp [ i ] ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 3 , 4 , 6 , 8 , 10 , 18 , 21 , 24 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maximum_set ( arr , n ) ) NEW_LINE
Longest sub | Python3 implementation of the approach ; Function to return the length of the largest sub - string divisible by 3 ; Base - case ; If the state has been solved before then return its value ; Marking the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE import sys NEW_LINE N = 100 NEW_LINE INT_MIN = - ( sys . maxsize - 1 ) NEW_LINE dp = np . zeros ( ( N , 3 ) ) ; NEW_LINE v = np . zeros ( ( N , 3 ) ) ; NEW_LINE def findLargestString ( s , i , r ) : NEW_LINE INDENT if ( i == len ( s ) ) : NEW_LINE INDENT if ( r == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT return INT_MIN ; NEW_LINE DEDENT DEDENT if ( v [ i ] [ r ] ) : NEW_LINE INDENT return dp [ i ] [ r ] ; NEW_LINE DEDENT v [ i ] [ r ] = 1 ; NEW_LINE dp [ i ] [ r ] = max ( 1 + findLargestString ( s , i + 1 , ( r * 2 + ( ord ( s [ i ] ) - ord ( '0' ) ) ) % 3 ) , findLargestString ( s , i + 1 , r ) ) ; NEW_LINE return dp [ i ] [ r ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "101" ; NEW_LINE print ( findLargestString ( s , 0 , 0 ) ) ; NEW_LINE DEDENT
Number of sub | Python3 implementation of th approach ; Function to return the number of sub - sequences divisible by 3 ; Base - cases ; If the state has been solved before then return its value ; Marking the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE N = 100 NEW_LINE dp = np . zeros ( ( N , 3 ) ) ; NEW_LINE v = np . zeros ( ( N , 3 ) ) ; NEW_LINE def findCnt ( s , i , r ) : NEW_LINE INDENT if ( i == len ( s ) ) : NEW_LINE INDENT if ( r == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( v [ i ] [ r ] ) : NEW_LINE INDENT return dp [ i ] [ r ] ; NEW_LINE DEDENT v [ i ] [ r ] = 1 ; NEW_LINE dp [ i ] [ r ] = findCnt ( s , i + 1 , ( r * 2 + ( ord ( s [ i ] ) - ord ( '0' ) ) ) % 3 ) + findCnt ( s , i + 1 , r ) ; NEW_LINE return dp [ i ] [ r ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "11" ; NEW_LINE print ( findCnt ( s , 0 , 0 ) - 1 ) ; NEW_LINE DEDENT
Remove minimum elements from ends of array so that sum decreases by at least K | O ( N ) | Function to return the count of minimum elements to be removed from the ends of the array such that the sum of the array decrease by at least K ; To store the final answer ; Maximum possible sum required ; Left point ; Right pointer ; Total current sum ; Two pointer loop ; If the sum fits ; Update the answer ; Update the total sum ; Increment the left pointer ; Driver code
def minCount ( arr , n , k ) : NEW_LINE INDENT ans = 0 ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT sum -= k ; NEW_LINE l = 0 ; NEW_LINE r = 0 ; NEW_LINE tot = 0 ; NEW_LINE while ( l < n ) : NEW_LINE INDENT if ( tot <= sum ) : NEW_LINE INDENT ans = max ( ans , r - l ) ; NEW_LINE if ( r == n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT tot += arr [ r ] ; NEW_LINE r += 1 NEW_LINE DEDENT else : NEW_LINE INDENT tot -= arr [ l ] ; NEW_LINE l += 1 NEW_LINE DEDENT DEDENT return ( n - ans ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 11 , 5 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 11 ; NEW_LINE print ( minCount ( arr , n , k ) ) ; NEW_LINE DEDENT
Minimum cost to merge all elements of List | Python3 implementation of the approach ; To store the states of DP ; Function to return the minimum merge cost ; Base case ; If the state has been solved before ; Marking the state as solved ; Reference to dp [ i ] [ j ] ; To store the sum of all the elements in the subarray arr [ i ... j ] ; Loop to iterate the recurrence ; Returning the solved value ; Driver code
import sys NEW_LINE N = 401 ; NEW_LINE dp = [ [ 0 for i in range ( N ) ] for j in range ( N ) ] ; NEW_LINE v = [ [ False for i in range ( N ) ] for j in range ( N ) ] ; NEW_LINE def minMergeCost ( i , j , arr ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( v [ i ] [ j ] ) : NEW_LINE INDENT return dp [ i ] [ j ] ; NEW_LINE DEDENT v [ i ] [ j ] = True ; NEW_LINE x = dp [ i ] [ j ] ; NEW_LINE x = sys . maxsize ; NEW_LINE tot = 0 ; NEW_LINE for k in range ( i , j + 1 ) : NEW_LINE INDENT tot += arr [ k ] ; NEW_LINE DEDENT for k in range ( i + 1 , j + 1 ) : NEW_LINE INDENT x = min ( x , tot + minMergeCost ( i , k - 1 , arr ) + minMergeCost ( k , j , arr ) ) ; NEW_LINE DEDENT return x ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 7 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( minMergeCost ( 0 , n - 1 , arr ) ) ; NEW_LINE DEDENT
Expected number of moves to reach the end of a board | Dynamic programming | Python3 implementation of the approach ; To store the states of dp ; To determine whether a state has been solved before ; Function to return the count ; Base cases ; If a state has been solved before it won 't be evaluated again ; Recurrence relation ; Driver code
maxSize = 50 NEW_LINE dp = [ 0 ] * maxSize NEW_LINE v = [ 0 ] * maxSize NEW_LINE def expectedSteps ( x ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( x <= 5 ) : NEW_LINE INDENT return 6 NEW_LINE DEDENT if ( v [ x ] ) : NEW_LINE INDENT return dp [ x ] NEW_LINE DEDENT v [ x ] = 1 NEW_LINE dp [ x ] = 1 + ( expectedSteps ( x - 1 ) + expectedSteps ( x - 2 ) + expectedSteps ( x - 3 ) + expectedSteps ( x - 4 ) + expectedSteps ( x - 5 ) + expectedSteps ( x - 6 ) ) / 6 NEW_LINE return dp [ x ] NEW_LINE DEDENT n = 10 NEW_LINE print ( round ( expectedSteps ( n - 1 ) , 5 ) ) NEW_LINE
Number of subsequences in a given binary string divisible by 2 | Function to return the count of the required subsequences ; To store the final answer ; Multiplier ; Loop to find the answer ; Condition to update the answer ; updating multiplier ; Driver code
def countSubSeq ( strr , lenn ) : NEW_LINE INDENT ans = 0 NEW_LINE mul = 1 NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( strr [ i ] == '0' ) : NEW_LINE INDENT ans += mul NEW_LINE DEDENT mul *= 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT strr = "10010" NEW_LINE lenn = len ( strr ) NEW_LINE print ( countSubSeq ( strr , lenn ) ) NEW_LINE
Knapsack with large Weights | Python3 implementation of the approach ; To store the states of DP ; Function to solve the recurrence relation ; Base cases ; Marking state as solved ; Recurrence relation ; Function to return the maximum weight ; Iterating through all possible values to find the the largest value that can be represented by the given weights ; Driver code
V_SUM_MAX = 1000 NEW_LINE N_MAX = 100 NEW_LINE W_MAX = 10000000 NEW_LINE dp = [ [ 0 for i in range ( N_MAX ) ] for i in range ( V_SUM_MAX + 1 ) ] NEW_LINE v = [ [ 0 for i in range ( N_MAX ) ] for i in range ( V_SUM_MAX + 1 ) ] NEW_LINE def solveDp ( r , i , w , val , n ) : NEW_LINE INDENT if ( r <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT return W_MAX NEW_LINE DEDENT if ( v [ r ] [ i ] ) : NEW_LINE INDENT return dp [ r ] [ i ] NEW_LINE DEDENT v [ r ] [ i ] = 1 NEW_LINE dp [ r ] [ i ] = min ( solveDp ( r , i + 1 , w , val , n ) , w [ i ] + solveDp ( r - val [ i ] , i + 1 , w , val , n ) ) NEW_LINE return dp [ r ] [ i ] NEW_LINE DEDENT def maxWeight ( w , val , n , c ) : NEW_LINE INDENT for i in range ( V_SUM_MAX , - 1 , - 1 ) : NEW_LINE INDENT if ( solveDp ( i , 0 , w , val , n ) <= c ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT w = [ 3 , 4 , 5 ] NEW_LINE val = [ 30 , 50 , 60 ] NEW_LINE n = len ( w ) NEW_LINE C = 8 NEW_LINE print ( maxWeight ( w , val , n , C ) ) NEW_LINE DEDENT
Sum of lengths of all paths possible in a given tree | Python3 implementation of the approach ; Number of vertices ; Adjacency list representation of the tree ; Array that stores the subtree size ; Array to mark all the vertices which are visited ; Utility function to create an edge between two vertices ; Add a to b 's list ; Add b to a 's list ; Function to calculate the subtree size ; Mark visited ; For every adjacent node ; If not already visited ; Recursive call for the child ; Function to calculate the contribution of each edge ; Mark current node as visited ; For every adjacent node ; If it is not already visisted ; Function to return the required sum ; First pass of the dfs ; Second pass ; Driver code
sz = 10 ** 5 NEW_LINE n = 5 NEW_LINE an = 0 NEW_LINE tree = [ [ ] for i in range ( sz ) ] NEW_LINE subtree_size = [ 0 ] * sz NEW_LINE vis = [ 0 ] * sz NEW_LINE def addEdge ( a , b ) : NEW_LINE INDENT tree [ a ] . append ( b ) NEW_LINE tree [ b ] . append ( a ) NEW_LINE DEDENT def dfs ( node ) : NEW_LINE INDENT leaf = True NEW_LINE vis [ node ] = 1 NEW_LINE for child in tree [ node ] : NEW_LINE INDENT if ( vis [ child ] == 0 ) : NEW_LINE INDENT leaf = False NEW_LINE dfs ( child ) NEW_LINE subtree_size [ node ] += subtree_size [ child ] NEW_LINE DEDENT DEDENT if leaf : NEW_LINE INDENT subtree_size [ node ] = 1 NEW_LINE DEDENT DEDENT def contribution ( node , ans ) : NEW_LINE INDENT global an NEW_LINE vis [ node ] = 1 NEW_LINE for child in tree [ node ] : NEW_LINE INDENT if ( vis [ child ] == 0 ) : NEW_LINE INDENT an += ( subtree_size [ child ] * ( n - subtree_size [ child ] ) ) NEW_LINE contribution ( child , ans ) NEW_LINE DEDENT DEDENT DEDENT def getSum ( ) : NEW_LINE INDENT for i in range ( sz ) : NEW_LINE INDENT vis [ i ] = 0 NEW_LINE DEDENT dfs ( 0 ) NEW_LINE ans = 0 NEW_LINE for i in range ( sz ) : NEW_LINE INDENT vis [ i ] = 0 NEW_LINE DEDENT contribution ( 0 , ans ) NEW_LINE return an NEW_LINE DEDENT n = 5 NEW_LINE addEdge ( 0 , 1 ) NEW_LINE addEdge ( 0 , 2 ) NEW_LINE addEdge ( 1 , 3 ) NEW_LINE addEdge ( 1 , 4 ) NEW_LINE print ( getSum ( ) ) NEW_LINE
Number of cells in a matrix that satisfy the given condition | Python3 implementation of the approach ; Function to return the number of cells in which mirror can be placed ; Update the row array where row [ i ] [ j ] will store whether the current row i contains all 1 s in the columns starting from j ; Update the column array where col [ i ] [ j ] will store whether the current column j contains all 1 s in the rows starting from i ; To store the required result ; For every cell except the last row and the last column ; If the current cell is not blocked and the light can travel from the next row and the next column then the current cell is valid ; For the last column ; For the last row , note that the last column is not taken into consideration as the bottom right element has already been considered in the last column previously ; Driver code
N = 3 NEW_LINE def numberOfCells ( mat ) : NEW_LINE INDENT row = [ [ False for i in range ( N ) ] for i in range ( N ) ] NEW_LINE col = [ [ False for i in range ( N ) ] for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT if j + 1 < N : NEW_LINE INDENT row [ i ] [ j ] = row [ i ] [ j + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT row [ i ] [ j ] = True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT row [ i ] [ j ] = False NEW_LINE DEDENT DEDENT DEDENT for j in range ( N ) : NEW_LINE INDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT if i + 1 < N : NEW_LINE INDENT col [ i ] [ j ] = col [ i + 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT col [ i ] [ j ] = True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT col [ i ] [ j ] = False NEW_LINE DEDENT DEDENT DEDENT cnt = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT for j in range ( N - 1 ) : NEW_LINE INDENT if ( row [ i ] [ j ] and col [ i ] [ j ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( col [ i ] [ N - 1 ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT for j in range ( N - 1 ) : NEW_LINE INDENT if ( row [ N - 1 ] [ j ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT mat = [ [ 0 , 1 , 1 ] , [ 0 , 1 , 1 ] , [ 0 , 1 , 1 ] ] NEW_LINE print ( numberOfCells ( mat ) ) NEW_LINE
Maximum sum subarray after altering the array | Python3 implementation of the approach ; Function to return the maximum subarray sum ; Function to reverse the subarray arr [ 0. . . i ] ; Function to return the maximum subarray sum after performing the given operation at most once ; To store the result ; When no operation is performed ; Find the maximum subarray sum after reversing the subarray arr [ 0. . . i ] for all possible values of i ; The complete array is reversed so that the subarray can be processed as arr [ 0. . . i ] instead of arr [ i ... N - 1 ] ; Driver code
import sys NEW_LINE def maxSumSubarray ( arr , size ) : NEW_LINE INDENT max_so_far = - sys . maxsize - 1 NEW_LINE max_ending_here = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT max_ending_here = max_ending_here + arr [ i ] NEW_LINE if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_here NEW_LINE DEDENT if ( max_ending_here < 0 ) : NEW_LINE INDENT max_ending_here = 0 NEW_LINE DEDENT DEDENT return max_so_far NEW_LINE DEDENT def getUpdatedArray ( arr , copy , i ) : NEW_LINE INDENT for j in range ( ( i // 2 ) + 1 ) : NEW_LINE INDENT copy [ j ] = arr [ i - j ] NEW_LINE copy [ i - j ] = arr [ j ] NEW_LINE DEDENT return NEW_LINE DEDENT def maxSum ( arr , size ) : NEW_LINE INDENT resSum = - sys . maxsize - 1 NEW_LINE resSum = max ( resSum , maxSumSubarray ( arr , size ) ) NEW_LINE copyArr = [ ] NEW_LINE copyArr = arr NEW_LINE for i in range ( 1 , size , 1 ) : NEW_LINE INDENT getUpdatedArray ( arr , copyArr , i ) NEW_LINE resSum = max ( resSum , maxSumSubarray ( copyArr , size ) ) NEW_LINE DEDENT arr = arr [ : : - 1 ] NEW_LINE copyArr = arr NEW_LINE for i in range ( 1 , size , 1 ) : NEW_LINE INDENT getUpdatedArray ( arr , copyArr , i ) NEW_LINE resSum = max ( resSum , maxSumSubarray ( copyArr , size ) ) NEW_LINE DEDENT resSum += 6 NEW_LINE return resSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 9 , 21 , 24 , 24 , - 51 , - 6 , 17 , - 42 , - 39 , 33 ] NEW_LINE size = len ( arr ) NEW_LINE print ( maxSum ( arr , size ) ) NEW_LINE DEDENT
Maximum possible GCD after replacing at most one element in the given array | Python3 implementation of the approach ; Function to return the maximum possible gcd after replacing a single element ; Prefix and Suffix arrays ; Single state dynamic programming relation for storing gcd of first i elements from the left in Prefix [ i ] ; Initializing Suffix array ; Single state dynamic programming relation for storing gcd of all the elements having index greater than or equal to i in Suffix [ i ] ; If first or last element of the array has to be replaced ; If any other element is replaced ; Return the maximized gcd ; Driver code
from math import gcd as __gcd NEW_LINE def MaxGCD ( a , n ) : NEW_LINE INDENT Prefix = [ 0 ] * ( n + 2 ) ; NEW_LINE Suffix = [ 0 ] * ( n + 2 ) ; NEW_LINE Prefix [ 1 ] = a [ 0 ] ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT Prefix [ i ] = __gcd ( Prefix [ i - 1 ] , a [ i - 1 ] ) ; NEW_LINE DEDENT Suffix [ n ] = a [ n - 1 ] ; NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT Suffix [ i ] = __gcd ( Suffix [ i + 1 ] , a [ i - 1 ] ) ; NEW_LINE DEDENT ans = max ( Suffix [ 2 ] , Prefix [ n - 1 ] ) ; NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT ans = max ( ans , __gcd ( Prefix [ i - 1 ] , Suffix [ i + 1 ] ) ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 6 , 7 , 8 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( MaxGCD ( a , n ) ) ; NEW_LINE DEDENT
Sum of products of all possible K size subsets of the given array | Function to return the sum of products of all the possible k size subsets ; Initialising all the values to 0 ; To store the answer for current value of k ; For k = 1 , the answer will simply be the sum of all the elements ; Filling the table in bottom up manner ; To store the elements of the current row so that we will be able to use this sum for subsequent values of k ; We will subtract previously computed value so as to get the sum of elements from j + 1 to n in the ( i - 1 ) th row ; Driver code
def sumOfProduct ( arr , n , k ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE cur_sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = arr [ i - 1 ] NEW_LINE cur_sum += arr [ i - 1 ] NEW_LINE DEDENT for i in range ( 2 , k + 1 ) : NEW_LINE INDENT temp_sum = 0 NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT cur_sum -= dp [ i - 1 ] [ j ] NEW_LINE dp [ i ] [ j ] = arr [ j - 1 ] * cur_sum NEW_LINE temp_sum += dp [ i ] [ j ] NEW_LINE DEDENT cur_sum = temp_sum NEW_LINE DEDENT return cur_sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE print ( sumOfProduct ( arr , n , k ) ) NEW_LINE DEDENT
Find the equal pairs of subsequence of S and subsequence of T | Python3 implementation of the approach ; Function to return the pairs of subsequences from S [ ] and subsequences from T [ ] such that both have the same content ; Create dp array ; Base values ; Base values ; Keep previous dp value ; If both elements are same ; Return the required answer ; Driver code
import numpy as np NEW_LINE mod = int ( 1e9 + 7 ) NEW_LINE def subsequence ( S , T , n , m ) : NEW_LINE INDENT dp = np . zeros ( ( n + 1 , m + 1 ) ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 1 ; NEW_LINE DEDENT for j in range ( m + 1 ) : NEW_LINE INDENT dp [ 0 ] [ j ] = 1 ; NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] - dp [ i - 1 ] [ j - 1 ] ; NEW_LINE if ( S [ i - 1 ] == T [ j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i - 1 ] [ j - 1 ] ; NEW_LINE DEDENT dp [ i ] [ j ] += mod ; NEW_LINE dp [ i ] [ j ] %= mod ; NEW_LINE DEDENT DEDENT return dp [ n ] [ m ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = [ 1 , 1 ] ; NEW_LINE n = len ( S ) ; NEW_LINE T = [ 1 , 1 ] ; NEW_LINE m = len ( T ) ; NEW_LINE print ( subsequence ( S , T , n , m ) ) ; NEW_LINE DEDENT
Maximum count of elements divisible on the left for any element | Function to return the maximum count of required elements ; For every element in the array starting from the second element ; Check all the elements on the left of current element which are divisible by the current element ; Driver code
def findMax ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( 0 , i ) : NEW_LINE INDENT if arr [ j ] % arr [ i ] == 0 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT res = max ( count , res ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 8 , 1 , 28 , 4 , 2 , 6 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMax ( arr , n ) ) NEW_LINE
Maximum count of elements divisible on the left for any element | Function to return the maximum count of required elements ; divisible [ i ] will store true if arr [ i ] is divisible by any element on its right ; To store the maximum required count ; For every element of the array ; If the current element is divisible by any element on its right ; Find the count of element on the left which are divisible by the current element ; If arr [ j ] is divisible then set divisible [ j ] to true ; Update the maximum required count ; Driver code
def findMax ( arr , n ) : NEW_LINE INDENT divisible = [ False ] * n ; NEW_LINE res = 0 ; NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( divisible [ i ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT cnt = 0 ; NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( ( arr [ j ] % arr [ i ] ) == 0 ) : NEW_LINE INDENT divisible [ j ] = True ; NEW_LINE cnt += 1 ; NEW_LINE DEDENT DEDENT res = max ( res , cnt ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 8 , 1 , 28 , 4 , 2 , 6 , 7 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findMax ( arr , n ) ) ; NEW_LINE DEDENT
Number of subsets with sum divisible by M | Set 2 | Python3 implementation of the approach ; To store the states of DP ; Function to find the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
maxN = 20 NEW_LINE maxM = 10 NEW_LINE dp = [ [ 0 for i in range ( maxN ) ] for i in range ( maxM ) ] NEW_LINE v = [ [ 0 for i in range ( maxN ) ] for i in range ( maxM ) ] NEW_LINE def findCnt ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( curr == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( v [ i ] [ curr ] ) : NEW_LINE INDENT return dp [ i ] [ curr ] NEW_LINE DEDENT v [ i ] [ curr ] = 1 NEW_LINE dp [ i ] [ curr ] = findCnt ( arr , i + 1 , curr , n , m ) + findCnt ( arr , i + 1 , ( curr + arr [ i ] ) % m , n , m ) NEW_LINE return dp [ i ] [ curr ] NEW_LINE DEDENT arr = [ 3 , 3 , 3 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE m = 6 NEW_LINE print ( findCnt ( arr , 0 , 0 , n , m ) - 1 ) NEW_LINE
Longest subsequence with a given OR value : Dynamic Programming Approach | Python3 implementation of the approach ; To store the states of DP ; Function to return the required length ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxM = 64 NEW_LINE dp = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE v = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE def findLen ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( curr == m ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT if ( v [ i ] [ curr ] ) : NEW_LINE INDENT return dp [ i ] [ curr ] ; NEW_LINE DEDENT v [ i ] [ curr ] = 1 ; NEW_LINE l = findLen ( arr , i + 1 , curr , n , m ) ; NEW_LINE r = findLen ( arr , i + 1 , curr arr [ i ] , n , m ) ; NEW_LINE dp [ i ] [ curr ] = l ; NEW_LINE if ( r != - 1 ) : NEW_LINE INDENT dp [ i ] [ curr ] = max ( dp [ i ] [ curr ] , r + 1 ) ; NEW_LINE DEDENT return dp [ i ] [ curr ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 7 , 2 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE m = 3 ; NEW_LINE ans = findLen ( arr , 0 , 0 , n , m ) ; NEW_LINE if ( ans == - 1 ) : NEW_LINE INDENT print ( 0 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) ; NEW_LINE DEDENT DEDENT
Longest subsequence with a given AND value | Python3 implementation of the approach ; To store the states of DP ; Function to return the required length ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxM = 256 NEW_LINE dp = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE v = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE def findLen ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( curr == m ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT if ( v [ i ] [ curr ] ) : NEW_LINE INDENT return dp [ i ] [ curr ] ; NEW_LINE DEDENT v [ i ] [ curr ] = 1 ; NEW_LINE l = findLen ( arr , i + 1 , curr , n , m ) ; NEW_LINE r = findLen ( arr , i + 1 , curr & arr [ i ] , n , m ) ; NEW_LINE dp [ i ] [ curr ] = l ; NEW_LINE if ( r != - 1 ) : NEW_LINE INDENT dp [ i ] [ curr ] = max ( dp [ i ] [ curr ] , r + 1 ) ; NEW_LINE DEDENT return dp [ i ] [ curr ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 7 , 2 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE m = 3 ; NEW_LINE ans = findLen ( arr , 0 , ( ( 1 << 8 ) - 1 ) , n , m ) ; NEW_LINE if ( ans == - 1 ) : NEW_LINE INDENT print ( 0 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) ; NEW_LINE DEDENT DEDENT
Longest subsequence whose sum is divisible by a given number | Python3 implementation of the approach ; To store the states of DP ; Function to return the length of the longest subsequence whose sum is divisible by m ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxM = 64 NEW_LINE dp = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE v = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE def findLen ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( not curr ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT if ( v [ i ] [ curr ] ) : NEW_LINE INDENT return dp [ i ] [ curr ] ; NEW_LINE DEDENT v [ i ] [ curr ] = 1 ; NEW_LINE l = findLen ( arr , i + 1 , curr , n , m ) ; NEW_LINE r = findLen ( arr , i + 1 , ( curr + arr [ i ] ) % m , n , m ) ; NEW_LINE dp [ i ] [ curr ] = l ; NEW_LINE if ( r != - 1 ) : NEW_LINE INDENT dp [ i ] [ curr ] = max ( dp [ i ] [ curr ] , r + 1 ) ; NEW_LINE DEDENT return dp [ i ] [ curr ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 2 , 2 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE m = 3 ; NEW_LINE print ( findLen ( arr , 0 , 0 , n , m ) ) ; NEW_LINE DEDENT
Count of subsets with sum equal to X | Python3 implementation of the approach ; To store the states of DP ; Function to return the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxSum = 50 NEW_LINE minSum = 50 NEW_LINE base = 50 NEW_LINE dp = np . zeros ( ( maxN , maxSum + minSum ) ) ; NEW_LINE v = np . zeros ( ( maxN , maxSum + minSum ) ) ; NEW_LINE def findCnt ( arr , i , required_sum , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( required_sum == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( v [ i ] [ required_sum + base ] ) : NEW_LINE INDENT return dp [ i ] [ required_sum + base ] ; NEW_LINE DEDENT v [ i ] [ required_sum + base ] = 1 ; NEW_LINE dp [ i ] [ required_sum + base ] = findCnt ( arr , i + 1 , required_sum , n ) + findCnt ( arr , i + 1 , required_sum - arr [ i ] , n ) ; NEW_LINE return dp [ i ] [ required_sum + base ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 3 , 3 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE x = 6 ; NEW_LINE print ( findCnt ( arr , 0 , x , n ) ) ; NEW_LINE DEDENT
Number of subsets with a given OR value | Python3 implementation of the approach ; To store states of DP ; Function to return the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxM = 64 NEW_LINE dp = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE v = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE def findCnt ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return ( curr == m ) ; NEW_LINE DEDENT if ( v [ i ] [ curr ] ) : NEW_LINE INDENT return dp [ i ] [ curr ] ; NEW_LINE DEDENT v [ i ] [ curr ] = 1 ; NEW_LINE dp [ i ] [ curr ] = findCnt ( arr , i + 1 , curr , n , m ) + findCnt ( arr , i + 1 , ( curr arr [ i ] ) , n , m ) ; NEW_LINE return dp [ i ] [ curr ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE m = 3 ; NEW_LINE print ( findCnt ( arr , 0 , 0 , n , m ) ) ; NEW_LINE DEDENT
Number of subsets with a given AND value | Python3 implementation of the approach ; To store states of DP ; Function to return the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxM = 64 NEW_LINE dp1 = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE v1 = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE def findCnt ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return ( curr == m ) ; NEW_LINE DEDENT if ( v1 [ i ] [ curr ] ) : NEW_LINE INDENT return dp1 [ i ] [ curr ] ; NEW_LINE DEDENT v1 [ i ] [ curr ] = 1 ; NEW_LINE dp1 [ i ] [ curr ] = findCnt ( arr , i + 1 , curr , n , m ) + findCnt ( arr , i + 1 , ( curr & arr [ i ] ) , n , m ) ; NEW_LINE return dp1 [ i ] [ curr ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 0 , 0 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE m = 0 ; NEW_LINE print ( findCnt ( arr , 0 , ( ( 1 << 6 ) - 1 ) , n , m ) ) ; NEW_LINE DEDENT
Count of integers obtained by replacing ? in the given string that give remainder 5 when divided by 13 | Python3 implementation of the approach ; Function to find the count of integers obtained by replacing ' ? ' in a given string such that formed integer gives remainder 5 when it is divided by 13 ; Initialise ; Place digit j at ? position ; Get the remainder ; Return the required answer ; Driver code
import numpy as np NEW_LINE MOD = ( int ) ( 1e9 + 7 ) NEW_LINE def modulo_13 ( s , n ) : NEW_LINE INDENT dp = np . zeros ( ( n + 1 , 13 ) ) ; NEW_LINE dp [ 0 ] [ 0 ] = 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT nxt = ord ( s [ i ] ) - ord ( '0' ) ; NEW_LINE if ( s [ i ] == ' ? ' ) : NEW_LINE INDENT nxt = j ; NEW_LINE DEDENT for k in range ( 13 ) : NEW_LINE INDENT rem = ( 10 * k + nxt ) % 13 ; NEW_LINE dp [ i + 1 ] [ rem ] += dp [ i ] [ k ] ; NEW_LINE dp [ i + 1 ] [ rem ] %= MOD ; NEW_LINE DEDENT if ( s [ i ] != ' ? ' ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT return int ( dp [ n ] [ 5 ] ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " ? 44" ; NEW_LINE n = len ( s ) ; NEW_LINE print ( modulo_13 ( s , n ) ) ; NEW_LINE DEDENT
Longest Increasing Subsequence using Longest Common Subsequence Algorithm | Function to return the size of the longest increasing subsequence ; Create an 2D array of integer for tabulation ; Take the second sequence as the sorted sequence of the given sequence ; Classical Dynamic Programming algorithm for Longest Common Subsequence ; Return the ans ; Driver code
def LISusingLCS ( seq ) : NEW_LINE INDENT n = len ( seq ) NEW_LINE L = [ [ 0 for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE sortedseq = sorted ( seq ) NEW_LINE for i in range ( n + 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 ( seq [ i - 1 ] == sortedseq [ j - 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 [ n ] [ n ] NEW_LINE DEDENT sequence = [ 12 , 34 , 1 , 5 , 40 , 80 ] NEW_LINE print ( LISusingLCS ( sequence ) ) NEW_LINE
Count of N | Function to return the count of n - digit numbers that satisfy the given conditions ; Base case ; If 0 wasn 't chosen previously ; If 0 wasn 't chosen previously ; Driver code
def count_numbers ( k , n , flag ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT if ( flag ) : NEW_LINE INDENT return ( k - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT return ( k - 1 ) * ( count_numbers ( k , n - 1 , 0 ) + count_numbers ( k , n - 1 , 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT return count_numbers ( k , n - 1 , 1 ) NEW_LINE DEDENT DEDENT n = 3 NEW_LINE k = 10 NEW_LINE print ( count_numbers ( k , n , True ) ) NEW_LINE
Count of N | Function to return the count of n - digit numbers that satisfy the given conditions ; DP array to store the pre - caluclated states ; Base cases ; i - digit numbers ending with 0 can be formed by concatenating 0 in the end of all the ( i - 1 ) - digit number ending at a non - zero digit ; i - digit numbers ending with non - zero can be formed by concatenating any non - zero digit in the end of all the ( i - 1 ) - digit number ending with any digit ; n - digit number ending with and ending with non - zero ; Driver code
def count_numbers ( k , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for i in range ( n + 1 ) ] NEW_LINE dp [ 1 ] [ 0 ] = 0 NEW_LINE dp [ 1 ] [ 1 ] = k - 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 1 ] NEW_LINE dp [ i ] [ 1 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] ) * ( k - 1 ) NEW_LINE DEDENT return dp [ n ] [ 0 ] + dp [ n ] [ 1 ] NEW_LINE DEDENT k = 10 NEW_LINE n = 3 NEW_LINE print ( count_numbers ( k , n ) ) NEW_LINE
Divide an array into K subarray with the given condition | Function to divide an array into k parts such that the summ of difference of every element with the maximum element of that part is minimum ; Dp to store the values ; Fill up the dp table ; Intitilize maximum value ; Max element and the summ ; Run a loop from i to n ; Find the maximum number from i to l and the summ from i to l ; Find the summ of difference of every element with the maximum element ; If the array can be divided ; Returns the minimum summ in K parts ; Driver code
def divideArray ( arr , n , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 500 ) ] for i in range ( 500 ) ] NEW_LINE k -= 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( 0 , k + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = 10 ** 9 NEW_LINE max_ = - 1 NEW_LINE summ = 0 NEW_LINE for l in range ( i , n ) : NEW_LINE INDENT max_ = max ( max_ , arr [ l ] ) NEW_LINE summ += arr [ l ] NEW_LINE diff = ( l - i + 1 ) * max_ - summ NEW_LINE if ( j > 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i ] [ j ] , diff + dp [ l + 1 ] [ j - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = diff NEW_LINE DEDENT DEDENT DEDENT DEDENT return dp [ 0 ] [ k ] NEW_LINE DEDENT arr = [ 2 , 9 , 5 , 4 , 8 , 3 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE print ( divideArray ( arr , n , k ) ) NEW_LINE
Count of subsets not containing adjacent elements | Function to return the count of possible subsets ; Total possible subsets of n sized array is ( 2 ^ n - 1 ) ; To store the required count of subsets ; Run from i 000. .0 to 111. .1 ; If current subset has consecutive elements from the array ; Driver code
def cntSubsets ( arr , n ) : NEW_LINE INDENT max = pow ( 2 , n ) NEW_LINE result = 0 NEW_LINE for i in range ( max ) : NEW_LINE INDENT counter = i NEW_LINE if ( counter & ( counter >> 1 ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT result += 1 NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 3 , 5 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( cntSubsets ( arr , n ) ) NEW_LINE
Count of subsets not containing adjacent elements | Function to return the count of possible subsets ; If previous element was 0 then 0 as well as 1 can be appended ; If previous element was 1 then only 0 can be appended ; Store the count of all possible subsets ; Driver code
def cntSubsets ( arr , n ) : NEW_LINE INDENT a = [ 0 ] * n NEW_LINE b = [ 0 ] * n ; NEW_LINE a [ 0 ] = b [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT a [ i ] = a [ i - 1 ] + b [ i - 1 ] ; NEW_LINE b [ i ] = a [ i - 1 ] ; NEW_LINE DEDENT result = a [ n - 1 ] + b [ n - 1 ] ; NEW_LINE return result ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 5 , 7 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( cntSubsets ( arr , n ) ) ; NEW_LINE DEDENT
Maximum perimeter of a square in a 2D grid | Function to calculate the perfix sum of the rows and the columns of the given matrix ; Number of rows and cols ; First column of the row prefix array ; Update the prefix sum for the rows ; First row of the column prefix array ; Update the prefix sum for the columns ; Function to return the perimeter of the square having top - left corner at ( i , j ) and size k ; i and j represent the top left corner of the square and k is the size ; Get the upper row sum ; Get the left column sum ; At the distance of k in both direction ; The perimeter will be sum of all the values ; Since all the corners are included twice , they need to be subtract from the sum ; Function to return the maximum perimeter of a square in the given matrix ; Number of rows and cols ; Function call to calculate the prefix sum of rows and cols ; To store the maximum perimeter ; Nested loops to choose the top - left corner of the square ; Loop for the size of the square ; Get the perimeter of the current square ; Update the maximum perimeter so far ; Driver code
def perfix_calculate ( A , row , col ) : NEW_LINE INDENT n = len ( A ) NEW_LINE m = len ( A [ 0 ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT row [ i ] [ 0 ] = A [ i ] [ 0 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , m ) : NEW_LINE INDENT row [ i ] [ j ] = row [ i ] [ j - 1 ] + A [ i ] [ j ] NEW_LINE DEDENT DEDENT for i in range ( m ) : NEW_LINE INDENT col [ 0 ] [ i ] = A [ 0 ] [ i ] NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT for j in range ( 1 , m ) : NEW_LINE INDENT col [ j ] [ i ] = A [ j ] [ i ] + col [ j - 1 ] [ i ] NEW_LINE DEDENT DEDENT DEDENT def perimeter ( i , j , k , row , col , A ) : NEW_LINE INDENT row_s , col_s = 0 , 0 NEW_LINE if ( j == 0 ) : NEW_LINE INDENT row_s = 0 NEW_LINE DEDENT else : NEW_LINE INDENT row_s = row [ i ] [ j - 1 ] NEW_LINE DEDENT if ( i == 0 ) : NEW_LINE INDENT col_s = 0 NEW_LINE DEDENT else : NEW_LINE INDENT col_s = col [ i - 1 ] [ j ] NEW_LINE DEDENT upper_row = row [ i ] [ j + k ] - row_s NEW_LINE left_col = col [ i + k ] [ j ] - col_s NEW_LINE if ( j == 0 ) : NEW_LINE INDENT row_s = 0 NEW_LINE DEDENT else : NEW_LINE INDENT row_s = row [ i + k ] [ j - 1 ] NEW_LINE DEDENT if ( i == 0 ) : NEW_LINE INDENT col_s = 0 NEW_LINE DEDENT else : NEW_LINE INDENT col_s = col [ i - 1 ] [ j + k ] NEW_LINE DEDENT lower_row = row [ i + k ] [ j + k ] - row_s NEW_LINE right_col = col [ i + k ] [ j + k ] - col_s NEW_LINE sum = upper_row + lower_row + left_col + right_col NEW_LINE sum -= ( A [ i ] [ j ] + A [ i + k ] [ j ] + \ A [ i ] [ j + k ] + A [ i + k ] [ j + k ] ) NEW_LINE return sum NEW_LINE DEDENT def maxPerimeter ( A ) : NEW_LINE INDENT n = len ( A ) NEW_LINE m = len ( A [ 0 ] ) NEW_LINE row = [ [ 0 for i in range ( m ) ] for i in range ( n ) ] NEW_LINE col = [ [ 0 for i in range ( m ) ] for i in range ( n ) ] NEW_LINE perfix_calculate ( A , row , col ) NEW_LINE maxPer = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT for k in range ( min ( n - i , m - j ) ) : NEW_LINE INDENT perimtr = perimeter ( i , j , k , row , col , A ) NEW_LINE maxPer = max ( maxPer , perimtr ) NEW_LINE DEDENT DEDENT DEDENT return maxPer NEW_LINE DEDENT A = [ [ 1 , 1 , 0 ] , [ 1 , 1 , 1 ] , [ 0 , 1 , 1 ] ] NEW_LINE print ( maxPerimeter ( A ) ) NEW_LINE
Optimal Strategy for a Game | Set 3 | Calculates the maximum score possible for P1 If only the bags from beg to ed were available ; Length of the game ; Which turn is being played ; Base case i . e last turn ; if it is P1 's turn ; if P2 's turn ; Player picks money from the left end ; Player picks money from the right end ; If it is player 1 's turn then current picked score added to his total. choose maximum of the two scores as P1 tries to maximize his score. ; If player 2 ' s ▁ turn ▁ don ' t add current picked bag score to total . choose minimum of the two scores as P2 tries to minimize P1 's score. ; Input array ; Function Calling
def maxScore ( money , beg , ed ) : NEW_LINE INDENT totalTurns = len ( money ) NEW_LINE turnsTillNow = beg + ( ( totalTurns - 1 ) - ed ) NEW_LINE if ( beg == ed ) : NEW_LINE INDENT if ( turnsTillNow % 2 == 0 ) : NEW_LINE INDENT return [ money [ beg ] , " L " ] NEW_LINE DEDENT else : NEW_LINE INDENT return [ 0 , " L " ] NEW_LINE DEDENT DEDENT scoreOne = maxScore ( money , beg + 1 , ed ) NEW_LINE scoreTwo = maxScore ( money , beg , ed - 1 ) NEW_LINE if ( turnsTillNow % 2 == 0 ) : NEW_LINE INDENT if ( money [ beg ] + scoreOne [ 0 ] > money [ ed ] + scoreTwo [ 0 ] ) : NEW_LINE INDENT return [ money [ beg ] + scoreOne [ 0 ] , " L " + scoreOne [ 1 ] ] NEW_LINE DEDENT else : NEW_LINE INDENT return [ money [ ed ] + scoreTwo [ 0 ] , " R " + scoreTwo [ 1 ] ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( scoreOne [ 0 ] < scoreTwo [ 0 ] ) : NEW_LINE INDENT return [ scoreOne [ 0 ] , " L " + scoreOne [ 1 ] ] NEW_LINE DEDENT else : NEW_LINE INDENT return [ scoreTwo [ 0 ] , " R " + scoreTwo [ 1 ] ] NEW_LINE DEDENT DEDENT DEDENT ar = [ 10 , 80 , 90 , 30 ] NEW_LINE arraySize = len ( ar ) NEW_LINE bags = ar NEW_LINE ans = maxScore ( bags , 0 , arraySize - 1 ) NEW_LINE print ( ans [ 0 ] , ans [ 1 ] ) NEW_LINE
Minimum number of Fibonacci jumps to reach end | A Dynamic Programming based Python3 program to find minimum number of jumps to reach Destination ; Function that returns the min number of jump to reach the destination ; We consider only those Fibonacci numbers which are less than n , where we can consider fib [ 30 ] to be the upper bound as this will cross 10 ^ 5 ; DP [ i ] will be storing the minimum number of jumps required for the position i . So DP [ N + 1 ] will have the result we consider 0 as source and N + 1 as the destination ; Base case ( Steps to reach source is ) ; Initialize all table values as Infinite ; Go through each positions till destination . ; Calculate the minimum of that position if all the Fibonacci numbers are considered ; If the position is safe or the position is the destination then only we calculate the minimum otherwise the cost is MAX as default ; - 1 denotes if there is no path possible ; Driver Code
MAX = 1e9 NEW_LINE def minJumps ( arr , N ) : NEW_LINE INDENT fib = [ 0 for i in range ( 30 ) ] NEW_LINE fib [ 0 ] = 0 NEW_LINE fib [ 1 ] = 1 NEW_LINE for i in range ( 2 , 30 ) : NEW_LINE INDENT fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] NEW_LINE DEDENT DP = [ 0 for i in range ( N + 2 ) ] NEW_LINE DP [ 0 ] = 0 NEW_LINE for i in range ( 1 , N + 2 ) : NEW_LINE INDENT DP [ i ] = MAX NEW_LINE DEDENT for i in range ( 1 , N + 2 ) : NEW_LINE INDENT for j in range ( 1 , 30 ) : NEW_LINE INDENT if ( ( arr [ i - 1 ] == 1 or i == N + 1 ) and i - fib [ j ] >= 0 ) : NEW_LINE INDENT DP [ i ] = min ( DP [ i ] , 1 + DP [ i - fib [ j ] ] ) NEW_LINE DEDENT DEDENT DEDENT if ( DP [ N + 1 ] != MAX ) : NEW_LINE INDENT return DP [ N + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT arr = [ 0 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minJumps ( arr , n - 1 ) ) NEW_LINE
Subsequence X of length K such that gcd ( X [ 0 ] , X [ 1 ] ) + ( X [ 2 ] , X [ 3 ] ) + ... is maximized | Python3 program to find the sum of the addition of all possible subsets ; Recursive function to find the maximum value of the given recurrence ; If we get K elements ; If we have reached the end and K elements are not there ; If the state has been visited ; Iterate for every element as the next possible element and take the element which gives the maximum answer ; If this element is the first element in the individual pair in the subsequence then simply recurrence with the last element as i - th index ; If this element is the second element in the individual pair , the find gcd with the previous element and add to the answer and recur for the next element ; Driver Code
from math import gcd as __gcd NEW_LINE MAX = 100 NEW_LINE def recur ( ind , cnt , last , a , n , k , dp ) : NEW_LINE INDENT if ( cnt == k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( ind == n ) : NEW_LINE INDENT return - 10 ** 9 NEW_LINE DEDENT if ( dp [ ind ] [ cnt ] != - 1 ) : NEW_LINE INDENT return dp [ ind ] [ cnt ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( ind , n ) : NEW_LINE INDENT if ( cnt % 2 == 0 ) : NEW_LINE INDENT ans = max ( ans , recur ( i + 1 , cnt + 1 , i , a , n , k , dp ) ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = max ( ans , __gcd ( a [ last ] , a [ i ] ) + recur ( i + 1 , cnt + 1 , 0 , a , n , k , dp ) ) NEW_LINE DEDENT DEDENT dp [ ind ] [ cnt ] = ans NEW_LINE return ans NEW_LINE DEDENT a = [ 4 , 5 , 3 , 7 , 8 , 10 , 9 , 8 ] NEW_LINE n = len ( a ) NEW_LINE k = 4 ; NEW_LINE dp = [ [ - 1 for i in range ( MAX ) ] for i in range ( n ) ] NEW_LINE print ( recur ( 0 , 0 , 0 , a , n , k , dp ) ) NEW_LINE
Maximum number of given operations to remove the entire string | Function to return the maximum number of given operations required to remove the given entirely ; If length of the is zero ; Single operation can delete the entire string ; To store the prefix of the string which is to be deleted ; Prefix s [ 0. . i ] ; To store the subs [ i + 1. . .2 * i + 1 ] ; If the prefix s [ 0. . . i ] can be deleted ; 1 operation to remove the current prefix and then recursively find the count of operations for the subs [ i + 1. . . n - 1 ] ; Entire has to be deleted ; Driver code
def find ( s ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT c = 1 NEW_LINE d = " " NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT d += s [ i ] NEW_LINE s2 = s [ i + 1 : i + 1 + len ( d ) ] NEW_LINE if ( s2 == d ) : NEW_LINE INDENT c = 1 + find ( s [ i + 1 : ] ) NEW_LINE break NEW_LINE DEDENT DEDENT return c NEW_LINE DEDENT s = " abababab " NEW_LINE print ( find ( s ) ) NEW_LINE
Sum of the distances from every node to all other nodes is maximum | Python3 program to implement the above approach ; Function to add an edge to the tree ; Function to run DFS and calculate the height of the subtree below it ; Initially initialize with 1 ; Traverse for all nodes connected to node ; If node is not parent then recall dfs ; Add the size of the subtree beneath it ; Function to assign weights to edges to maximize the final sum ; Initialize it which stores the height of the subtree beneath it ; Call the DFS function to ; Sort the given array ; Stores the number of times an edge is part of a path ; Iterate for all edges and find the number of nodes on the left and on the right ; Node 1 ; Node 2 ; If the number of nodes below is less then the other will be n - dp [ node ] ; Second condition ; Sort the number of times an edges occurs in the path ; Find the summation of all those paths and return ; Driver code ; Add an edge 1 - 2 in the tree ; Add an edge 2 - 3 in the tree ; Add an edge 3 - 4 in the tree ; Add an edge 3 - 5 in the tree ; Array which gives the edges weight to be assigned
edges = [ [ ] for i in range ( 100 ) ] NEW_LINE tree = [ [ ] for i in range ( 100 ) ] NEW_LINE def addEdge ( x , y ) : NEW_LINE INDENT edges . append ( [ x , y ] ) NEW_LINE tree [ x ] . append ( y ) NEW_LINE tree [ y ] . append ( x ) NEW_LINE DEDENT def dfs ( node , parent , dp ) : NEW_LINE INDENT dp [ node ] = 1 NEW_LINE for it in tree [ node ] : NEW_LINE INDENT if ( it != parent ) : NEW_LINE INDENT dfs ( it , node , dp ) NEW_LINE dp [ node ] += dp [ it ] NEW_LINE DEDENT DEDENT DEDENT def maximizeSum ( a , n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE dfs ( 1 , 0 , dp ) NEW_LINE a = sorted ( a [ : - 1 ] ) NEW_LINE ans = [ ] NEW_LINE for it in edges : NEW_LINE INDENT if len ( it ) > 0 : NEW_LINE INDENT x = it [ 0 ] NEW_LINE y = it [ 1 ] NEW_LINE if ( dp [ x ] < dp [ y ] ) : NEW_LINE INDENT fi = dp [ x ] NEW_LINE sec = n - dp [ x ] NEW_LINE ans . append ( fi * sec ) NEW_LINE DEDENT else : NEW_LINE INDENT fi = dp [ y ] NEW_LINE sec = n - dp [ y ] NEW_LINE ans . append ( fi * sec ) NEW_LINE DEDENT DEDENT DEDENT ans = sorted ( ans ) NEW_LINE res = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT res += ans [ i ] * a [ i ] NEW_LINE DEDENT return res NEW_LINE DEDENT n = 5 NEW_LINE addEdge ( 1 , 2 ) NEW_LINE addEdge ( 1 , 3 ) NEW_LINE addEdge ( 3 , 4 ) NEW_LINE addEdge ( 3 , 5 ) NEW_LINE a = [ 6 , 3 , 1 , 9 , 3 ] NEW_LINE print ( maximizeSum ( a , n ) ) NEW_LINE
Divide the array in K segments such that the sum of minimums is maximized | Python 3 program to find the sum of the minimum of all the segments ; Function to maximize the sum of the minimums ; If k segments have been divided ; If we are at the end ; If we donot reach the end then return a negative number that cannot be the sum ; If at the end but k segments are not formed ; If the state has been visited already ; If the state has not been visited ; Get the minimum element in the segment ; Iterate and try to break at every index and create a segment ; Find the minimum element in the segment ; Find the sum of all the segments trying all the possible combinations ; Return the answer by memoizing it ; Driver Code ; Initialize dp array with - 1
MAX = 10 NEW_LINE def maximizeSum ( a , n , ind , k , dp ) : NEW_LINE INDENT if ( k == 0 ) : NEW_LINE INDENT if ( ind == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1e9 NEW_LINE DEDENT DEDENT elif ( ind == n ) : NEW_LINE INDENT return - 1e9 NEW_LINE DEDENT elif ( dp [ ind ] [ k ] != - 1 ) : NEW_LINE INDENT return dp [ ind ] [ k ] NEW_LINE DEDENT else : NEW_LINE INDENT ans = 0 NEW_LINE mini = a [ ind ] NEW_LINE for i in range ( ind , n , 1 ) : NEW_LINE INDENT mini = min ( mini , a [ i ] ) NEW_LINE ans = max ( ans , maximizeSum ( \ a , n , i + 1 , k - 1 , dp ) + mini ) NEW_LINE DEDENT dp [ ind ] [ k ] = ans NEW_LINE return ans NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 5 , 7 , 4 , 2 , 1 , 6 ] NEW_LINE k = 3 NEW_LINE n = len ( a ) NEW_LINE dp = [ [ - 1 for i in range ( MAX ) ] \ for j in range ( MAX ) ] NEW_LINE print ( maximizeSum ( a , n , 0 , k , dp ) ) NEW_LINE DEDENT
Optimally accommodate 0 s and 1 s from a Binary String into K buckets | Function to find the minimum required sum using dynamic programming ; If both start and bucket reached end then return 0 else that arrangement is not possible so return INT_MAX ; Corner case ; If state if already calculated then return its answer ; Start filling zeroes and ones which to be accommodated in jth bucket then ans for current arrangement will be ones * zeroes + recur ( i + 1 , bucket + 1 ) ; If this arrangement is not possible then don 't calculate further ; Function to initialize the dp and call solveUtil ( ) method to get the answer ; Start with 0 - th index and 1 bucket ; Driver code ; K buckets
def solveUtil ( start , bucket , str1 , K , dp ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE if ( start == N ) : NEW_LINE INDENT if ( bucket == K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 10 ** 9 NEW_LINE DEDENT if ( bucket == K ) : NEW_LINE INDENT return 10 ** 9 NEW_LINE DEDENT if ( dp [ start ] [ bucket ] != - 1 ) : NEW_LINE INDENT return dp [ start ] [ bucket ] NEW_LINE DEDENT zeroes = 0 NEW_LINE ones = 0 NEW_LINE ans = 10 ** 9 NEW_LINE for i in range ( start , N ) : NEW_LINE INDENT if ( str1 [ i ] == '1' ) : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zeroes += 1 NEW_LINE DEDENT if ( ones * zeroes > ans ) : NEW_LINE INDENT break NEW_LINE DEDENT temp = solveUtil ( i + 1 , bucket + 1 , str1 , K , dp ) NEW_LINE if ( temp != 10 ** 9 ) : NEW_LINE INDENT ans = min ( ans , temp + ( ones * zeroes ) ) NEW_LINE DEDENT DEDENT dp [ start ] [ bucket ] = ans NEW_LINE return ans NEW_LINE DEDENT def solve ( str1 , K ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE dp = [ [ - 1 for i in range ( K ) ] for i in range ( N ) ] NEW_LINE ans = solveUtil ( 0 , 0 , str1 , K , dp ) NEW_LINE if ans == 10 ** 9 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ans NEW_LINE DEDENT DEDENT s = "0101" NEW_LINE S = [ i for i in s ] NEW_LINE K = 2 NEW_LINE print ( solve ( S , K ) ) NEW_LINE
Probability of getting more heads than tails when N biased coins are tossed | Python3 implementation of the above approach ; Function to return the probability when number of heads is greater than the number of tails ; Declaring the DP table ; Base case ; Iterating for every coin ; j represents the numbers of heads ; If number of heads is equal to zero there there is only one possibility ; When the number of heads is greater than ( n + 1 ) / 2 it means that heads are greater than tails as no of tails + no of heads is equal to n for any permutation of heads and tails ; Driver Code ; 1 based indexing ; Number of coins ; Function call
import numpy as np NEW_LINE def Probability ( p , n ) : NEW_LINE INDENT dp = np . zeros ( ( n + 1 , n + 1 ) ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = 0.0 NEW_LINE DEDENT DEDENT dp [ 0 ] [ 0 ] = 1.0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] * ( 1.0 - p [ i ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i - 1 ] [ j ] * ( 1.0 - p [ i ] ) + dp [ i - 1 ] [ j - 1 ] * p [ i ] ) ; NEW_LINE DEDENT DEDENT DEDENT ans = 0.0 ; NEW_LINE for i in range ( ( n + 1 ) // 2 , n + 1 ) : NEW_LINE INDENT ans += dp [ n ] [ i ] ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p = [ 0.0 , 0.3 , 0.4 , 0.7 ] ; NEW_LINE n = len ( p ) - 1 ; NEW_LINE print ( Probability ( p , n ) ) ; NEW_LINE DEDENT
Number of ways to get a given sum with n number of m | Python3 function to calculate the number of ways to achieve sum x in n no of throws ; Function to calculate recursively the number of ways to get sum in given throws and [ 1. . m ] values ; Base condition 1 ; Base condition 2 ; If value already calculated dont move into re - computation ; Recursively moving for sum - i in throws - 1 no of throws left ; Inserting present values in dp ; Driver function
import numpy as np NEW_LINE mod = 1000000007 ; NEW_LINE dp = np . zeros ( ( 55 , 55 ) ) ; NEW_LINE def NoofWays ( face , throws , sum ) : NEW_LINE INDENT if ( sum == 0 and throws == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( sum < 0 or throws == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ throws ] [ sum ] != - 1 ) : NEW_LINE INDENT return dp [ throws ] [ sum ] ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for i in range ( 1 , face + 1 ) : NEW_LINE INDENT ans += NoofWays ( face , throws - 1 , sum - i ) ; NEW_LINE DEDENT dp [ throws ] [ sum ] = ans ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT faces = 6 ; throws = 3 ; sum = 12 ; NEW_LINE for i in range ( 55 ) : NEW_LINE INDENT for j in range ( 55 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT print ( NoofWays ( faces , throws , sum ) ) ; NEW_LINE DEDENT
Longest sub | Function to return the length of the longest required sub - sequence ; Sort the array ; To store the resultant length ; If array contains only one element then it divides itself ; Every element divides itself ; Count for all numbers which are lesser than a [ i ] ; If a [ i ] % a [ j ] then update the maximum subsequence length , dp [ i ] = max ( dp [ i ] , 1 + dp [ j ] ) where j is in the range [ 0 , i - 1 ] ; If array contains only one element then i = j which doesn 't satisfy the condition ; Driver code
def find ( n , a ) : NEW_LINE INDENT a . sort ( ) ; NEW_LINE res = 1 ; NEW_LINE dp = [ 0 ] * n ; NEW_LINE dp [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] = 1 ; NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( a [ i ] % a [ j ] == 0 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , 1 + dp [ j ] ) ; NEW_LINE DEDENT DEDENT res = max ( res , dp [ i ] ) ; NEW_LINE DEDENT if ( res == 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return res ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 4 , 6 , 1 , 3 , 11 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( find ( n , a ) ) ; NEW_LINE DEDENT
Maximize the happiness of the groups on the Trip | Python3 implementation of the approach ; Function to return the maximized happiness ; Two arrays similar to 0 1 knapsack problem ; To store the happiness of the current group ; Current person is a child ; Woman ; Man ; Old person ; Group 's happiness is the sum of happiness of the people in the group multiplied by the number of people ; Solution using 0 1 knapsack ; Driver code ; Number of seats ; Groups
import numpy as np NEW_LINE def MaxHappiness ( A , N , v ) : NEW_LINE INDENT val = [ 0 ] * N ; wt = [ 0 ] * N ; c = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT string = v [ i ] ; NEW_LINE c = 0 ; NEW_LINE for j in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ j ] == ' c ' ) : NEW_LINE INDENT c += 4 ; NEW_LINE DEDENT elif ( string [ j ] == ' w ' ) : NEW_LINE INDENT c += 3 ; NEW_LINE DEDENT elif ( string [ j ] == ' m ' ) : NEW_LINE INDENT c += 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT c += 1 ; NEW_LINE DEDENT DEDENT c *= len ( string ) ; NEW_LINE val [ i ] = c ; NEW_LINE wt [ i ] = len ( string ) ; NEW_LINE DEDENT k = np . zeros ( ( N + 1 , A + 1 ) ) NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT for w in range ( A + 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 return k [ N ] [ A ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 5 ; NEW_LINE v = [ " mmo " , " oo " , " cmw " , " cc " , " c " ] ; NEW_LINE N = len ( v ) ; NEW_LINE print ( MaxHappiness ( A , N , v ) ) ; NEW_LINE DEDENT
0 | Python3 implementation of the approach ; To store states of DP ; To check if a state has been solved ; Function to compute the states ; Base case ; Check if a state has been solved ; Setting a state as solved ; Returning the solved state ; Function to pre - compute the states dp [ 0 ] [ 0 ] , dp [ 0 ] [ 1 ] , . . , dp [ 0 ] [ C_MAX ] ; Function to answer a query in O ( 1 ) ; Driver code ; Performing required pre - computation ; Perform queries
import numpy as np NEW_LINE import sys NEW_LINE C_MAX = 30 NEW_LINE max_arr_len = 10 NEW_LINE dp = np . zeros ( ( max_arr_len , C_MAX + 1 ) ) ; NEW_LINE v = np . zeros ( ( max_arr_len , C_MAX + 1 ) ) ; NEW_LINE INT_MIN = - ( sys . maxsize ) + 1 NEW_LINE def findMax ( i , r , w , n ) : NEW_LINE INDENT if ( r < 0 ) : NEW_LINE INDENT return INT_MIN ; NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( v [ i ] [ r ] ) : NEW_LINE INDENT return dp [ i ] [ r ] ; NEW_LINE DEDENT v [ i ] [ r ] = 1 ; NEW_LINE dp [ i ] [ r ] = max ( w [ i ] + findMax ( i + 1 , r - w [ i ] , w , n ) , findMax ( i + 1 , r , w , n ) ) ; NEW_LINE return dp [ i ] [ r ] ; NEW_LINE DEDENT def preCompute ( w , n ) : NEW_LINE INDENT for i in range ( C_MAX , - 1 , - 1 ) : NEW_LINE INDENT findMax ( 0 , i , w , n ) ; NEW_LINE DEDENT DEDENT def ansQuery ( w ) : NEW_LINE INDENT return dp [ 0 ] [ w ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT w = [ 3 , 8 , 9 ] ; NEW_LINE n = len ( w ) NEW_LINE preCompute ( w , n ) ; NEW_LINE queries = [ 11 , 10 , 4 ] ; NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( ansQuery ( queries [ i ] ) ) ; NEW_LINE DEDENT DEDENT
Maximise array sum after taking non | Python3 implementation of the approach ; To store the states of dp ; To check if a given state has been solved ; To store the prefix - sum ; Function to fill the prefix_sum [ ] with the prefix sum of the given array ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Required recurrence relation ; Returning the value ; Driver code ; Finding prefix - sum ; Finding the maximum possible sum
maxLen = 10 NEW_LINE dp = [ 0 ] * maxLen ; NEW_LINE v = [ 0 ] * maxLen ; NEW_LINE prefix_sum = [ 0 ] * maxLen ; NEW_LINE def findPrefixSum ( arr , n ) : NEW_LINE INDENT prefix_sum [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix_sum [ i ] = arr [ i ] + prefix_sum [ i - 1 ] ; NEW_LINE DEDENT DEDENT def maxSum ( arr , i , n , k ) : NEW_LINE INDENT if ( i + k > n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( v [ i ] ) : NEW_LINE INDENT return dp [ i ] ; NEW_LINE DEDENT v [ i ] = 1 ; NEW_LINE if ( i == 0 ) : NEW_LINE INDENT x = prefix_sum [ k - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT x = prefix_sum [ i + k - 1 ] - prefix_sum [ i - 1 ] ; NEW_LINE DEDENT dp [ i ] = max ( maxSum ( arr , i + 1 , n , k ) , x + maxSum ( arr , i + k + 1 , n , k ) ) ; NEW_LINE return dp [ i ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 7 , 6 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 1 ; NEW_LINE findPrefixSum ( arr , n ) ; NEW_LINE print ( maxSum ( arr , 0 , n , k ) ) ; NEW_LINE DEDENT
Find maximum path sum in a 2D matrix when exactly two left moves are allowed | Python3 program to find maximum path sum in a 2D matrix when exactly two left moves are allowed ; Function to return the maximum path sum ; Copy last column i . e . starting and ending columns in another array ; Calculate suffix sum in each row ; Select the path we are going to follow ; Driver Code
import numpy as np NEW_LINE N = 3 NEW_LINE M = 3 NEW_LINE def findMaxSum ( arr ) : NEW_LINE INDENT sum = 0 ; NEW_LINE b = np . zeros ( ( N , M ) ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT b [ i ] [ M - 1 ] = arr [ i ] [ M - 1 ] ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M - 2 , - 1 , - 1 ) : NEW_LINE INDENT b [ i ] [ j ] = arr [ i ] [ j ] + b [ i ] [ j + 1 ] ; NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT sum = max ( sum , b [ i ] [ j ] + b [ i - 1 ] [ j ] ) ; NEW_LINE b [ i ] [ j ] = max ( b [ i ] [ j ] , b [ i - 1 ] [ j ] + arr [ i ] [ j ] ) ; NEW_LINE DEDENT DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 3 , 7 , 4 ] , [ 1 , 9 , 6 ] , [ 1 , 7 , 7 ] ] ; NEW_LINE print ( findMaxSum ( arr ) ) ; NEW_LINE DEDENT
Queries to check if string B exists as substring in string A | Python3 implementation of the approach ; Function to return the modular inverse using Fermat 's little theorem ; Function to generate hash ; To store prefix - sum of rolling hash ; Multiplier for different values of i ; Generating hash value for string b ; Generating prefix - sum of hash of a ; Function that returns true if the required sub - string in a is equal to b ; To store hash of required sub - string of A ; If i = 0 then requires hash value ; Required hash if i != 0 ; Comparing hash with hash of B ; Driver Code ; Generating hash ; Queries ; Perform queries
mod = 3803 NEW_LINE d = 26 NEW_LINE hash_b = 0 NEW_LINE hash_a = [ ] NEW_LINE mul = [ ] NEW_LINE def mi ( x ) : NEW_LINE INDENT global mod NEW_LINE p = mod - 2 NEW_LINE s = 1 NEW_LINE while p != 1 : NEW_LINE INDENT if p % 2 == 1 : NEW_LINE INDENT s = ( s * x ) % mod NEW_LINE DEDENT x = ( x * x ) % mod NEW_LINE p //= 2 NEW_LINE DEDENT return ( s * x ) % mod NEW_LINE DEDENT def genHash ( a , b ) : NEW_LINE INDENT global hash_b , hash_a , mul , d , mod NEW_LINE hash_a = [ 0 ] * len ( a ) NEW_LINE mul = [ 0 ] * len ( a ) NEW_LINE for i in range ( len ( b ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT hash_b = ( hash_b * d + ( ord ( b [ i ] ) - 97 ) ) % mod NEW_LINE DEDENT mul [ 0 ] = 1 NEW_LINE hash_a [ 0 ] = ( ord ( a [ 0 ] ) - 97 ) % mod NEW_LINE for i in range ( 1 , len ( a ) ) : NEW_LINE INDENT mul [ i ] = ( mul [ i - 1 ] * d ) % mod NEW_LINE hash_a [ i ] = ( hash_a [ i - 1 ] + mul [ i ] * ( ord ( a [ i ] ) - 97 ) ) % mod NEW_LINE DEDENT DEDENT def checkEqual ( i , len_a , len_b ) : NEW_LINE INDENT global hash_b , hash_a , mul , d , mod NEW_LINE x = - 1 NEW_LINE if i == 0 : NEW_LINE INDENT x = hash_a [ len_b - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT x = ( hash_a [ i + len_b - 1 ] - hash_a [ i - 1 ] + 2 * mod ) % mod NEW_LINE x = ( x * mi ( mul [ i ] ) ) % mod NEW_LINE DEDENT if x == hash_b : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = " abababababa " NEW_LINE b = " aba " NEW_LINE genHash ( a , b ) NEW_LINE queries = [ 0 , 1 , 2 , 3 ] NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT if checkEqual ( queries [ i ] , len ( a ) , len ( b ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT DEDENT
Number of ways to divide an array into K equal sum sub | Python3 implementation of the approach ; Array to store the states of DP ; Array to check if a state has been solved before ; To store the sum of the array elements ; Function to find the sum of all the array elements ; Function to return the number of ways ; If sum is not divisible by k answer will be zero ; Base case ; To check if a state has been solved before ; Sum of all the numbers from the beginning of the array ; Setting the current state as solved ; Recurrence relation ; Returning solved state ; Driver code ; Function call to find the sum of the array elements ; Print the number of ways
import numpy as np NEW_LINE max_size = 20 NEW_LINE max_k = 20 NEW_LINE dp = np . zeros ( ( max_size , max_k ) ) ; NEW_LINE v = np . zeros ( ( max_size , max_k ) ) ; NEW_LINE sum = 0 ; NEW_LINE def findSum ( arr , n ) : NEW_LINE INDENT global sum NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT DEDENT def cntWays ( arr , i , ck , k , n , curr_sum ) : NEW_LINE INDENT if ( sum % k != 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( i != n and ck == k + 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT if ( ck == k + 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( v [ i ] [ ck ] ) : NEW_LINE INDENT return dp [ i ] [ ck ] ; NEW_LINE DEDENT curr_sum += arr [ i ] ; NEW_LINE v [ i ] [ ck ] = 1 ; NEW_LINE dp [ i ] [ ck ] = cntWays ( arr , i + 1 , ck , k , n , curr_sum ) ; NEW_LINE if ( curr_sum == ( sum / k ) * ck ) : NEW_LINE INDENT dp [ i ] [ ck ] += cntWays ( arr , i + 1 , ck + 1 , k , n , curr_sum ) ; NEW_LINE DEDENT return dp [ i ] [ ck ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , - 1 , 1 , - 1 , 1 , - 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE findSum ( arr , n ) ; NEW_LINE print ( cntWays ( arr , 0 , 1 , k , n , 0 ) ) ; NEW_LINE DEDENT
Maximum sum in an array such that every element has exactly one adjacent element to it | Python 3 implementation of the approach ; To store the states of dp ; Function to return the maximized sum ; Base case ; Checks if a state is already solved ; Recurrence relation ; Return the result ; Driver code
arrSize = 51 NEW_LINE dp = [ 0 for i in range ( arrSize ) ] NEW_LINE v = [ False for i in range ( arrSize ) ] NEW_LINE def sumMax ( i , arr , n ) : NEW_LINE INDENT if ( i >= n - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( v [ i ] ) : NEW_LINE INDENT return dp [ i ] NEW_LINE DEDENT v [ i ] = True NEW_LINE dp [ i ] = max ( arr [ i ] + arr [ i + 1 ] + sumMax ( i + 3 , arr , n ) , sumMax ( i + 1 , arr , n ) ) NEW_LINE return dp [ i ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( sumMax ( 0 , arr , n ) ) NEW_LINE DEDENT
Maximum Sum Subsequence of length k | Python program to calculate the maximum sum of increasing subsequence of length k ; In the implementation dp [ n ] [ k ] represents maximum sum subsequence of length k and the subsequence is ending at index n . ; Initializing whole multidimensional dp array with value - 1 ; For each ith position increasing subsequence of length 1 is equal to that array ith value so initializing dp [ i ] [ 1 ] with that array value ; Starting from 1 st index as we have calculated for 0 th index . Computing optimized dp values in bottom - up manner ; check for increasing subsequence ; Proceed if value is pre calculated ; Check for all the subsequences ending at any j < i and try including element at index i in them for some length l . Update the maximum value for every length . ; The final result would be the maximum value of dp [ i ] [ k ] for all different i . ; When no subsequence of length k is possible sum would be considered zero ; Driver Code
def MaxIncreasingSub ( arr , n , k ) : NEW_LINE INDENT dp = [ - 1 ] * n NEW_LINE ans = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] = [ - 1 ] * ( k + 1 ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT dp [ i ] [ 1 ] = arr [ i ] NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if arr [ j ] < arr [ i ] : NEW_LINE INDENT for l in range ( 1 , k ) : NEW_LINE INDENT if dp [ j ] [ l ] != - 1 : NEW_LINE INDENT dp [ i ] [ l + 1 ] = max ( dp [ i ] [ l + 1 ] , dp [ j ] [ l ] + arr [ i ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ans < dp [ i ] [ k ] : NEW_LINE INDENT ans = dp [ i ] [ k ] NEW_LINE DEDENT DEDENT return ( 0 if ans == - 1 else ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 8 , 3 NEW_LINE arr = [ 8 , 5 , 9 , 10 , 5 , 6 , 21 , 8 ] NEW_LINE ans = MaxIncreasingSub ( arr , n , k ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Generate all unique partitions of an integer | Set 2 | Array to store the numbers used to form the required sum ; Function to print the array which contains the unique partitions which are used to form the required sum ; Function to find all the unique partitions remSum = remaining sum to form maxVal is the maximum number that can be used to make the partition ; If remSum == 0 that means the sum is achieved so print the array ; i will begin from maxVal which is the maximum value which can be used to form the sum ; Store the number used in forming sum gradually in the array ; Since i used the rest of partition cant have any number greater than i hence second parameter is i ; Driver code
dp = [ 0 for i in range ( 200 ) ] NEW_LINE count = 0 NEW_LINE def print1 ( idx ) : NEW_LINE INDENT for i in range ( 1 , idx , 1 ) : NEW_LINE INDENT print ( dp [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " , end ▁ = ▁ " " ) NEW_LINE DEDENT def solve ( remSum , maxVal , idx , count ) : NEW_LINE INDENT if ( remSum == 0 ) : NEW_LINE INDENT print1 ( idx ) NEW_LINE count += 1 NEW_LINE return NEW_LINE DEDENT i = maxVal NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT if ( i > remSum ) : NEW_LINE INDENT i -= 1 NEW_LINE continue NEW_LINE DEDENT elif ( i <= remSum ) : NEW_LINE INDENT dp [ idx ] = i NEW_LINE solve ( remSum - i , i , idx + 1 , count ) NEW_LINE i -= 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE count = 0 NEW_LINE solve ( n , n , 1 , count ) NEW_LINE DEDENT
Queries for bitwise OR in the given matrix | Python 3 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 for each row ; Finding column - wise prefix count ; Function to return the result for a query ; To store the answer ; Loop for each bit ; To store the number of variables with ith bit set ; If count of variables with ith bit set is greater than 0 ; Driver code
bitscount = 32 NEW_LINE n = 3 NEW_LINE prefix_count = [ [ [ 0 for i in range ( n ) ] for j in range ( n ) ] for k in range ( bitscount ) ] NEW_LINE def findPrefixCount ( arr ) : NEW_LINE INDENT for i in range ( bitscount ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT prefix_count [ i ] [ j ] [ 0 ] = ( ( arr [ j ] [ 0 ] >> i ) & 1 ) NEW_LINE for k in range ( 1 , n ) : NEW_LINE INDENT prefix_count [ i ] [ j ] [ k ] = ( ( arr [ j ] [ k ] >> i ) & 1 ) NEW_LINE prefix_count [ i ] [ j ] [ k ] += prefix_count [ i ] [ j ] [ k - 1 ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( bitscount ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE INDENT for k in range ( n ) : NEW_LINE INDENT prefix_count [ i ] [ j ] [ k ] += prefix_count [ i ] [ j - 1 ] [ k ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def rangeOr ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( bitscount ) : NEW_LINE INDENT if ( x1 == 0 and y1 == 0 ) : NEW_LINE INDENT p = prefix_count [ i ] [ x2 ] [ y2 ] NEW_LINE DEDENT elif ( x1 == 0 ) : NEW_LINE INDENT p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x2 ] [ y1 - 1 ] NEW_LINE DEDENT elif ( y1 == 0 ) : NEW_LINE INDENT p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x1 - 1 ] [ y2 ] NEW_LINE DEDENT else : NEW_LINE INDENT p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x1 - 1 ] [ y2 ] - prefix_count [ i ] [ x2 ] [ y1 - 1 ] + prefix_count [ i ] [ x1 - 1 ] [ y1 - 1 ] ; NEW_LINE DEDENT if ( p != 0 ) : NEW_LINE INDENT ans = ( ans | ( 1 << i ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE findPrefixCount ( arr ) NEW_LINE queries = [ [ 1 , 1 , 1 , 1 ] , [ 1 , 2 , 2 , 2 ] ] NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( rangeOr ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , queries [ i ] [ 2 ] , queries [ i ] [ 3 ] ) ) NEW_LINE DEDENT DEDENT
Queries for bitwise AND in the given matrix | Python 3 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 for each row ; Finding column - wise prefix count ; Function to return the result for a query ; To store the answer ; Loop for each bit ; To store the number of variables with ith bit set ; If count of variables with ith bit set is greater than 0 ; Driver code
bitscount = 32 NEW_LINE n = 3 NEW_LINE prefix_count = [ [ [ 0 for i in range ( n ) ] for j in range ( n ) ] for k in range ( bitscount ) ] NEW_LINE def findPrefixCount ( arr ) : NEW_LINE INDENT for i in range ( bitscount ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT prefix_count [ i ] [ j ] [ 0 ] = ( ( arr [ j ] [ 0 ] >> i ) & 1 ) NEW_LINE for k in range ( 1 , n ) : NEW_LINE INDENT prefix_count [ i ] [ j ] [ k ] = ( ( arr [ j ] [ k ] >> i ) & 1 ) NEW_LINE prefix_count [ i ] [ j ] [ k ] += prefix_count [ i ] [ j ] [ k - 1 ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( bitscount ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE INDENT for k in range ( n ) : NEW_LINE INDENT prefix_count [ i ] [ j ] [ k ] += prefix_count [ i ] [ j - 1 ] [ k ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def rangeOr ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( bitscount ) : NEW_LINE INDENT if ( x1 == 0 and y1 == 0 ) : NEW_LINE INDENT p = prefix_count [ i ] [ x2 ] [ y2 ] NEW_LINE DEDENT elif ( x1 == 0 ) : NEW_LINE INDENT p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x2 ] [ y1 - 1 ] NEW_LINE DEDENT elif ( y1 == 0 ) : NEW_LINE INDENT p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x1 - 1 ] [ y2 ] NEW_LINE DEDENT else : NEW_LINE INDENT p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x1 - 1 ] [ y2 ] - prefix_count [ i ] [ x2 ] [ y1 - 1 ] + prefix_count [ i ] [ x1 - 1 ] [ y1 - 1 ] ; NEW_LINE DEDENT if ( p == ( x2 - x1 + 1 ) * ( y2 - y1 + 1 ) ) : NEW_LINE INDENT ans = ( ans | ( 1 << i ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE findPrefixCount ( arr ) NEW_LINE queries = [ [ 1 , 1 , 1 , 1 ] , [ 1 , 2 , 2 , 2 ] ] NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( rangeOr ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , queries [ i ] [ 2 ] , queries [ i ] [ 3 ] ) ) NEW_LINE DEDENT DEDENT
Maximum sum such that no two elements are adjacent | Set 2 | Python 3 program to implement above approach ; variable to store states of dp ; variable to check if a given state has been solved ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Required recurrence relation ; Returning the value ; Driver code
maxLen = 10 NEW_LINE dp = [ 0 for i in range ( maxLen ) ] NEW_LINE v = [ 0 for i in range ( maxLen ) ] NEW_LINE def maxSum ( arr , i , n ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( v [ i ] ) : NEW_LINE INDENT return dp [ i ] NEW_LINE DEDENT v [ i ] = 1 NEW_LINE dp [ i ] = max ( maxSum ( arr , i + 1 , n ) , arr [ i ] + maxSum ( arr , i + 2 , n ) ) NEW_LINE return dp [ i ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 9 , 7 , 33 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSum ( arr , 0 , n ) ) NEW_LINE DEDENT
Optimal Strategy for a Game | Set 2 | Python3 program to find out maximum value from a given sequence of coins ; For both of your choices , the opponent gives you total sum minus maximum of his value ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Compute sum of elements ; Initialize memoization table ; Driver Code
MAX = 100 NEW_LINE memo = [ [ 0 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE def oSRec ( arr , i , j , Sum ) : NEW_LINE INDENT if ( j == i + 1 ) : NEW_LINE INDENT return max ( arr [ i ] , arr [ j ] ) NEW_LINE DEDENT if ( memo [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return memo [ i ] [ j ] NEW_LINE DEDENT memo [ i ] [ j ] = max ( ( Sum - oSRec ( arr , i + 1 , j , Sum - arr [ i ] ) ) , ( Sum - oSRec ( arr , i , j - 1 , Sum - arr [ j ] ) ) ) NEW_LINE return memo [ i ] [ j ] NEW_LINE DEDENT def optimalStrategyOfGame ( arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE Sum = sum ( arr ) NEW_LINE for j in range ( MAX ) : NEW_LINE INDENT for k in range ( MAX ) : NEW_LINE INDENT memo [ j ] [ k ] = - 1 NEW_LINE DEDENT DEDENT return oSRec ( arr , 0 , n - 1 , Sum ) NEW_LINE DEDENT arr1 = [ 8 , 15 , 3 , 7 ] NEW_LINE n = len ( arr1 ) NEW_LINE print ( optimalStrategyOfGame ( arr1 , n ) ) NEW_LINE arr2 = [ 2 , 2 , 2 , 2 ] NEW_LINE n = len ( arr2 ) NEW_LINE print ( optimalStrategyOfGame ( arr2 , n ) ) NEW_LINE arr3 = [ 20 , 30 , 2 , 2 , 2 , 10 ] NEW_LINE n = len ( arr3 ) NEW_LINE print ( optimalStrategyOfGame ( arr3 , n ) ) NEW_LINE
Minimum cost to select K strictly increasing elements | Python3 program for the above approach ; Function to calculate min cost to choose k increasing elements ; If k elements are counted return 0 ; If all elements of array has been traversed then return MAX_VALUE ; To check if this is already calculated ; When i 'th elements is not considered ; When the ith element is greater than previous element check if adding its cost makes total cost minimum ; Driver code
N = 1005 ; NEW_LINE K = 20 ; NEW_LINE n = 0 NEW_LINE k = 0 NEW_LINE dp = [ [ [ - 1 for k in range ( K + 1 ) ] for j in range ( N + 1 ) ] for i in range ( N + 1 ) ] NEW_LINE def minCost ( i , prev , cnt , ele , cost ) : NEW_LINE INDENT if ( cnt == k + 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( i == n + 1 ) : NEW_LINE INDENT return 100000 ; NEW_LINE DEDENT ans = dp [ i ] [ prev ] [ cnt ] ; NEW_LINE if ( ans != - 1 ) : NEW_LINE INDENT return ans ; NEW_LINE DEDENT ans = minCost ( i + 1 , prev , cnt , ele , cost ) ; NEW_LINE if ( ele [ i ] > ele [ prev ] ) : NEW_LINE INDENT ans = min ( ans , cost [ i ] + minCost ( i + 1 , i , cnt + 1 , ele , cost ) ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE k = 2 ; NEW_LINE ele = [ 0 , 2 , 6 , 4 , 8 ] NEW_LINE cost = [ 0 , 40 , 20 , 30 , 10 ] NEW_LINE ans = minCost ( 1 , 0 , 1 , ele , cost ) ; NEW_LINE if ( ans == 100000 ) : NEW_LINE INDENT ans = - 1 ; NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT
Maximize the subarray sum after multiplying all elements of any subarray with X | Python3 implementation of the approach ; Function to return the maximum sum ; Base case ; If already calculated ; If no elements have been chosen ; Do not choose any element and use Kadane 's algorithm by taking max ; Choose the sub - array and multiply x ; Choose the sub - array and multiply x ; End the sub - array multiplication ; No more multiplication ; Memoize and return the answer ; Function to get the maximum sum ; Initialize dp with - 1 ; Iterate from every position and find the maximum sum which is possible ; Driver code
N = 5 NEW_LINE def func ( idx , cur , a , dp , n , x ) : NEW_LINE INDENT if ( idx == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ idx ] [ cur ] != - 1 ) : NEW_LINE INDENT return dp [ idx ] [ cur ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( cur == 0 ) : NEW_LINE INDENT ans = max ( ans , a [ idx ] + func ( idx + 1 , 0 , a , dp , n , x ) ) NEW_LINE ans = max ( ans , x * a [ idx ] + func ( idx + 1 , 1 , a , dp , n , x ) ) NEW_LINE DEDENT elif ( cur == 1 ) : NEW_LINE INDENT ans = max ( ans , x * a [ idx ] + func ( idx + 1 , 1 , a , dp , n , x ) ) NEW_LINE ans = max ( ans , a [ idx ] + func ( idx + 1 , 2 , a , dp , n , x ) ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = max ( ans , a [ idx ] + func ( idx + 1 , 2 , a , dp , n , x ) ) NEW_LINE DEDENT dp [ idx ] [ cur ] = ans NEW_LINE return dp [ idx ] [ cur ] NEW_LINE DEDENT def getMaximumSum ( a , n , x ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( 3 ) ] for j in range ( n ) ] NEW_LINE maxi = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT maxi = max ( maxi , func ( i , 0 , a , dp , n , x ) ) NEW_LINE DEDENT return maxi NEW_LINE DEDENT a = [ - 3 , 8 , - 2 , 1 , - 6 ] NEW_LINE n = len ( a ) NEW_LINE x = - 1 NEW_LINE print ( getMaximumSum ( a , n , x ) ) NEW_LINE
Count pairs of non | Python3 implementation of the approach ; Pre - processing function ; Get the size of the string ; Initially mark every position as false ; For the length ; Iterate for every index with length j ; If the length is less than 2 ; If characters are equal ; Check for equal ; Function to return the number of pairs ; Create the dp table initially ; Declare the left array ; Declare the right array ; Initially left [ 0 ] is 1 ; Count the number of palindrome pairs to the left ; Initially right most as 1 ; Count the number of palindrome pairs to the right ; Count the number of pairs ; Driver code
N = 100 NEW_LINE def pre_process ( dp , s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT dp [ i ] [ j ] = False NEW_LINE DEDENT DEDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT for i in range ( n - j + 1 ) : NEW_LINE INDENT if ( j <= 2 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ i + j - 1 ] = True NEW_LINE DEDENT DEDENT elif ( s [ i ] == s [ i + j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ i + j - 1 ] = dp [ i + 1 ] [ i + j - 2 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def countPairs ( s ) : NEW_LINE INDENT dp = [ [ False for i in range ( N ) ] for j in range ( N ) ] NEW_LINE pre_process ( dp , s ) NEW_LINE n = len ( s ) NEW_LINE left = [ 0 for i in range ( n ) ] NEW_LINE right = [ 0 for i in range ( n ) ] NEW_LINE left [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT if ( dp [ j ] [ i ] == 1 ) : NEW_LINE INDENT left [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT right [ n - 1 ] = 1 NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT right [ i ] = right [ i + 1 ] NEW_LINE for j in range ( n - 1 , i - 1 , - 1 ) : NEW_LINE INDENT if ( dp [ i ] [ j ] == 1 ) : NEW_LINE INDENT right [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT ans = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT ans += left [ i ] * right [ i + 1 ] NEW_LINE DEDENT return ans NEW_LINE DEDENT s = " abacaba " NEW_LINE print ( countPairs ( s ) ) NEW_LINE
Queries to check if substring [ L ... R ] is palindrome or not | Python3 implementation of the approach ; Pre - processing function ; Get the size of the string ; Initially mark every position as false ; For the length ; Iterate for every index with length j ; If the length is less than 2 ; If characters are equal ; Check for equal ; Function to answer every query in O ( 1 ) ; Driver code
N = 100 NEW_LINE def pre_process ( dp , s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT dp [ i ] [ j ] = False NEW_LINE DEDENT DEDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT for i in range ( n - j + 1 ) : NEW_LINE INDENT if ( j <= 2 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ i + j - 1 ] = True NEW_LINE DEDENT DEDENT elif ( s [ i ] == s [ i + j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ i + j - 1 ] = dp [ i + 1 ] [ i + j - 2 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def answerQuery ( l , r , dp ) : NEW_LINE INDENT if ( dp [ l ] [ r ] ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT s = " abaaab " NEW_LINE dp = [ [ 0 for i in range ( N ) ] for i in range ( N ) ] NEW_LINE pre_process ( dp , s ) NEW_LINE queries = [ [ 0 , 1 ] , [ 1 , 5 ] ] NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT answerQuery ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , dp ) NEW_LINE DEDENT
Length of the longest increasing subsequence such that no two adjacent elements are coprime | Python3 program to find the length of the longest increasing sub sequence from the given array such that no two adjacent elements are co prime ; Function to find the length of the longest increasing sub sequence from the given array such that no two adjacent elements are co prime ; To store dp and d value ; To store required answer ; For all elements in the array ; Initially answer is one ; For all it 's divisors ; Update the dp value ; Update the divisor value ; Check for required answer ; Update divisor of a [ i ] ; Return required answer ; Driver code
N = 100005 NEW_LINE def LIS ( a , n ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE d = [ 0 for i in range ( N ) ] NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ a [ i ] ] = 1 NEW_LINE for j in range ( 2 , a [ i ] ) : NEW_LINE INDENT if j * j > a [ i ] : NEW_LINE INDENT break NEW_LINE DEDENT if ( a [ i ] % j == 0 ) : NEW_LINE INDENT dp [ a [ i ] ] = max ( dp [ a [ i ] ] , dp [ d [ j ] ] + 1 ) NEW_LINE dp [ a [ i ] ] = max ( dp [ a [ i ] ] , dp [ d [ a [ i ] // j ] ] + 1 ) NEW_LINE d [ j ] = a [ i ] NEW_LINE d [ a [ i ] // j ] = a [ i ] NEW_LINE DEDENT DEDENT ans = max ( ans , dp [ a [ i ] ] ) NEW_LINE d [ a [ i ] ] = a [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( LIS ( a , n ) ) NEW_LINE
Find the number of binary strings of length N with at least 3 consecutive 1 s | Function that returns true if s contains three consecutive 1 's ; Function to return the count of required strings ; Driver code
def check ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( s [ i ] == '1' and s [ i - 1 ] == '1' and s [ i - 2 ] == '1' ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT DEDENT DEDENT def countStr ( i , s ) : NEW_LINE INDENT if ( i < 0 ) : NEW_LINE INDENT if ( check ( s ) ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT s [ i ] = '0' ; NEW_LINE ans = countStr ( i - 1 , s ) ; NEW_LINE s [ i ] = '1' ; NEW_LINE ans += countStr ( i - 1 , s ) ; NEW_LINE s [ i ] = '0' ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 ; NEW_LINE s = list ( '0' * N ) ; NEW_LINE print ( countStr ( N - 1 , s ) ) ; NEW_LINE DEDENT
Find the number of binary strings of length N with at least 3 consecutive 1 s | Function to return the count of required strings ; '0' at ith position ; '1' at ith position ; Driver code ; Base condition : 2 ^ ( i + 1 ) because of 0 indexing
def solve ( i , x , dp ) : NEW_LINE INDENT if ( i < 0 ) : NEW_LINE INDENT return x == 3 NEW_LINE DEDENT if ( dp [ i ] [ x ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ x ] NEW_LINE DEDENT dp [ i ] [ x ] = solve ( i - 1 , 0 , dp ) NEW_LINE dp [ i ] [ x ] += solve ( i - 1 , x + 1 , dp ) NEW_LINE return dp [ i ] [ x ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 ; NEW_LINE dp = [ [ 0 for i in range ( n ) ] for j in range ( 4 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 4 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT dp [ i ] [ 3 ] = ( 1 << ( i + 1 ) ) NEW_LINE DEDENT print ( solve ( n - 1 , 0 , dp ) ) NEW_LINE DEDENT
Find the sum of the diagonal elements of the given N X N spiral matrix | Function to return the sum of both the diagonal elements of the required matrix ; Array to store sum of diagonal elements ; Base cases ; Computing the value of dp ; Driver code
def findSum ( n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE dp [ 1 ] = 1 NEW_LINE dp [ 0 ] = 0 NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT dp [ i ] = ( ( 4 * ( i * i ) ) - 6 * ( i - 1 ) + dp [ i - 2 ] ) NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE print ( findSum ( n ) ) NEW_LINE DEDENT
Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming | Function to find the diameter of the tree using Dynamic Programming ; Traverse for all children of node ; Call DFS function again ; Include the current node then donot include the children ; Donot include current node , then include children or not include them ; Recurrence value ; Driver code ; Constructed tree is 1 / \ 2 3 / \ 4 5 ; create undirected edges ; Numbers to node ; Find maximum sum by calling function
def dfs ( node , parent , dp1 , dp2 , adj , tree ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 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 , tree ) ; NEW_LINE sum1 += dp2 [ i ] ; NEW_LINE sum2 += max ( dp1 [ i ] , dp2 [ i ] ) ; NEW_LINE DEDENT dp1 [ node ] = tree [ node ] + sum1 ; NEW_LINE dp2 [ node ] = sum2 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; 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 tree = [ 0 for i in range ( n + 1 ) ] ; NEW_LINE tree [ 1 ] = 10 ; NEW_LINE tree [ 2 ] = 5 ; NEW_LINE tree [ 3 ] = 11 ; NEW_LINE tree [ 4 ] = 6 ; NEW_LINE tree [ 5 ] = 8 ; NEW_LINE dp1 = [ 0 for i in range ( n + 1 ) ] ; NEW_LINE dp2 = [ 0 for i in range ( n + 1 ) ] ; NEW_LINE dfs ( 1 , 1 , dp1 , dp2 , adj , tree ) ; NEW_LINE print ( " Maximum ▁ sum : " , max ( dp1 [ 1 ] , dp2 [ 1 ] ) ) NEW_LINE DEDENT
Count number of ways to reach a given score in a Matrix | Python3 implementation of the approach ; To store the states of dp ; To check whether a particular state of dp has been solved ; Function to find the ways using memoization ; Base cases ; If required score becomes negative ; If current state has been reached before ; Set current state to visited ; Driver code
n = 3 NEW_LINE MAX = 60 NEW_LINE dp = [ [ [ 0 for i in range ( 30 ) ] for i in range ( 30 ) ] for i in range ( MAX + 1 ) ] NEW_LINE v = [ [ [ 0 for i in range ( 30 ) ] for i in range ( 30 ) ] for i in range ( MAX + 1 ) ] NEW_LINE def findCount ( mat , i , j , m ) : NEW_LINE INDENT if ( i == 0 and j == 0 ) : NEW_LINE INDENT if ( m == mat [ 0 ] [ 0 ] ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( m < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( i < 0 or j < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( v [ i ] [ j ] [ m ] > 0 ) : NEW_LINE INDENT return dp [ i ] [ j ] [ m ] NEW_LINE DEDENT v [ i ] [ j ] [ m ] = True NEW_LINE dp [ i ] [ j ] [ m ] = ( findCount ( mat , i - 1 , j , m - mat [ i ] [ j ] ) + findCount ( mat , i , j - 1 , m - mat [ i ] [ j ] ) ) NEW_LINE return dp [ i ] [ j ] [ m ] NEW_LINE DEDENT mat = [ [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] ] NEW_LINE m = 5 NEW_LINE print ( findCount ( mat , n - 1 , n - 1 , m ) ) NEW_LINE
Number of ways of scoring R runs in B balls with at most W wickets | Python3 implementation of the approach ; Function to return the number of ways to score R runs in B balls with at most W wickets ; If the wickets lost are more ; If runs scored are more ; If condition is met ; If no run got scored ; Already visited state ; If scored 0 run ; If scored 1 run ; If scored 2 runs ; If scored 3 runs ; If scored 4 runs ; If scored 6 runs ; If scored no run and lost a wicket ; Memoize and return ; Driver code
mod = 1000000007 NEW_LINE RUNMAX = 300 NEW_LINE BALLMAX = 50 NEW_LINE WICKETMAX = 10 NEW_LINE def CountWays ( r , b , l , R , B , W , dp ) : NEW_LINE INDENT if ( l > W ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( r > R ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( b == B and r == R ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( b == B ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ r ] [ b ] [ l ] != - 1 ) : NEW_LINE INDENT return dp [ r ] [ b ] [ l ] NEW_LINE DEDENT ans = 0 ; NEW_LINE ans += CountWays ( r , b + 1 , l , R , B , W , dp ) ; NEW_LINE ans = ans % mod ; NEW_LINE ans += CountWays ( r + 1 , b + 1 , l , R , B , W , dp ) ; NEW_LINE ans = ans % mod ; NEW_LINE ans += CountWays ( r + 2 , b + 1 , l , R , B , W , dp ) ; NEW_LINE ans = ans % mod ; NEW_LINE ans += CountWays ( r + 3 , b + 1 , l , R , B , W , dp ) ; NEW_LINE ans = ans % mod ; NEW_LINE ans += CountWays ( r + 4 , b + 1 , l , R , B , W , dp ) ; NEW_LINE ans = ans % mod ; NEW_LINE ans += CountWays ( r + 6 , b + 1 , l , R , B , W , dp ) ; NEW_LINE ans = ans % mod ; NEW_LINE ans += CountWays ( r , b + 1 , l + 1 , R , B , W , dp ) ; NEW_LINE ans = ans % mod ; NEW_LINE dp [ r ] [ b ] [ l ] = ans NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT R = 40 NEW_LINE B = 10 NEW_LINE W = 40 NEW_LINE dp = [ [ [ - 1 for k in range ( WICKETMAX ) ] for j in range ( BALLMAX ) ] for i in range ( RUNMAX ) ] NEW_LINE print ( CountWays ( 0 , 0 , 0 , R , B , W , dp ) ) NEW_LINE DEDENT
Minimum steps to delete a string by deleting substring comprising of same characters | Function to return the minimum number of delete operations ; When a single character is deleted ; When a group of consecutive characters are deleted if any of them matches ; When both the characters are same then delete the letters in between them ; Memoize ; Driver code
def findMinimumDeletion ( l , r , dp , s ) : NEW_LINE INDENT if l > r : NEW_LINE INDENT return 0 NEW_LINE DEDENT if l == r : NEW_LINE INDENT return 1 NEW_LINE DEDENT if dp [ l ] [ r ] != - 1 : NEW_LINE INDENT return dp [ l ] [ r ] NEW_LINE DEDENT res = 1 + findMinimumDeletion ( l + 1 , r , dp , s ) NEW_LINE for i in range ( l + 1 , r + 1 ) : NEW_LINE INDENT if s [ l ] == s [ i ] : NEW_LINE INDENT res = min ( res , findMinimumDeletion ( l + 1 , i - 1 , dp , s ) + findMinimumDeletion ( i , r , dp , s ) ) NEW_LINE DEDENT DEDENT dp [ l ] [ r ] = res NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abcddcba " NEW_LINE n = len ( s ) NEW_LINE N = 10 NEW_LINE dp = [ [ - 1 for i in range ( N ) ] for j in range ( N ) ] NEW_LINE print ( findMinimumDeletion ( 0 , n - 1 , dp , s ) ) NEW_LINE DEDENT
Minimal product subsequence where adjacent elements are separated by a maximum distance of K | Python3 implementation of the above approach . ; Function to get the minimum product of subsequence such that adjacent elements are separated by a max distance of K ; multiset will hold pairs pair = ( log value of product , dp [ j ] value ) dp [ j ] = minimum product % mod multiset will be sorted according to log values Therefore , corresponding to the minimum log value dp [ j ] value can be obtained . ; For the first k - sized window . ; Update log value by adding previous minimum log value ; Update dp [ i ] ; Insert it again into the multiset since it is within the k - size window ; Eliminate previous value which falls out of the k - sized window ; Insert newest value to enter in the k - sized window . ; dp [ n - 1 ] will have minimum product % mod such that adjacent elements are separated by a max distance K ; Driver Code
import math NEW_LINE mod = 1000000007 ; NEW_LINE MAX = 100005 ; NEW_LINE def minimumProductSubsequence ( arr , n , k ) : NEW_LINE INDENT s = [ ] NEW_LINE dp = [ 0 for i in range ( MAX ) ] ; NEW_LINE p = [ 0.0 for i in range ( MAX ) ] ; NEW_LINE dp [ 0 ] = arr [ 0 ] ; NEW_LINE p [ 0 ] = math . log ( arr [ 0 ] ) ; NEW_LINE s . append ( [ p [ 0 ] , dp [ 0 ] ] ) ; NEW_LINE s . sort ( ) NEW_LINE for i in range ( 1 , k ) : NEW_LINE INDENT l = s [ 0 ] [ 0 ] NEW_LINE min = s [ 0 ] [ 1 ] NEW_LINE p [ i ] = math . log ( arr [ i ] ) + l ; NEW_LINE dp [ i ] = ( arr [ i ] * min ) % mod ; NEW_LINE s . append ( [ p [ i ] , dp [ i ] ] ) ; NEW_LINE s . sort ( ) NEW_LINE DEDENT for i in range ( k , n ) : NEW_LINE INDENT l = s [ 0 ] [ 0 ] NEW_LINE min = s [ 0 ] [ 1 ] NEW_LINE p [ i ] = math . log ( arr [ i ] ) + l ; NEW_LINE dp [ i ] = ( arr [ i ] * min ) % mod ; NEW_LINE if [ p [ i - k ] , dp [ i - k ] ] in s : NEW_LINE INDENT s . pop ( s . index ( [ p [ i - k ] , dp [ i - k ] ] ) ) NEW_LINE DEDENT s . append ( [ p [ i ] , dp [ i ] ] ) ; NEW_LINE s . sort ( ) NEW_LINE DEDENT return dp [ n - 1 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 ; NEW_LINE print ( minimumProductSubsequence ( arr , n , k ) ) NEW_LINE DEDENT
Ways to form a group from three groups with given constraints | Python3 program to find the number of ways to form the group of peopls ; Function to pre - compute the Combination using DP ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to find the number of ways ; Function to pre - compute ; Sum the Zci ; Iterate for second position ; Iterate for first position ; Multiply the common Combination value ; Driver Code
C = [ [ 0 for i in range ( 1000 ) ] for i in range ( 1000 ) ] NEW_LINE def binomialCoeff ( n ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( i + 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 DEDENT def numberOfWays ( x , y , z ) : NEW_LINE INDENT binomialCoeff ( max ( x , max ( y , z ) ) ) NEW_LINE sum = 0 NEW_LINE for i in range ( 1 , z + 1 ) : NEW_LINE INDENT sum = ( sum + C [ z ] [ i ] ) NEW_LINE DEDENT sum1 = 0 NEW_LINE for i in range ( 1 , y + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , x + 1 ) : NEW_LINE INDENT sum1 = ( sum1 + ( C [ y ] [ i ] * C [ x ] [ j ] ) ) NEW_LINE DEDENT DEDENT sum1 = ( sum * sum1 ) NEW_LINE return sum1 NEW_LINE DEDENT x = 3 NEW_LINE y = 2 NEW_LINE z = 1 NEW_LINE print ( numberOfWays ( x , y , z ) ) NEW_LINE
Longest subsequence such that adjacent elements have at least one common digit | Returns Length of maximum Length subsequence ; To store the Length of the maximum Length subsequence ; To store current element arr [ i ] ; To store the Length of the sub - sequence ending at index i and having common digit d ; To store digits present in current element ; To store Length of maximum Length subsequence ending at index i ; For first element maximum Length is 1 for each digit ; Find digits of each element , then find Length of subsequence for each digit and then find local maximum ; Find digits in current element ; For each digit present find Length of subsequence and find local maximum ; Update value of dp [ i ] [ d ] for each digit present in current element to local maximum found . ; Update maximum Length with local maximum ; Driver code
def findSubsequence ( arr , n ) : NEW_LINE INDENT Len = 1 NEW_LINE tmp = 0 NEW_LINE i , j , d = 0 , 0 , 0 NEW_LINE dp = [ [ 0 for i in range ( 10 ) ] for i in range ( n ) ] NEW_LINE cnt = [ 0 for i in range ( 10 ) ] NEW_LINE locMax = 0 NEW_LINE tmp = arr [ 0 ] NEW_LINE while ( tmp > 0 ) : NEW_LINE INDENT dp [ 0 ] [ tmp % 10 ] = 1 NEW_LINE tmp //= 10 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT tmp = arr [ i ] NEW_LINE locMax = 1 NEW_LINE cnt = [ 0 for i in range ( 10 ) ] NEW_LINE while ( tmp > 0 ) : NEW_LINE INDENT cnt [ tmp % 10 ] = 1 NEW_LINE tmp //= 10 NEW_LINE DEDENT for d in range ( 10 ) : NEW_LINE INDENT if ( cnt [ d ] ) : NEW_LINE INDENT dp [ i ] [ d ] = 1 NEW_LINE for j in range ( i ) : NEW_LINE INDENT dp [ i ] [ d ] = max ( dp [ i ] [ d ] , dp [ j ] [ d ] + 1 ) NEW_LINE locMax = max ( dp [ i ] [ d ] , locMax ) NEW_LINE DEDENT DEDENT DEDENT for d in range ( 10 ) : NEW_LINE INDENT if ( cnt [ d ] ) : NEW_LINE INDENT dp [ i ] [ d ] = locMax NEW_LINE DEDENT DEDENT Len = max ( Len , locMax ) NEW_LINE DEDENT return Len NEW_LINE DEDENT arr = [ 1 , 12 , 44 , 29 , 33 , 96 , 89 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findSubsequence ( arr , n ) ) NEW_LINE
Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime | Python implementation of the above approach ; Prime numbers upto 100 ; Function to return the count of required numbers from 0 to num ; Base Case ; check if the difference is equal to any prime number ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current position is odd add it to currOdd , otherwise to currEven ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver Code
M = 18 NEW_LINE prime = [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ] NEW_LINE def count ( pos , even , odd , tight , num ) : NEW_LINE INDENT if pos == len ( num ) : NEW_LINE INDENT if len ( num ) & 1 : NEW_LINE INDENT odd , even = even , odd NEW_LINE DEDENT d = even - odd NEW_LINE for i in range ( 24 ) : NEW_LINE INDENT if d == prime [ i ] : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT if dp [ pos ] [ even ] [ odd ] [ tight ] != - 1 : NEW_LINE INDENT return dp [ pos ] [ even ] [ odd ] [ tight ] NEW_LINE DEDENT ans = 0 NEW_LINE limit = 9 if tight else num [ pos ] NEW_LINE for d in range ( limit + 1 ) : NEW_LINE INDENT currF = tight NEW_LINE currEven = even NEW_LINE currOdd = odd NEW_LINE if d < num [ pos ] : NEW_LINE INDENT currF = 1 NEW_LINE DEDENT if pos & 1 : NEW_LINE INDENT currOdd += d NEW_LINE DEDENT else : NEW_LINE INDENT currEven += d NEW_LINE DEDENT ans += count ( pos + 1 , currEven , currOdd , currF , num ) NEW_LINE DEDENT dp [ pos ] [ even ] [ odd ] [ tight ] = ans NEW_LINE return dp [ pos ] [ even ] [ odd ] [ tight ] NEW_LINE DEDENT def solve ( x ) : NEW_LINE INDENT global dp NEW_LINE num = [ ] NEW_LINE while x : NEW_LINE INDENT num . append ( x % 10 ) NEW_LINE x //= 10 NEW_LINE DEDENT num . reverse ( ) NEW_LINE dp = [ [ [ [ - 1 , - 1 ] for i in range ( 90 ) ] for j in range ( 90 ) ] for k in range ( M ) ] NEW_LINE return count ( 0 , 0 , 0 , 0 , num ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT dp = [ ] NEW_LINE L = 1 NEW_LINE R = 50 NEW_LINE print ( solve ( R ) - solve ( L - 1 ) ) NEW_LINE L = 50 NEW_LINE R = 100 NEW_LINE print ( solve ( R ) - solve ( L - 1 ) ) NEW_LINE DEDENT
Find the number of distinct pairs of vertices which have a distance of exactly k in a tree | Python3 implementation of the approach ; To store vertices and value of k ; To store number vertices at a level i ; To store the final answer ; Function to add an edge between two nodes ; Function to find the number of distinct pairs of the vertices which have a distance of exactly k in a tree ; At level zero vertex itself is counted ; Count the pair of vertices at distance k ; For all levels count vertices ; Driver code ; Add edges ; Function call ; Required answer
N = 5005 NEW_LINE n , k = 0 , 0 NEW_LINE gr = [ [ ] for i in range ( N ) ] NEW_LINE d = [ [ 0 for i in range ( 505 ) ] for i in range ( N ) ] NEW_LINE ans = 0 NEW_LINE def Add_edge ( x , y ) : NEW_LINE INDENT gr [ x ] . append ( y ) NEW_LINE gr [ y ] . append ( x ) NEW_LINE DEDENT def dfs ( v , par ) : NEW_LINE INDENT global ans NEW_LINE d [ v ] [ 0 ] = 1 NEW_LINE for i in gr [ v ] : NEW_LINE INDENT if ( i != par ) : NEW_LINE INDENT dfs ( i , v ) NEW_LINE for j in range ( 1 , k + 1 ) : NEW_LINE INDENT ans += d [ i ] [ j - 1 ] * d [ v ] [ k - j ] NEW_LINE DEDENT for j in range ( 1 , k + 1 ) : NEW_LINE INDENT d [ v ] [ j ] += d [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT n = 5 NEW_LINE k = 2 NEW_LINE Add_edge ( 1 , 2 ) NEW_LINE Add_edge ( 2 , 3 ) NEW_LINE Add_edge ( 3 , 4 ) NEW_LINE Add_edge ( 2 , 5 ) NEW_LINE dfs ( 1 , 0 ) NEW_LINE print ( ans ) NEW_LINE
Sum of XOR of all subarrays | Function to calculate the Sum of XOR of all subarrays ; variable to store the final Sum ; multiplier ; variable to store number of sub - arrays with odd number of elements with ith bits starting from the first element to the end of the array ; variable to check the status of the odd - even count while calculating c_odd ; loop to calculate initial value of c_odd ; loop to iterate through all the elements of the array and update Sum ; updating the multiplier ; returning the Sum ; Driver Code
def findXorSum ( arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE mul = 1 NEW_LINE for i in range ( 30 ) : NEW_LINE INDENT c_odd = 0 NEW_LINE odd = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) : NEW_LINE INDENT odd = ( ~ odd ) NEW_LINE DEDENT if ( odd ) : NEW_LINE INDENT c_odd += 1 NEW_LINE DEDENT DEDENT for j in range ( n ) : NEW_LINE INDENT Sum += ( mul * c_odd ) NEW_LINE if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) : NEW_LINE INDENT c_odd = ( n - j - c_odd ) NEW_LINE DEDENT DEDENT mul *= 2 NEW_LINE DEDENT return Sum NEW_LINE DEDENT arr = [ 3 , 8 , 13 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findXorSum ( arr , n ) ) NEW_LINE
Minimum replacements to make adjacent characters unequal in a ternary string | Set | Python 3 program to count the minimal replacements such that adjacent characters are unequal ; function to return integer value of i - th character in the string ; Function to count the number of minimal replacements ; If the string has reached the end ; If the state has been visited previously ; Get the current value of character ; If it is equal then change it ; All possible changes ; Change done ; If same no change ; Driver Code ; Length of string ; Create a DP array ; First character ; Function to find minimal replacements
import sys NEW_LINE def charVal ( s , i ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( s [ i ] == '1' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 2 NEW_LINE DEDENT DEDENT def countMinimalReplacements ( s , i , prev , dp , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ prev ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ prev ] NEW_LINE DEDENT val = charVal ( s , i ) NEW_LINE ans = sys . maxsize NEW_LINE if ( val == prev ) : NEW_LINE INDENT val = 0 NEW_LINE for cur in range ( 3 ) : NEW_LINE INDENT if ( cur == prev ) : NEW_LINE INDENT continue NEW_LINE DEDENT val = 1 + countMinimalReplacements ( s , i + 1 , cur , dp , n ) NEW_LINE ans = min ( ans , val ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT ans = countMinimalReplacements ( s , i + 1 , val , dp , n ) NEW_LINE DEDENT dp [ i ] [ val ] = ans NEW_LINE return dp [ i ] [ val ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "201220211" NEW_LINE n = len ( s ) NEW_LINE dp = [ [ - 1 for i in range ( 3 ) ] for i in range ( n ) ] NEW_LINE val = charVal ( s , 0 ) NEW_LINE print ( countMinimalReplacements ( s , 1 , val , dp , n ) ) NEW_LINE DEDENT
Find probability of selecting element from kth column after N iterations | Python3 implementation of the above approach ; Function to calculate probability ; declare dp [ ] [ ] and sum [ ] ; precalculate the first row ; calculate the probability for each element and update dp table ; return result ; Driver code
n = 4 NEW_LINE m = 4 NEW_LINE def calcProbability ( M , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( m ) ] NEW_LINE Sum = [ 0 for i in range ( n ) ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT dp [ 0 ] [ j ] = M [ 0 ] [ j ] NEW_LINE Sum [ 0 ] += dp [ 0 ] [ j ] NEW_LINE DEDENT for i in range ( 1 , m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT dp [ i ] [ j ] += ( dp [ i - 1 ] [ j ] / Sum [ i - 1 ] + M [ i ] [ j ] ) NEW_LINE Sum [ i ] += dp [ i ] [ j ] NEW_LINE DEDENT DEDENT return dp [ n - 1 ] [ k - 1 ] / Sum [ n - 1 ] NEW_LINE DEDENT M = [ [ 1 , 1 , 0 , 3 ] , [ 2 , 3 , 2 , 3 ] , [ 9 , 3 , 0 , 2 ] , [ 2 , 3 , 2 , 2 ] ] NEW_LINE k = 3 NEW_LINE print ( calcProbability ( M , k ) ) NEW_LINE
Possible cuts of a number such that maximum parts are divisible by 3 | Python3 program to find the maximum number of numbers divisible by 3 in a large number ; Function to find the maximum number of numbers divisible by 3 in a large number ; store size of the string ; Stores last index of a remainder ; last visited place of remainder zero is at 0. ; To store result from 0 to i ; get the remainder ; Get maximum res [ i ] value ; Driver Code
import math as mt NEW_LINE def MaximumNumbers ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE remIndex = [ - 1 for i in range ( 3 ) ] NEW_LINE remIndex [ 0 ] = 0 NEW_LINE res = [ - 1 for i in range ( n + 1 ) ] NEW_LINE r = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT r = ( r + ord ( string [ i - 1 ] ) - ord ( '0' ) ) % 3 NEW_LINE res [ i ] = res [ i - 1 ] NEW_LINE if ( remIndex [ r ] != - 1 ) : NEW_LINE INDENT res [ i ] = max ( res [ i ] , res [ remIndex [ r ] ] + 1 ) NEW_LINE DEDENT remIndex [ r ] = i + 1 NEW_LINE DEDENT return res [ n ] NEW_LINE DEDENT s = "12345" NEW_LINE print ( MaximumNumbers ( s ) ) NEW_LINE
Minimum steps required to convert X to Y where a binary matrix represents the possible conversions | Pyton3 implementation of the above approach ; dist [ ] [ ] will be the output matrix that will finally have the shortest distances between every pair of numbers ; Initially same as mat ; Add all numbers one by one to the set of intermediate numbers . Before start of an iteration , we have shortest distances between all pairs of numbers such that the shortest distances consider only the numbers in set { 0 , 1 , 2 , . . k - 1 } as intermediate numbers . After the end of an iteration , vertex no . k is added to the set of intermediate numbers and the set becomes { 0 , 1 , 2 , . . k } ; Pick all numbers as source one by one ; Pick all numbers as destination for the above picked source ; If number k is on the shortest path from i to j , then update the value of dist [ i ] [ j ] ; If no path ; Driver Code
INF = 99999 NEW_LINE size = 10 NEW_LINE def findMinimumSteps ( mat , x , y , n ) : NEW_LINE INDENT dist = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE i , j , k = 0 , 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 0 ) : NEW_LINE INDENT dist [ i ] [ j ] = INF NEW_LINE DEDENT else : NEW_LINE INDENT dist [ i ] [ j ] = 1 NEW_LINE DEDENT if ( i == j ) : NEW_LINE INDENT dist [ i ] [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT for k in range ( n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( dist [ i ] [ k ] + dist [ k ] [ j ] < dist [ i ] [ j ] ) : NEW_LINE INDENT dist [ i ] [ j ] = dist [ i ] [ k ] + dist [ k ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( dist [ x ] [ y ] < INF ) : NEW_LINE INDENT return dist [ x ] [ y ] NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT mat = [ [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] ] NEW_LINE x , y = 2 , 3 NEW_LINE print ( findMinimumSteps ( mat , x , y , size ) ) NEW_LINE
Count number of paths whose weight is exactly X and has at | Python3 program to count the number of paths ; Function to find the number of paths ; If the Summation is more than X ; If exactly X weights have reached ; Already visited ; Count paths ; Traverse in all paths ; If the edge weight is M ; else : Edge 's weight is not M ; Driver Code ; Initialized the DP array with - 1 ; Function to count paths
Max = 4 NEW_LINE c = 2 NEW_LINE def countPaths ( Sum , get , m , n , dp ) : NEW_LINE INDENT if ( Sum < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( Sum == 0 ) : NEW_LINE INDENT return get NEW_LINE DEDENT if ( dp [ Sum ] [ get ] != - 1 ) : NEW_LINE INDENT return dp [ Sum ] [ get ] NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i == m ) : NEW_LINE INDENT res += countPaths ( Sum - i , 1 , m , n , dp ) NEW_LINE res += countPaths ( Sum - i , get , m , n , dp ) NEW_LINE DEDENT DEDENT dp [ Sum ] [ get ] = res NEW_LINE return dp [ Sum ] [ get ] NEW_LINE DEDENT n = 3 NEW_LINE m = 2 NEW_LINE x = 3 NEW_LINE dp = [ [ - 1 for i in range ( 2 ) ] for i in range ( Max + 1 ) ] NEW_LINE for i in range ( Max + 1 ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT print ( countPaths ( x , 0 , m , n , dp ) ) NEW_LINE
Minimum Operations to make value of all vertices of the tree Zero | A utility function to add an edge in an undirected graph ; A utility function to print the adjacency list representation of graph ; Utility Function for findMinOperation ( ) ; Base Case for current node ; Iterate over the adjacency list for src ; calculate DP table for each child V ; Number of Increase Type operations for node src is equal to maximum of number of increase operations required by each of its child ; Number of Decrease Type operations for node src is equal to maximum of number of decrease operations required by each of its child ; After performing operations for subtree rooted at src A [ src ] changes by the net difference of increase and decrease type operations ; for negative value of node src ; Returns the minimum operations required to make value of all vertices equal to zero , uses findMinOperationUtil ( ) ; Initialise DP table ; find dp [ 1 ] [ 0 ] and dp [ 1 ] [ 1 ] ; Driver code ; Build the Graph / Tree
def addEdge ( adj , u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def printGraph ( adj , V ) : NEW_LINE INDENT for v in range ( 0 , V ) : NEW_LINE INDENT print ( " Adjacency ▁ list ▁ of ▁ vertex " , v ) NEW_LINE print ( " head " , end = " ▁ " ) NEW_LINE for x in adj [ v ] : NEW_LINE INDENT print ( " - > " , x , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def findMinOperationUtil ( dp , adj , A , src , parent ) : NEW_LINE INDENT dp [ src ] [ 0 ] = dp [ src ] [ 1 ] = 0 NEW_LINE for V in adj [ src ] : NEW_LINE INDENT if V == parent : NEW_LINE INDENT continue NEW_LINE DEDENT findMinOperationUtil ( dp , adj , A , V , src ) NEW_LINE dp [ src ] [ 0 ] = max ( dp [ src ] [ 0 ] , dp [ V ] [ 0 ] ) NEW_LINE dp [ src ] [ 1 ] = max ( dp [ src ] [ 1 ] , dp [ V ] [ 1 ] ) NEW_LINE DEDENT A [ src - 1 ] += dp [ src ] [ 0 ] - dp [ src ] [ 1 ] NEW_LINE if A [ src - 1 ] > 0 : NEW_LINE INDENT dp [ src ] [ 1 ] += A [ src - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ src ] [ 0 ] += abs ( A [ src - 1 ] ) NEW_LINE DEDENT DEDENT def findMinOperation ( adj , A , V ) : NEW_LINE INDENT dp = [ [ 0 , 0 ] for i in range ( V + 1 ) ] NEW_LINE findMinOperationUtil ( dp , adj , A , 1 , 0 ) NEW_LINE minOperations = dp [ 1 ] [ 0 ] + dp [ 1 ] [ 1 ] NEW_LINE return minOperations NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT V = 5 NEW_LINE adj = [ [ ] for i in range ( V + 1 ) ] NEW_LINE addEdge ( adj , 1 , 2 ) NEW_LINE addEdge ( adj , 1 , 3 ) NEW_LINE A = [ 1 , - 1 , 1 ] NEW_LINE minOperations = findMinOperation ( adj , A , V ) NEW_LINE print ( minOperations ) NEW_LINE DEDENT
Sum of kth powers of first n natural numbers | global array to store factorials ; function to calculate the factorials of all the numbers upto k ; function to return the binomial coeff ; nCr = ( n ! * ( n - r ) ! ) / r ! ; function to return the sum of the kth powers of n natural numbers ; when j is 1 ; calculating sum ( n ^ 1 ) of unity powers of n storing sum ( n ^ 1 ) for sum ( n ^ 2 ) ; if k == 1 then temp is the result ; for finding sum ( n ^ k ) removing 1 and n * KCk from ( n + 1 ) ^ k ; Removing all kC2 * sum ( n ^ ( k - 2 ) ) + ... + kCk - 1 * ( sum ( n ^ ( k - ( k - 1 ) ) ; storing the result for next sum of next powers of k ; Driver code
MAX_K = 15 NEW_LINE fac = [ 1 for i in range ( MAX_K ) ] NEW_LINE def factorial ( k ) : NEW_LINE INDENT fac [ 0 ] = 1 NEW_LINE for i in range ( 1 , k + 2 ) : NEW_LINE INDENT fac [ i ] = ( i * fac [ i - 1 ] ) NEW_LINE DEDENT DEDENT def bin ( a , b ) : NEW_LINE INDENT ans = fac [ a ] // ( fac [ a - b ] * fac [ b ] ) NEW_LINE return ans NEW_LINE DEDENT def sumofn ( n , k ) : NEW_LINE INDENT p = 0 NEW_LINE num1 , temp = 1 , 1 NEW_LINE arr = [ 1 for i in range ( 1000 ) ] NEW_LINE for j in range ( 1 , k + 1 ) : NEW_LINE INDENT if j == 1 : NEW_LINE INDENT num1 = ( n * ( n + 1 ) ) // 2 NEW_LINE arr [ p ] = num1 NEW_LINE p += 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp = pow ( n + 1 , j + 1 ) - 1 - n NEW_LINE for s in range ( 1 , j ) : NEW_LINE INDENT temp = temp - ( arr [ j - s - 1 ] * bin ( j + 1 , s + 1 ) ) NEW_LINE DEDENT temp = temp // ( j + 1 ) NEW_LINE arr [ p ] = temp NEW_LINE p += 1 NEW_LINE DEDENT DEDENT temp = arr [ p - 1 ] NEW_LINE return temp NEW_LINE DEDENT n , k = 5 , 2 NEW_LINE factorial ( k ) NEW_LINE print ( sumofn ( n , k ) ) NEW_LINE
Ways to fill N positions using M colors such that there are exactly K pairs of adjacent different colors | Python 3 implementation of the approach ; Recursive function to find the required number of ways ; When all positions are filled ; If adjacent pairs are exactly K ; If already calculated ; Next position filled with same color ; Next position filled with different color So there can be m - 1 different colors ; Driver Code
max = 4 NEW_LINE def countWays ( index , cnt , dp , n , m , k ) : NEW_LINE INDENT if ( index == n ) : NEW_LINE INDENT if ( cnt == k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( dp [ index ] [ cnt ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ cnt ] NEW_LINE DEDENT ans = 0 NEW_LINE ans += countWays ( index + 1 , cnt , dp , n , m , k ) NEW_LINE ans += ( m - 1 ) * countWays ( index + 1 , cnt + 1 , dp , n , m , k ) NEW_LINE dp [ index ] [ cnt ] = ans NEW_LINE return dp [ index ] [ cnt ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE m = 3 NEW_LINE k = 2 NEW_LINE dp = [ [ - 1 for x in range ( n + 1 ) ] for y in range ( max ) ] NEW_LINE print ( m * countWays ( 1 , 0 , dp , n , m , k ) ) NEW_LINE DEDENT
Number of balanced bracket expressions that can be formed from a string | Max string length ; Function to check whether index start and end can form a bracket pair or not ; Check for brackets ( ) ; Check for brackets [ ] ; Check for brackets { } ; Function to find number of proper bracket expressions ; If starting index is greater than ending index ; If dp [ start ] [ end ] has already been computed ; Search for the bracket in from next index ; If bracket pair is formed , add number of combination ; If ? comes then all three bracket expressions are possible ; Return answer ; If n is odd , string cannot be balanced ; Driver Code
MAX = 300 NEW_LINE def checkFunc ( i , j , st ) : NEW_LINE INDENT if ( st [ i ] == ' ( ' and st [ j ] == ' ) ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( st [ i ] == ' ( ' and st [ j ] == ' ? ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( st [ i ] == ' ? ' and st [ j ] == ' ) ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( st [ i ] == ' [ ' and st [ j ] == ' ] ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( st [ i ] == ' [ ' and st [ j ] == ' ? ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( st [ i ] == ' ? ' and st [ j ] == ' ] ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( st [ i ] == ' { ' and st [ j ] == ' } ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( st [ i ] == ' { ' and st [ j ] == ' ? ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( st [ i ] == ' ? ' and st [ j ] == ' } ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def countRec ( start , end , dp , st ) : NEW_LINE INDENT sum = 0 NEW_LINE if ( start > end ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ start ] [ end ] != - 1 ) : NEW_LINE INDENT return dp [ start ] [ end ] NEW_LINE DEDENT r = 0 NEW_LINE for i in range ( start + 1 , end + 1 , 2 ) : NEW_LINE INDENT if ( checkFunc ( start , i , st ) ) : NEW_LINE INDENT sum = ( sum + countRec ( start + 1 , i - 1 , dp , st ) * countRec ( i + 1 , end , dp , st ) ) NEW_LINE DEDENT elif ( st [ start ] == ' ? ' and st [ i ] == ' ? ' ) : NEW_LINE INDENT sum = ( sum + countRec ( start + 1 , i - 1 , dp , st ) * countRec ( i + 1 , end , dp , st ) * 3 ) NEW_LINE DEDENT DEDENT dp [ start ] [ end ] = sum NEW_LINE return dp [ start ] [ end ] NEW_LINE DEDENT def countWays ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE if ( n % 2 == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT dp = [ [ - 1 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE return countRec ( 0 , n - 1 , dp , st ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " ( ? ( [ ? ) ] ? } ? " NEW_LINE print ( countWays ( st ) ) NEW_LINE DEDENT
Count pairs ( A , B ) such that A has X and B has Y number of set bits and A + B = C | Initial DP array ; Recursive function to generate all combinations of bits ; if the state has already been visited ; find if C has no more set bits on left ; if no set bits are left for C and there are no set bits for A and B and the carry is 0 , then this combination is possible ; if no set bits are left for C and requirement of set bits for A and B have exceeded ; Find if the bit is 1 or 0 at third index to the left ; carry = 1 and bit set = 1 ; since carry is 1 , and we need 1 at C 's bit position we can use 0 and 0 or 1 and 1 at A and B bit position ; carry = 0 and bit set = 1 ; since carry is 0 , and we need 1 at C 's bit position we can use 1 and 0 or 0 and 1 at A and B bit position ; carry = 1 and bit set = 0 ; since carry is 1 , and we need 0 at C 's bit position we can use 1 and 0 or 0 and 1 at A and B bit position ; carry = 0 and bit set = 0 ; since carry is 0 , and we need 0 at C 's bit position we can use 0 and 0 or 1 and 1 at A and B bit position ; Function to count ways ; function call that returns the answer ; Driver Code
dp = [ [ [ [ - 1 , - 1 ] for i in range ( 64 ) ] for j in range ( 64 ) ] for k in range ( 64 ) ] NEW_LINE def func ( third , seta , setb , carry , number ) : NEW_LINE INDENT if dp [ third ] [ seta ] [ setb ] [ carry ] != - 1 : NEW_LINE INDENT return dp [ third ] [ seta ] [ setb ] [ carry ] NEW_LINE DEDENT shift = number >> third NEW_LINE if ( shift == 0 and seta == 0 and setb == 0 and carry == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( shift == 0 or seta < 0 or setb < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT mask = shift & 1 NEW_LINE dp [ third ] [ seta ] [ setb ] [ carry ] = 0 NEW_LINE if ( mask ) and carry : NEW_LINE INDENT dp [ third ] [ seta ] [ setb ] [ carry ] += func ( third + 1 , seta , setb , 0 , number ) + func ( third + 1 , seta - 1 , setb - 1 , 1 , number ) NEW_LINE DEDENT elif mask and not carry : NEW_LINE INDENT dp [ third ] [ seta ] [ setb ] [ carry ] += func ( third + 1 , seta - 1 , setb , 0 , number ) + func ( third + 1 , seta , setb - 1 , 0 , number ) NEW_LINE DEDENT elif not mask and carry : NEW_LINE INDENT dp [ third ] [ seta ] [ setb ] [ carry ] += func ( third + 1 , seta - 1 , setb , 1 , number ) + func ( third + 1 , seta , setb - 1 , 1 , number ) NEW_LINE DEDENT elif not mask and not carry : NEW_LINE INDENT dp [ third ] [ seta ] [ setb ] [ carry ] += func ( third + 1 , seta , setb , 0 , number ) + func ( third + 1 , seta - 1 , setb - 1 , 1 , number ) NEW_LINE DEDENT return dp [ third ] [ seta ] [ setb ] [ carry ] NEW_LINE DEDENT def possibleSwaps ( a , b , c ) : NEW_LINE INDENT ans = func ( 0 , a , b , 0 , c ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x , y , c = 2 , 2 , 20 NEW_LINE print ( possibleSwaps ( x , y , c ) ) NEW_LINE DEDENT
Sum of Fibonacci numbers at even indexes upto N terms | Computes value of first fibonacci numbers and stores the even - indexed sum ; Initialize result ; Add remaining terms ; For even indices ; Return the alternting sum ; Driver code ; Get n ; Find the even - indiced sum
def calculateEvenSum ( n ) : NEW_LINE INDENT if n <= 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT fibo = [ 0 ] * ( 2 * n + 1 ) NEW_LINE fibo [ 0 ] , fibo [ 1 ] = 0 , 1 NEW_LINE sum = 0 NEW_LINE for i in range ( 2 , 2 * n + 1 ) : NEW_LINE INDENT fibo [ i ] = fibo [ i - 1 ] + fibo [ i - 2 ] NEW_LINE if i % 2 == 0 : NEW_LINE INDENT sum += fibo [ i ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 8 NEW_LINE print ( " Even ▁ indexed ▁ Fibonacci ▁ Sum ▁ upto " , n , " terms : " , calculateEvenSum ( n ) ) NEW_LINE DEDENT
Sum of Fibonacci numbers at even indexes upto N terms | Python3 Program to find even indexed Fibonacci Sum in O ( Log n ) time . ; Create an array for memoization ; Returns n 'th Fibonacci number using table f[] ; Base cases ; If fib ( n ) is already computed ; Applying above formula [ Note value n & 1 is 1 if n is odd , else 0 ] . ; Computes value of even - indexed Fibonacci Sum ; Driver Code ; Get n ; Find the alternating sum
MAX = 1000 ; NEW_LINE f = [ 0 ] * MAX ; NEW_LINE def fib ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n == 1 or n == 2 ) : NEW_LINE INDENT f [ n ] = 1 ; NEW_LINE return f [ n ] ; NEW_LINE DEDENT if ( f [ n ] ) : NEW_LINE INDENT return f [ n ] ; NEW_LINE DEDENT k = ( n + 1 ) // 2 if ( n % 2 == 1 ) else n // 2 ; NEW_LINE f [ n ] = ( fib ( k ) * fib ( k ) + fib ( k - 1 ) * fib ( k - 1 ) ) if ( n % 2 == 1 ) else ( 2 * fib ( k - 1 ) + fib ( k ) ) * fib ( k ) ; NEW_LINE return f [ n ] ; NEW_LINE DEDENT def calculateEvenSum ( n ) : NEW_LINE INDENT return ( fib ( 2 * n + 1 ) - 1 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 8 ; NEW_LINE print ( " Even ▁ indexed ▁ Fibonacci ▁ Sum ▁ upto " , n , " terms : " , calculateEvenSum ( n ) ) ; NEW_LINE DEDENT
Gould 's Sequence | 32768 = 2 ^ 15 ; Array to store Sequence up to 2 ^ 16 = 65536 ; Utility function to pre - compute odd numbers in ith row of Pascals 's triangle ; First term of the Sequence is 1 ; Initialize i to 1 ; Initialize p to 1 ( i . e 2 ^ i ) in each iteration i will be pth power of 2 ; loop to generate gould 's Sequence ; i is pth power of 2 traverse the array from j = 0 to i i . e ( 2 ^ p ) ; double the value of arr [ j ] and store to arr [ i + j ] ; update i to next power of 2 ; increment p ; Function to print gould 's Sequence ; loop to generate gould 's Sequence up to n ; Driver code ; Get n ; Function call
MAX = 32768 NEW_LINE arr = [ None ] * ( 2 * MAX ) NEW_LINE def gouldSequence ( ) : NEW_LINE INDENT arr [ 0 ] = 1 NEW_LINE i = 1 NEW_LINE p = 1 NEW_LINE while i <= MAX : NEW_LINE INDENT j = 0 NEW_LINE while j < i : NEW_LINE INDENT arr [ i + j ] = 2 * arr [ j ] NEW_LINE j += 1 NEW_LINE DEDENT i = ( 1 << p ) NEW_LINE p += 1 NEW_LINE DEDENT DEDENT def printSequence ( n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT gouldSequence ( ) NEW_LINE n = 16 NEW_LINE printSequence ( n ) NEW_LINE DEDENT
Count the number of ways to traverse a Matrix | Find factorial ; Find number of ways to reach mat [ m - 1 ] [ n - 1 ] from mat [ 0 ] [ 0 ] in a matrix mat [ ] [ ] ] ; Driver code ; Function call
def factorial ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res *= i NEW_LINE DEDENT return res NEW_LINE DEDENT def countWays ( m , n ) : NEW_LINE INDENT m = m - 1 NEW_LINE n = n - 1 NEW_LINE return ( factorial ( m + n ) // ( factorial ( m ) * factorial ( n ) ) ) NEW_LINE DEDENT m = 5 NEW_LINE n = 5 NEW_LINE result = countWays ( m , n ) NEW_LINE print ( result ) NEW_LINE
Matrix Chain Multiplication ( A O ( N ^ 2 ) Solution ) | Matrix Mi has dimension p [ i - 1 ] x p [ i ] for i = 1. . n ; For simplicity of the program , one extra row and one extra column are allocated in dp [ ] [ ] . 0 th row and 0 th column of dp [ ] [ ] are not used ; cost is zero when multiplying one matrix . ; Simply following above recursive formula . ; Driver code
def MatrixChainOrder ( p , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] [ i ] = 0 NEW_LINE DEDENT for L in range ( 1 , n - 1 ) : NEW_LINE INDENT for i in range ( n - L ) : NEW_LINE INDENT dp [ i ] [ i + L ] = min ( dp [ i + 1 ] [ i + L ] + p [ i - 1 ] * p [ i ] * p [ i + L ] , dp [ i ] [ i + L - 1 ] + p [ i - 1 ] * p [ i + L - 1 ] * p [ i + L ] ) NEW_LINE DEDENT DEDENT return dp [ 1 ] [ n - 1 ] NEW_LINE DEDENT arr = [ 10 , 20 , 30 , 40 , 30 ] NEW_LINE size = len ( arr ) NEW_LINE print ( " Minimum ▁ number ▁ of ▁ multiplications ▁ is " , MatrixChainOrder ( arr , size ) ) NEW_LINE
Count common subsequence in two strings | return the number of common subsequence in two strings ; for each character of S ; for each character in T ; if character are same in both the string ; Driver Code
def CommomSubsequencesCount ( s , t ) : NEW_LINE INDENT n1 = len ( s ) NEW_LINE n2 = len ( t ) NEW_LINE dp = [ [ 0 for i in range ( n2 + 1 ) ] for i in range ( n1 + 1 ) ] NEW_LINE for i in range ( 1 , n1 + 1 ) : NEW_LINE INDENT for j in range ( 1 , n2 + 1 ) : NEW_LINE INDENT if ( s [ i - 1 ] == t [ j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] = ( 1 + dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ j ] - dp [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n1 ] [ n2 ] NEW_LINE DEDENT s = " ajblqcpdz " NEW_LINE t = " aefcnbtdi " NEW_LINE print ( CommomSubsequencesCount ( s , t ) ) NEW_LINE
Minimum number of palindromes required to express N as a sum | Set 2 | A utility for creating palindrome ; checks if number of digits is odd or even if odd then neglect the last digit of _input in finding reverse as in case of odd number of digits middle element occur once ; Creates palindrome by just appending reverse of number to itself ; Function to generate palindromes ; Run two times for odd and even length palindromes ; Creates palindrome numbers with first half as i . Value of j decides whether we need an odd length or even length palindrome . ; Function to find the minimum number of palindromes required to express N as a sum ; Checking if the number is a palindrome ; Getting the list of all palindromes upto N ; Sorting the list of palindromes ; The answer is three if the control reaches till this point ; Driver code
def createPalindrome ( _input , isOdd ) : NEW_LINE INDENT n = palin = _input NEW_LINE if isOdd : NEW_LINE INDENT n //= 10 NEW_LINE DEDENT while n > 0 : NEW_LINE INDENT palin = palin * 10 + ( n % 10 ) NEW_LINE n //= 10 NEW_LINE DEDENT return palin NEW_LINE DEDENT def generatePalindromes ( N ) : NEW_LINE INDENT palindromes = [ ] NEW_LINE for j in range ( 0 , 2 ) : NEW_LINE INDENT i = 1 NEW_LINE number = createPalindrome ( i , j ) NEW_LINE while number <= N : NEW_LINE INDENT palindromes . append ( number ) NEW_LINE i += 1 NEW_LINE number = createPalindrome ( i , j ) NEW_LINE DEDENT DEDENT return palindromes NEW_LINE DEDENT def minimumNoOfPalindromes ( N ) : NEW_LINE INDENT b = a = str ( N ) NEW_LINE b = b [ : : - 1 ] NEW_LINE if a == b : NEW_LINE INDENT return 1 NEW_LINE DEDENT palindromes = generatePalindromes ( N ) NEW_LINE palindromes . sort ( ) NEW_LINE l , r = 0 , len ( palindromes ) - 1 NEW_LINE while l < r : NEW_LINE INDENT if palindromes [ l ] + palindromes [ r ] == N : NEW_LINE INDENT return 2 NEW_LINE DEDENT elif palindromes [ l ] + palindromes [ r ] < N : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT r -= 1 NEW_LINE DEDENT DEDENT return 3 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 65 NEW_LINE print ( minimumNoOfPalindromes ( N ) ) NEW_LINE DEDENT
Minimum Cost to make two Numeric Strings Identical | Function to find weight of LCS ; if this state is already calculated then return ; adding required weight for particular match ; recurse for left and right child and store the max ; Function to calculate cost of string ; Driver code ; Minimum cost needed to make two strings identical
def lcs ( dp , a , b , m , n ) : NEW_LINE INDENT for i in range ( 100 ) : NEW_LINE INDENT for j in range ( 100 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT if ( m < 0 or n < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ m ] [ n ] != - 1 ) : NEW_LINE INDENT return dp [ m ] [ n ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( a [ m ] == b [ n ] ) : NEW_LINE INDENT ans = ( ord ( a [ m ] ) - 48 ) + lcs ( dp , a , b , m - 1 , n - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = max ( lcs ( dp , a , b , m - 1 , n ) , lcs ( dp , a , b , m , n - 1 ) ) NEW_LINE DEDENT dp [ m ] [ n ] = ans NEW_LINE return ans NEW_LINE DEDENT def costOfString ( s ) : NEW_LINE INDENT cost = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT cost += ( ord ( s [ i ] ) - 48 ) NEW_LINE DEDENT return cost NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = "9142" NEW_LINE b = "1429" NEW_LINE dp = [ [ 0 for x in range ( 101 ) ] for y in range ( 101 ) ] NEW_LINE print ( costOfString ( a ) + costOfString ( b ) - 2 * lcs ( dp , a , b , len ( a ) - 1 , len ( b ) - 1 ) ) NEW_LINE DEDENT
Sum of elements of all partitions of number such that no element is less than K | Function that returns total number of valid partitions of integer N ; Global declaration of 2D dp array which will be later used for memoization ; Initializing 2D dp array with - 1 we will use this 2D array for memoization ; If this subproblem is already previously calculated , then directly return that answer ; If N < K , then no valid partition is possible ; If N is between K to 2 * K then there is only one partition and that is the number N itself ; Initialize answer with 1 as the number N itself is always a valid partition ; For loop to iterate over K to N and find number of possible valid partitions recursively . ; Memoization is done by storing this calculated answer ; Returning number of valid partitions ; Driver code ; Printing total number of valid partitions
def countPartitions ( n , k ) : NEW_LINE INDENT dp = [ [ 0 ] * 201 ] * 201 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT if ( dp [ n ] [ k ] >= 0 ) : NEW_LINE INDENT return dp [ n ] [ k ] NEW_LINE DEDENT if ( n < k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n < 2 * k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT answer = 1 NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT answer = ( answer + countPartitions ( n - i , i ) ) NEW_LINE DEDENT dp [ n ] [ k ] = answer NEW_LINE return answer NEW_LINE DEDENT n = 10 NEW_LINE k = 3 NEW_LINE print ( " Total ▁ Aggregate ▁ sum ▁ of ▁ all ▁ " " Valid ▁ Partitions : ▁ " , countPartitions ( n , k ) * n ) NEW_LINE
Number of Co | Python3 program to count the pairs whose sum of digits is co - prime ; Function to find the elements after doing the sum of digits ; Traverse from a to b ; Find the sum of the digits of the elements in the given range one by one ; Function to count the co - prime pairs ; Function to make the pairs by doing the sum of digits ; Count pairs that are co - primes ; Driver code ; Function to count the pairs
from math import gcd NEW_LINE def makePairs ( pairs , a , b ) : NEW_LINE INDENT for i in range ( a , b + 1 , 1 ) : NEW_LINE INDENT sumOfDigits = 0 NEW_LINE k = i NEW_LINE while ( k > 0 ) : NEW_LINE INDENT sumOfDigits += k % 10 NEW_LINE k = int ( k / 10 ) NEW_LINE DEDENT if ( sumOfDigits <= 162 ) : NEW_LINE INDENT pairs . append ( sumOfDigits ) NEW_LINE DEDENT DEDENT DEDENT def countCoPrime ( a , b ) : NEW_LINE INDENT pairs = [ ] NEW_LINE makePairs ( pairs , a , b ) NEW_LINE count = 0 NEW_LINE for i in range ( 0 , len ( pairs ) , 1 ) : NEW_LINE INDENT for j in range ( i + 1 , len ( pairs ) , 1 ) : NEW_LINE INDENT if ( gcd ( pairs [ i ] , pairs [ j ] ) == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 12 NEW_LINE b = 15 NEW_LINE print ( countCoPrime ( a , b ) ) NEW_LINE DEDENT
Number of Co | Python3 program to count the pairs whose sum of digits is co - prime ; Recursive function to return the frequency of numbers having their sum of digits i ; Returns 1 or 0 ; Returns value of the dp if already stored ; Loop from digit 0 to 9 ; To change the tight to 1 ; Calling the recursive function to find the frequency ; Function to find out frequency of numbers from 1 to N having their sum of digits from 1 to 162 and store them in array ; Number to string conversion ; Calling the recursive function and pushing it into array ; Function to find the pairs ; Calling the formArray function of a - 1 numbers ; Calling the formArray function of b numbers ; Subtracting the frequency of higher number array with lower number array and thus finding the range of numbers from a to b having sum from 1 to 162 ; To find out total number of pairs which are co - prime ; Driver code ; Function to count the pairs
import math NEW_LINE def recursive ( idx , sum , tight , st , dp , num ) : NEW_LINE INDENT if ( idx == num ) : NEW_LINE INDENT return sum == 0 NEW_LINE DEDENT if ( dp [ idx ] [ tight ] [ sum ] != - 1 ) : NEW_LINE INDENT return dp [ idx ] [ tight ] [ sum ] NEW_LINE DEDENT ans = 0 NEW_LINE for d in range ( 10 ) : NEW_LINE INDENT newTight = False NEW_LINE if ( tight and ord ( st [ idx ] ) - ord ( '0' ) < d ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( tight and ord ( st [ idx ] ) - ord ( '0' ) == d ) : NEW_LINE INDENT newTight = True NEW_LINE DEDENT if ( sum >= d ) : NEW_LINE INDENT ans += recursive ( idx + 1 , sum - d , newTight , st , dp , num ) NEW_LINE DEDENT DEDENT dp [ idx ] [ tight ] [ sum ] = ans NEW_LINE return dp [ idx ] [ tight ] [ sum ] NEW_LINE DEDENT def formArray ( N ) : NEW_LINE INDENT dp = [ [ [ - 1 for x in range ( 166 ) ] for y in range ( 2 ) ] for z in range ( 20 ) ] NEW_LINE st = str ( N ) NEW_LINE num = len ( st ) NEW_LINE arr = [ ] NEW_LINE for i in range ( 1 , 163 ) : NEW_LINE INDENT arr . append ( recursive ( 0 , i , 1 , st , dp , num ) ) NEW_LINE DEDENT return arr NEW_LINE DEDENT def findPair ( a , b ) : NEW_LINE INDENT arr_smaller = formArray ( a - 1 ) NEW_LINE arr_greater = formArray ( b ) NEW_LINE for i in range ( len ( arr_greater ) ) : NEW_LINE INDENT arr_greater [ i ] -= arr_smaller [ i ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 1 , 163 ) : NEW_LINE INDENT for j in range ( i + 1 , 163 ) : NEW_LINE INDENT if ( math . gcd ( i , j ) == 1 ) : NEW_LINE INDENT ans = ( ans + arr_greater [ i - 1 ] * arr_greater [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 12 NEW_LINE b = 15 NEW_LINE print ( findPair ( a , b ) ) NEW_LINE DEDENT
Semiperfect Number | Python3 program to check if the number is semi - perfect or not ; code to find all the factors of the number excluding the number itself ; vector to store the factors ; note that this loop runs till sqrt ( n ) ; if the value of i is a factor ; condition to check the divisor is not the number itself ; return the vector ; Function to check if the number is semi - perfect or not ; find the divisors ; sorting the vector ; subset to check if no is semiperfect ; initialising 1 st column to true ; initializing 1 st row except zero position to 0 ; loop to find whether the number is semiperfect ; calculation to check if the number can be made by summation of divisors ; if not possible to make the number by any combination of divisors ; Driver Code
import math NEW_LINE def factors ( n ) : NEW_LINE INDENT v = [ ] NEW_LINE v . append ( 1 ) NEW_LINE sqt = int ( math . sqrt ( n ) ) NEW_LINE for i in range ( 2 , sqt + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE if ( n // i != i ) : NEW_LINE INDENT v . append ( n // i ) NEW_LINE DEDENT DEDENT DEDENT return v NEW_LINE DEDENT def check ( n ) : NEW_LINE INDENT v = [ ] NEW_LINE v = factors ( n ) NEW_LINE v . sort ( ) NEW_LINE r = len ( v ) NEW_LINE subset = [ [ 0 for i in range ( n + 1 ) ] for j in range ( r + 1 ) ] NEW_LINE for i in range ( r + 1 ) : NEW_LINE INDENT subset [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT subset [ 0 ] [ i ] = False NEW_LINE DEDENT for i in range ( 1 , r + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( j < v [ i - 1 ] ) : NEW_LINE INDENT subset [ i ] [ j ] = subset [ i - 1 ] [ j ] ; NEW_LINE DEDENT else : NEW_LINE INDENT subset [ i ] [ j ] = ( subset [ i - 1 ] [ j ] or subset [ i - 1 ] [ j - v [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT if ( ( subset [ r ] [ n ] ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 40 NEW_LINE if ( check ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT