text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Find the Side of the smallest Square that can contain given 4 Big Squares | Function to find the maximum of two values ; Function to find the smallest side of the suitable suitcase ; sort array to find the smallest and largest side of suitcases ; side of the suitcase will be smallest if they arranged in 2 x 2 way so find all possible sides of that arrangement ; since suitcase should be square so find maximum of all four side ; now find greatest side and that will be the smallest square ; return the result ; Driver Code ; Get the side of the 4 small squares ; Find the smallest side ; Get the side of the 4 small squares ; Find the smallest side
def max ( a , b ) : NEW_LINE INDENT if ( a > b ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return b NEW_LINE DEDENT DEDENT def smallestSide ( a ) : NEW_LINE INDENT a . sort ( reverse = False ) NEW_LINE side1 = a [ 0 ] + a [ 3 ] NEW_LINE side2 = a [ 1 ] + a [ 2 ] NEW_LINE side3 = a [ 0 ] + a [ 1 ] NEW_LINE side4 = a [ 2 ] + a [ 3 ] NEW_LINE side11 = max ( side1 , side2 ) NEW_LINE side12 = max ( side3 , side4 ) NEW_LINE sideOfSquare = max ( side11 , side12 ) NEW_LINE return sideOfSquare NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT side = [ 0 for i in range ( 4 ) ] NEW_LINE print ( " Test ▁ Case ▁ 1" ) NEW_LINE side [ 0 ] = 2 NEW_LINE side [ 1 ] = 2 NEW_LINE side [ 2 ] = 2 NEW_LINE side [ 3 ] = 2 NEW_LINE print ( smallestSide ( side ) ) NEW_LINE print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE print ( " Test ▁ Case ▁ 2" ) NEW_LINE side [ 0 ] = 100000000000000 NEW_LINE side [ 1 ] = 123450000000000 NEW_LINE side [ 2 ] = 987650000000000 NEW_LINE side [ 3 ] = 987654321000000 NEW_LINE print ( smallestSide ( side ) ) NEW_LINE DEDENT
Rectangle with minimum possible difference between the length and the width | Python3 implementation of the approach ; Function to print the length ( l ) and breadth ( b ) of the rectangle having area = N and | l - b | as minimum as possible ; i is a factor ; l >= sqrt ( area ) >= i ; so here l is + ve always ; Here l and b are length and breadth of the rectangle ; Driver code
import math as mt NEW_LINE def find_rectangle ( area ) : NEW_LINE INDENT l , b = 0 , 0 NEW_LINE M = mt . ceil ( mt . sqrt ( area ) ) NEW_LINE ans = 0 NEW_LINE for i in range ( M , 0 , - 1 ) : NEW_LINE INDENT if ( area % i == 0 ) : NEW_LINE INDENT l = ( area // i ) NEW_LINE b = i NEW_LINE break NEW_LINE DEDENT DEDENT print ( " l ▁ = " , l , " , ▁ b ▁ = " , b ) NEW_LINE DEDENT area = 99 NEW_LINE find_rectangle ( area ) NEW_LINE
Rectangle with minimum possible difference between the length and the width | Python3 implementation of the approach ; Function to print the length ( l ) and breadth ( b ) of the rectangle having area = N and | l - b | as minimum as possible ; Driver code
import math NEW_LINE def find_rectangle ( area ) : NEW_LINE INDENT for i in range ( int ( math . ceil ( math . sqrt ( area ) ) ) , area + 1 ) : NEW_LINE INDENT if ( ( int ( area / i ) * i ) == area ) : NEW_LINE INDENT print ( i , int ( area / i ) ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT area = 99 NEW_LINE find_rectangle ( area ) NEW_LINE
Largest sub | Python3 implementation of the approach ; Function to return the size of the required sub - set ; Sort the array ; Set to store the contents of the required sub - set ; Insert the elements satisfying the conditions ; Return the size of the set ; Driver code
import math as mt NEW_LINE def sizeSubSet ( a , k , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % k != 0 or a [ i ] // k not in s ) : NEW_LINE INDENT s . add ( a [ i ] ) NEW_LINE DEDENT DEDENT return len ( s ) NEW_LINE DEDENT a = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] NEW_LINE n = len ( a ) NEW_LINE k = 2 NEW_LINE print ( sizeSubSet ( a , k , n ) ) NEW_LINE
Minimum number of sets with numbers less than Y | Python3 program to find the minimum number sets with consecutive numbers and less than Y ; Function to find the minimum number of shets ; Variable to count the number of sets ; Iterate in the string ; Add the number to string ; Mark that we got a number ; Check if previous was anytime less than Y ; Current number ; Check for current number ; Check for last added number ; Driver Code
import math as mt NEW_LINE def minimumSets ( s , y ) : NEW_LINE INDENT cnt = 0 NEW_LINE num = 0 NEW_LINE l = len ( s ) NEW_LINE f = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT num = num * 10 + ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE if ( num <= y ) : NEW_LINE INDENT f = 1 NEW_LINE if ( f ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT num = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE f = 0 NEW_LINE if ( num <= y ) : NEW_LINE INDENT f = 1 NEW_LINE DEDENT else : NEW_LINE INDENT num = 0 NEW_LINE DEDENT DEDENT DEDENT if ( f ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT return cnt NEW_LINE DEDENT s = "1234" NEW_LINE y = 30 NEW_LINE print ( minimumSets ( s , y ) ) NEW_LINE
Find the non decreasing order array from given array | Python 3 implementation of the approach ; Utility function to print the contents of the array ; Function to build array B [ ] ; Lower and upper limits ; To store the required array ; Apply greedy approach ; Print the built array b [ ] ; Driver code
import sys NEW_LINE def printArr ( b , n ) : NEW_LINE INDENT for i in range ( 0 , n , 1 ) : NEW_LINE INDENT print ( b [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def ModifiedArray ( a , n ) : NEW_LINE INDENT l = 0 NEW_LINE r = sys . maxsize NEW_LINE b = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( 0 , int ( n / 2 ) , 1 ) : NEW_LINE INDENT b [ i ] = max ( l , a [ i ] - r ) NEW_LINE b [ n - i - 1 ] = a [ i ] - b [ i ] NEW_LINE l = b [ i ] NEW_LINE r = b [ n - i - 1 ] NEW_LINE DEDENT printArr ( b , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 5 , 6 ] NEW_LINE n = len ( a ) NEW_LINE ModifiedArray ( a , 2 * n ) NEW_LINE DEDENT
Count of lines required to write the given String | Function to return the number of lines required ; If string is empty ; Initialize lines and width ; Iterate through S ; Return lines and width used ; Driver Code ; Function call to print required answer
def numberOfLines ( S , widths ) : NEW_LINE INDENT if ( S == " " ) : NEW_LINE INDENT return 0 , 0 NEW_LINE DEDENT lines , width = 1 , 0 NEW_LINE for c in S : NEW_LINE INDENT w = widths [ ord ( c ) - ord ( ' a ' ) ] NEW_LINE width += w NEW_LINE if width > 10 : NEW_LINE INDENT lines += 1 NEW_LINE width = w NEW_LINE DEDENT DEDENT return lines , width NEW_LINE DEDENT S = " bbbcccdddaa " NEW_LINE Widths = [ 4 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] NEW_LINE print ( numberOfLines ( S , Widths ) ) NEW_LINE
Check if elements of an array can be arranged satisfying the given condition | Python implementation of the approach ; Function to return true if the elements can be arranged in the desired order ; If 2 * x is not found to pair ; Remove an occurrence of x and an occurrence of 2 * x ; Driver Code ; Function call to print required answer
import collections NEW_LINE def canReorder ( A ) : NEW_LINE INDENT count = collections . Counter ( A ) NEW_LINE for x in sorted ( A , key = abs ) : NEW_LINE INDENT if count [ x ] == 0 : NEW_LINE INDENT continue NEW_LINE DEDENT if count [ 2 * x ] == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT count [ x ] -= 1 NEW_LINE count [ 2 * x ] -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT A = [ 4 , - 2 , 2 , - 4 ] NEW_LINE print ( canReorder ( A ) ) NEW_LINE
Maximum sum of all elements of array after performing given operations | Python3 program to find the maximum sum after given operations ; Function to calculate Maximum Subarray Sum or Kadane 's Algorithm ; Function to find the maximum sum after given operations ; To store sum of all elements ; Maximum sum of a subarray ; Calculate the sum of all elements ; Driver Code ; size of an array
import sys NEW_LINE def maxSubArraySum ( a , 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 + a [ 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 maxSum ( a , n ) : NEW_LINE INDENT S = 0 ; NEW_LINE S1 = maxSubArraySum ( a , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT S += a [ i ] NEW_LINE DEDENT return ( 2 * S1 - S ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ - 35 , 32 , - 24 , 0 , 27 , - 10 , 0 , - 19 ] NEW_LINE n = len ( a ) NEW_LINE print ( maxSum ( a , n ) ) NEW_LINE DEDENT
Minimize the difference between minimum and maximum elements | Function to minimize the difference between minimum and maximum elements ; Find max and min elements of the array ; Check whether the difference between the max and min element is less than or equal to k or not ; Calculate average of max and min ; If the array element is greater than the average then decrease it by k ; If the array element is smaller than the average then increase it by k ; Find max and min of the modified array ; return the new difference ; Driver code
def minimizeDiff ( arr , n , k ) : NEW_LINE INDENT max_element = max ( arr ) NEW_LINE min_element = min ( arr ) NEW_LINE if ( ( max_element - min_element ) <= k ) : NEW_LINE INDENT return ( max_element - min_element ) NEW_LINE DEDENT avg = ( max_element + min_element ) // 2 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > avg ) : NEW_LINE INDENT arr [ i ] -= k NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] += k NEW_LINE DEDENT DEDENT max_element = max ( arr ) NEW_LINE min_element = min ( arr ) NEW_LINE return ( max_element - min_element ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 16 , 12 , 9 , 20 ] NEW_LINE n = 5 NEW_LINE k = 3 NEW_LINE print ( " Max ▁ height ▁ difference ▁ = " , minimizeDiff ( arr , n , k ) ) NEW_LINE DEDENT
Maximum litres of water that can be bought with N Rupees | Python3 implementation of the above approach ; if buying glass bottles is profitable ; Glass bottles that can be bought ; Change budget according the bought bottles ; Plastic bottles that can be bought ; if only plastic bottles need to be bought ; Driver Code
def maxLitres ( budget , plastic , glass , refund ) : NEW_LINE INDENT if glass - refund < plastic : NEW_LINE INDENT ans = max ( ( budget - refund ) // ( glass - refund ) , 0 ) NEW_LINE budget -= ans * ( glass - refund ) NEW_LINE ans += budget // plastic NEW_LINE print ( ans ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( budget // plastic ) NEW_LINE DEDENT DEDENT budget , plastic , glass , refund = 10 , 11 , 9 , 8 NEW_LINE maxLitres ( budget , plastic , glass , refund ) NEW_LINE
Find number from given list for which value of the function is closest to A | Function to find number from given list for which value of the function is closest to A ; Stores the final index ; Declaring a variable to store the minimum absolute difference ; Finding F ( n ) ; Updating the index of the answer if new absolute difference is less than tmp ; Driver Code
def leastValue ( P , A , N , a ) : NEW_LINE INDENT ans = - 1 NEW_LINE tmp = float ( ' inf ' ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT t = P - a [ i ] * 0.006 NEW_LINE if abs ( t - A ) < tmp : NEW_LINE INDENT tmp = abs ( t - A ) NEW_LINE ans = i NEW_LINE DEDENT DEDENT return a [ ans ] NEW_LINE DEDENT N , P , A = 2 , 12 , 5 NEW_LINE a = [ 1000 , 2000 ] NEW_LINE print ( leastValue ( P , A , N , a ) ) NEW_LINE
Find permutation of n which is divisible by 3 but not divisible by 6 | Python3 program to find permutation of n which is divisible by 3 but not divisible by 6 ; Function to find the permutation ; length of integer ; if integer is even ; return odd integer ; rotate integer ; return - 1 in case no required permutation exists ; Driver Code
from math import log10 , ceil , pow NEW_LINE def findPermutation ( n ) : NEW_LINE INDENT len = ceil ( log10 ( n ) ) NEW_LINE for i in range ( 0 , len , 1 ) : NEW_LINE INDENT if n % 2 != 0 : NEW_LINE INDENT return n NEW_LINE DEDENT else : NEW_LINE INDENT n = ( ( n / 10 ) + ( n % 10 ) * pow ( 10 , len - i - 1 ) ) NEW_LINE continue NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 132 NEW_LINE print ( int ( findPermutation ( n ) ) ) NEW_LINE DEDENT
Maximum score after flipping a Binary Matrix atmost K times | Python3 program to find the maximum score after flipping a Binary Matrix atmost K times ; Function to find maximum score of matrix ; Find value of rows having first column value equal to zero ; update those rows which lead to maximum score after toggle ; Calculating answer ; check if K > 0 we can toggle if necessary . ; return max answer possible ; Driver Code ; function call to print required answer
n = 3 NEW_LINE m = 4 NEW_LINE def maxMatrixScore ( A , K ) : NEW_LINE INDENT update = { } NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if A [ i ] [ 0 ] == 0 : NEW_LINE INDENT ans = 0 NEW_LINE for j in range ( 1 , m ) : NEW_LINE INDENT ans = ans + A [ i ] [ j ] * 2 ** ( m - j - 1 ) NEW_LINE DEDENT update [ ans ] = i NEW_LINE DEDENT DEDENT for idx in update . values ( ) : NEW_LINE INDENT for j in range ( 0 , m ) : NEW_LINE INDENT A [ idx ] [ j ] = ( A [ idx ] [ j ] + 1 ) % 2 NEW_LINE DEDENT K -= 1 NEW_LINE if K <= 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for j in range ( 0 , m ) : NEW_LINE INDENT zero , one = 0 , 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if A [ i ] [ j ] == 0 : zero += 1 NEW_LINE else : one += 1 NEW_LINE DEDENT if K > 0 and zero > one : NEW_LINE INDENT ans += zero * 2 ** ( m - j - 1 ) NEW_LINE K -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += one * 2 ** ( m - j - 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ [ 0 , 0 , 1 , 1 ] , [ 1 , 0 , 1 , 0 ] , [ 1 , 1 , 0 , 0 ] ] NEW_LINE K = 2 NEW_LINE print ( maxMatrixScore ( A , K ) ) NEW_LINE DEDENT
Check if it is possible to serve customer queue with different notes | Function that returns true is selling of the tickets is possible ; Nothing to return to the customer ; Check if 25 can be returned to customer . ; Try returning one 50 and one 25 ; Try returning three 25 ; If the loop did not break , all the tickets were sold ; Driver Code
def isSellingPossible ( n , a ) : NEW_LINE INDENT c25 = 0 ; NEW_LINE c50 = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( a [ i ] == 25 ) : NEW_LINE INDENT c25 += 1 ; NEW_LINE DEDENT elif ( a [ i ] == 50 ) : NEW_LINE INDENT c50 += 1 ; NEW_LINE if ( c25 == 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT c25 -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( c50 > 0 and c25 > 0 ) : NEW_LINE INDENT c50 -= 1 ; NEW_LINE c25 -= 1 ; NEW_LINE DEDENT elif ( c25 >= 3 ) : NEW_LINE INDENT c25 -= 3 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT i += 1 ; NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT a = [ 25 , 25 , 50 , 100 ] ; NEW_LINE n = len ( a ) ; NEW_LINE if ( isSellingPossible ( n , a ) ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE DEDENT
Check if a cell can be visited more than once in a String | Function to check if any cell can be visited more than once ; Array to mark cells ; Traverse the string ; Increase the visit count of the left and right cells within the array which can be visited ; If any cell can be visited more than once , Return True ; Driver code
def checkIfOverlap ( str ) : NEW_LINE INDENT length = len ( str ) NEW_LINE visited = [ 0 ] * ( length + 1 ) NEW_LINE for i in range ( length ) : NEW_LINE INDENT if str [ i ] == " . " : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( max ( 0 , i - ord ( str [ i ] ) , min ( length , i + ord ( str [ i ] ) ) + 1 ) ) : NEW_LINE INDENT visited [ j ] += 1 NEW_LINE DEDENT DEDENT for i in range ( length ) : NEW_LINE INDENT if visited [ i ] > 1 : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " . 2 . . 2 . " NEW_LINE if checkIfOverlap ( str ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Check if a number has digits in the given Order | Check if the digits follow the correct order ; to store the previous digit ; pointer to tell what type of sequence are we dealing with ; check if we have same digit as the previous digit ; checking the peak point of the number ; check if we have same digit as the previous digit ; check if the digit is greater than the previous one If true , then break from the loop as we are in descending order part ; Driver code
def isCorrectOrder ( n ) : NEW_LINE INDENT flag = True ; NEW_LINE prev = - 1 ; NEW_LINE type = - 1 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( type == - 1 ) : NEW_LINE INDENT if ( prev == - 1 ) : NEW_LINE INDENT prev = n % 10 ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE continue ; NEW_LINE DEDENT if ( prev == n % 10 ) : NEW_LINE INDENT flag = False ; NEW_LINE break ; NEW_LINE DEDENT if ( prev > n % 10 ) : NEW_LINE INDENT type = 1 ; NEW_LINE prev = n % 10 ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE continue ; NEW_LINE DEDENT prev = n % 10 ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( prev == n % 10 ) : NEW_LINE INDENT flag = False ; NEW_LINE break ; NEW_LINE DEDENT if ( prev < n % 10 ) : NEW_LINE INDENT flag = False ; NEW_LINE break ; NEW_LINE DEDENT prev = n % 10 ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE DEDENT DEDENT return flag ; NEW_LINE DEDENT n = 123454321 ; NEW_LINE if ( isCorrectOrder ( n ) ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE DEDENT
Coin game of two corners ( Greedy Approach ) | Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Find sum of odd positioned coins ; Find sum of even positioned coins ; Print even or odd coins depending upon which sum is greater . ; Driver code
def printCoins ( arr , n ) : NEW_LINE INDENT oddSum = 0 NEW_LINE for i in range ( 0 , n , 2 ) : NEW_LINE INDENT oddSum += arr [ i ] NEW_LINE DEDENT evenSum = 0 NEW_LINE for i in range ( 1 , n , 2 ) : NEW_LINE INDENT evenSum += arr [ i ] NEW_LINE DEDENT if oddSum > evenSum : NEW_LINE INDENT start = 0 NEW_LINE DEDENT else : NEW_LINE INDENT start = 1 NEW_LINE DEDENT for i in range ( start , n , 2 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr1 = [ 8 , 15 , 3 , 7 ] NEW_LINE n = len ( arr1 ) NEW_LINE printCoins ( arr1 , n ) NEW_LINE print ( ) NEW_LINE arr2 = [ 2 , 2 , 2 , 2 ] NEW_LINE n = len ( arr2 ) NEW_LINE printCoins ( arr2 , n ) NEW_LINE print ( ) NEW_LINE arr3 = [ 20 , 30 , 2 , 2 , 2 , 10 ] NEW_LINE n = len ( arr3 ) NEW_LINE printCoins ( arr3 , n ) NEW_LINE DEDENT
Prim 's Algorithm (Simple Implementation for Adjacency Matrix Representation) | Python3 implementation to find minimum spanning tree for adjacency representation . ; Returns true if edge u - v is a valid edge to be include in MST . An edge is valid if one end is already included in MST and other is not in MST . ; Include first vertex in MST ; Keep adding edges while number of included edges does not become V - 1. ; Find minimum weight valid edge . ; Driver Code ; Let us create the following graph 2 3 ( 0 ) -- ( 1 ) -- ( 2 ) | / \ | 6 | 8 / \ 5 | 7 | / \ | ( 3 ) -- -- -- - ( 4 ) 9 ; Print the solution
from sys import maxsize NEW_LINE INT_MAX = maxsize NEW_LINE V = 5 NEW_LINE def isValidEdge ( u , v , inMST ) : NEW_LINE INDENT if u == v : NEW_LINE INDENT return False NEW_LINE DEDENT if inMST [ u ] == False and inMST [ v ] == False : NEW_LINE INDENT return False NEW_LINE DEDENT elif inMST [ u ] == True and inMST [ v ] == True : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def primMST ( cost ) : NEW_LINE INDENT inMST = [ False ] * V NEW_LINE inMST [ 0 ] = True NEW_LINE edge_count = 0 NEW_LINE mincost = 0 NEW_LINE while edge_count < V - 1 : NEW_LINE INDENT minn = INT_MAX NEW_LINE a = - 1 NEW_LINE b = - 1 NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT if cost [ i ] [ j ] < minn : NEW_LINE INDENT if isValidEdge ( i , j , inMST ) : NEW_LINE INDENT minn = cost [ i ] [ j ] NEW_LINE a = i NEW_LINE b = j NEW_LINE DEDENT DEDENT DEDENT DEDENT if a != - 1 and b != - 1 : NEW_LINE INDENT print ( " Edge ▁ % d : ▁ ( % d , ▁ % d ) ▁ cost : ▁ % d " % ( edge_count , a , b , minn ) ) NEW_LINE edge_count += 1 NEW_LINE mincost += minn NEW_LINE inMST [ b ] = inMST [ a ] = True NEW_LINE DEDENT DEDENT print ( " Minimum ▁ cost ▁ = ▁ % d " % mincost ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT cost = [ [ INT_MAX , 2 , INT_MAX , 6 , INT_MAX ] , [ 2 , INT_MAX , 3 , 8 , 5 ] , [ INT_MAX , 3 , INT_MAX , INT_MAX , 7 ] , [ 6 , 8 , INT_MAX , INT_MAX , 9 ] , [ INT_MAX , 5 , 7 , 9 , INT_MAX ] ] NEW_LINE primMST ( cost ) NEW_LINE DEDENT
Subarray whose absolute sum is closest to K | function to return the index ; Add Last element tp currSum ; Save Difference of previous Iteration ; Calculate new Difference ; When the Sum exceeds K ; Current Difference greater in magnitude Store Temporary Result ; Difference in Previous was lesser In previous , Right index = j - 1 ; In next iteration , Left Index Increases but Right Index remains the Same Update currSum and i Accordingly ; Case to simply increase Right Index ; Check if lesser deviation found ; Driver Code
def getSubArray ( arr , n , K ) : NEW_LINE INDENT currSum = 0 NEW_LINE prevDif = 0 NEW_LINE currDif = 0 NEW_LINE result = [ - 1 , - 1 , abs ( K - abs ( currSum ) ) ] NEW_LINE resultTmp = result NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while ( i <= j and j < n ) : NEW_LINE INDENT currSum += arr [ j ] NEW_LINE prevDif = currDif NEW_LINE currDif = K - abs ( currSum ) NEW_LINE if ( currDif <= 0 ) : NEW_LINE INDENT if abs ( currDif ) < abs ( prevDif ) : NEW_LINE INDENT resultTmp = [ i , j , currDif ] NEW_LINE DEDENT else : NEW_LINE INDENT resultTmp = [ i , j - 1 , prevDif ] NEW_LINE DEDENT currSum -= ( arr [ i ] + arr [ j ] ) NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT resultTmp = [ i , j , currDif ] NEW_LINE j += 1 NEW_LINE DEDENT if ( abs ( resultTmp [ 2 ] ) < abs ( result [ 2 ] ) ) : NEW_LINE INDENT result = resultTmp NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT arr = [ 15 , - 3 , 5 , 2 , 7 , 6 , 34 , - 6 ] NEW_LINE n = len ( arr ) NEW_LINE K = 50 NEW_LINE [ i , j , minDev ] = getSubArray ( arr , n , K ) NEW_LINE if ( i == - 1 ) : NEW_LINE INDENT print ( " The ▁ empty ▁ array ▁ shows ▁ minimum ▁ Deviation " ) NEW_LINE return 0 NEW_LINE DEDENT for i in range ( i , j + 1 ) : NEW_LINE INDENT print arr [ i ] , NEW_LINE DEDENT DEDENT main ( ) NEW_LINE
Length and Breadth of rectangle such that ratio of Area to diagonal ^ 2 is maximum | function to print length and breadth ; sort the input array ; create array vector of integers occurring in pairs ; push the same pairs ; calculate length and breadth as per requirement ; check for given condition ; print the required answer ; Driver Code
def findLandB ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE arr_pairs = [ ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT arr_pairs . append ( arr [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT length = arr_pairs [ 0 ] NEW_LINE breadth = arr_pairs [ 1 ] NEW_LINE size = len ( arr_pairs ) NEW_LINE for i in range ( 1 , size - 1 ) : NEW_LINE INDENT if ( ( int ( length / breadth ) + int ( breadth / length ) ) > ( int ( arr_pairs [ i ] / arr_pairs [ i - 1 ] ) + int ( arr_pairs [ i - 1 ] / arr_pairs [ i ] ) ) ) : NEW_LINE INDENT length = arr_pairs [ i ] NEW_LINE breadth = arr_pairs [ i - 1 ] NEW_LINE DEDENT DEDENT print ( length , " , " , breadth ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 2 , 2 , 5 , 6 , 5 , 6 , 7 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE findLandB ( arr , n ) NEW_LINE DEDENT
Smallest sum contiguous subarray | Set | function to find the smallest sum contiguous subarray ; First invert the sign of the elements ; Apply the normal Kadane algorithm but on the elements of the array having inverted sign ; Invert the answer to get minimum val ; Driver Code
def smallestSumSubarr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = - arr [ i ] NEW_LINE DEDENT sum_here = arr [ 0 ] NEW_LINE max_sum = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT sum_here = max ( sum_here + arr [ i ] , arr [ i ] ) NEW_LINE max_sum = max ( max_sum , sum_here ) NEW_LINE DEDENT return ( - 1 ) * max_sum NEW_LINE DEDENT arr = [ 3 , - 4 , 2 , - 3 , - 1 , 7 , - 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Smallest ▁ sum : " , smallestSumSubarr ( arr , n ) ) NEW_LINE
Find k pairs with smallest sums in two arrays | Set 2 | Function to print the K smallest pairs ; if k is greater than total pairs ; _pair _one keeps track of ' first ' in a1 and ' second ' in a2 in _two , _two [ 0 ] keeps track of element in the a2and _two [ 1 ] in a1 [ ] ; Repeat the above process till all K pairs are printed ; when both the pointers are pointing to the same elements ( po3 ) ; updates according to step 1 ; if ( _one [ 1 ] == 0 ) : see po2 ; updates opposite to step 1 ; updates according to rule 1 ; if ( _one [ 0 ] == 0 ) : see po2 ; updates opposite to rule 1 ; if ( _two [ 0 ] == 0 ) : see po2 ; else update as necessary ( po1 ) ; updating according to rule 1 ; if ( _one [ 1 ] == 0 ) : see po2 ; updating according to rule 1 ; if ( _one [ 0 ] == 0 ) : see po2 ; updating according to rule 1 ; if ( _two [ 0 ] == 0 ) : see po2 ; updating according to rule 1 ; if ( _two [ 1 ] == 0 ) : see po2 ; Driver Code
def printKPairs ( a1 , a , size1 , size2 , k ) : NEW_LINE INDENT if ( k > ( size2 * size1 ) ) : NEW_LINE INDENT print ( " k pairs don ' t exist " ) NEW_LINE return NEW_LINE DEDENT _one , _two = [ 0 , 0 ] , [ 0 , 0 ] NEW_LINE cnt = 0 NEW_LINE while ( cnt < k ) : NEW_LINE INDENT if ( _one [ 0 ] == _two [ 1 ] and _two [ 0 ] == _one [ 1 ] ) : NEW_LINE INDENT if ( a1 [ _one [ 0 ] ] < a2 [ _one [ 1 ] ] ) : NEW_LINE INDENT print ( " [ " , a1 [ _one [ 0 ] ] , " , ▁ " , a2 [ _one [ 1 ] ] , " ] ▁ " , end = " ▁ " ) NEW_LINE _one [ 1 ] = ( _one [ 1 ] + 1 ) % size2 NEW_LINE INDENT _one [ 0 ] = ( _one [ 0 ] + 1 ) % size1 NEW_LINE DEDENT _two [ 1 ] = ( _two [ 1 ] + 1 ) % size2 NEW_LINE if ( _two [ 1 ] == 0 ) : NEW_LINE INDENT _two [ 0 ] = ( _two [ 0 ] + 1 ) % size2 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " [ " , a2 [ _one [ 1 ] ] , " , ▁ " , a1 [ _one [ 0 ] ] , " ] ▁ " , end = " ▁ " ) NEW_LINE _one [ 0 ] = ( _one [ 0 ] + 1 ) % size1 NEW_LINE INDENT _one [ 1 ] = ( _one [ 1 ] + 1 ) % size2 NEW_LINE DEDENT _two [ 0 ] = ( _two [ 0 ] + 1 ) % size2 NEW_LINE INDENT _two [ 1 ] = ( _two [ 1 ] + 1 ) % size1 NEW_LINE DEDENT DEDENT DEDENT elif ( a1 [ _one [ 0 ] ] + a2 [ _one [ 1 ] ] <= a2 [ _two [ 0 ] ] + a1 [ _two [ 1 ] ] ) : NEW_LINE INDENT if ( a1 [ _one [ 0 ] ] < a2 [ _one [ 1 ] ] ) : NEW_LINE INDENT print ( " [ " , a1 [ _one [ 0 ] ] , " , ▁ " , a2 [ _one [ 1 ] ] , " ] ▁ " , end = " ▁ " ) NEW_LINE _one [ 1 ] = ( ( _one [ 1 ] + 1 ) % size2 ) NEW_LINE INDENT _one [ 0 ] = ( _one [ 0 ] + 1 ) % size1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " [ " , a2 [ _one [ 1 ] ] , " , ▁ " , a1 [ _one [ 0 ] ] , " ] ▁ " , end = " ▁ " ) NEW_LINE _one [ 0 ] = ( ( _one [ 0 ] + 1 ) % size1 ) NEW_LINE INDENT _one [ 1 ] = ( _one [ 1 ] + 1 ) % size2 NEW_LINE DEDENT DEDENT DEDENT elif ( a1 [ _one [ 0 ] ] + a2 [ _one [ 1 ] ] > a2 [ _two [ 0 ] ] + a1 [ _two [ 1 ] ] ) : NEW_LINE INDENT if ( a2 [ _two [ 0 ] ] < a1 [ _two [ 1 ] ] ) : NEW_LINE INDENT print ( " [ " , a2 [ _two [ 0 ] ] , " , ▁ " , a1 [ _two [ 1 ] ] , " ] ▁ " , end = " ▁ " ) NEW_LINE _two [ 0 ] = ( ( _two [ 0 ] + 1 ) % size2 ) NEW_LINE INDENT _two [ 1 ] = ( _two [ 1 ] + 1 ) % size1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " [ " , a1 [ _two [ 1 ] ] , " , ▁ " , a2 [ _two [ 0 ] ] , " ] ▁ " , end = " ▁ " ) NEW_LINE _two [ 1 ] = ( ( _two [ 1 ] + 1 ) % size1 ) NEW_LINE INDENT _two [ 0 ] = ( _two [ 0 ] + 1 ) % size1 NEW_LINE DEDENT DEDENT DEDENT cnt += 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a1 = [ 2 , 3 , 4 ] NEW_LINE a2 = [ 1 , 6 , 5 , 8 ] NEW_LINE size1 = len ( a1 ) NEW_LINE size2 = len ( a2 ) NEW_LINE k = 4 NEW_LINE printKPairs ( a1 , a2 , size1 , size2 , k ) NEW_LINE DEDENT
Maximum number by concatenating every element in a rotation of an array | Function to print the largest number ; store the index of largest left most digit of elements ; Iterate for all numbers ; check for the last digit ; check for the largest left most digit ; print the rotation of array ; print the rotation of array ; Driver Code
def printLargest ( a , n ) : NEW_LINE INDENT max = - 1 NEW_LINE ind = - 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT num = a [ i ] NEW_LINE while ( num ) : NEW_LINE INDENT r = num % 10 ; NEW_LINE num = num / 10 ; NEW_LINE if ( num == 0 ) : NEW_LINE INDENT if ( max < r ) : NEW_LINE INDENT max = r NEW_LINE ind = i ; NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( ind , n ) : NEW_LINE INDENT print ( a [ i ] , end = ' ' ) , NEW_LINE DEDENT for i in range ( 0 , ind ) : NEW_LINE INDENT print ( a [ i ] , end = ' ' ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 54 , 546 , 548 , 60 ] NEW_LINE n = len ( a ) NEW_LINE printLargest ( a , n ) NEW_LINE DEDENT
Minimum operations to make GCD of array a multiple of k | Python 3 program to make GCD of array a multiple of k . ; If array value is not 1 and it is greater than k then we can increase the or decrease the remainder obtained by dividing k from the ith value of array so that we get the number which is either closer to k or its multiple ; Else we only have one choice which is to increment the value to make equal to k ; Driver code
def MinOperation ( a , n , k ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] != 1 and a [ i ] > k ) : NEW_LINE INDENT result = ( result + min ( a [ i ] % k , k - a [ i ] % k ) ) NEW_LINE DEDENT else : NEW_LINE INDENT result = result + k - a [ i ] NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE k = 5 NEW_LINE print ( MinOperation ( arr , n , k ) ) NEW_LINE DEDENT
Maximum product subset of an array | Python3 program to find maximum product of a subset . ; Find count of negative numbers , count of zeros , negative number with least absolute value and product of non - zero numbers ; If number is 0 , we don 't multiply it with product. ; Count negatives and keep track of negative number with least absolute value . ; If there are all zeros ; If there are odd number of negative numbers ; Exceptional case : There is only negative and all other are zeros ; Otherwise result is product of all non - zeros divided by negative number with least absolute value ; Driver Code
def maxProductSubset ( a , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return a [ 0 ] NEW_LINE DEDENT max_neg = - 999999999999 NEW_LINE count_neg = 0 NEW_LINE count_zero = 0 NEW_LINE prod = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] == 0 : NEW_LINE INDENT count_zero += 1 NEW_LINE continue NEW_LINE DEDENT if a [ i ] < 0 : NEW_LINE INDENT count_neg += 1 NEW_LINE max_neg = max ( max_neg , a [ i ] ) NEW_LINE DEDENT prod = prod * a [ i ] NEW_LINE DEDENT if count_zero == n : NEW_LINE INDENT return 0 NEW_LINE DEDENT if count_neg & 1 : NEW_LINE INDENT if ( count_neg == 1 and count_zero > 0 and count_zero + count_neg == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT prod = int ( prod / max_neg ) NEW_LINE DEDENT return prod NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ - 1 , - 1 , - 2 , 4 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( maxProductSubset ( a , n ) ) NEW_LINE DEDENT
Minimum cost to process m tasks where switching costs | Function to find out the farthest position where one of the currently ongoing tasks will rehappen . ; Iterate form last to current position and find where the task will happen next . ; Find out maximum of all these positions and it is the farthest position . ; Function to find out minimum cost to process all the tasks ; freqarr [ i ] [ j ] denotes the frequency of type j task after position i like in array 1 , 2 , 1 , 3 , 2 , 1 frequency of type 1 task after position 0 is 2. So , for this array freqarr [ 0 ] [ 1 ] = 2. Here , i can range in between 0 to m - 1 and j can range in between 0 to m ( though there is not any type 0 task ) . ; Fill up the freqarr vector from last to first . After m - 1 th position frequency of all type of tasks will be 0. Then at m - 2 th position only frequency of arr [ m - 1 ] type task will be increased by 1. Again , in m - 3 th position only frequency of type arr [ m - 2 ] task will be increased by 1 and so on . ; isRunning [ i ] denotes whether type i task is currently running in one of the cores . At the beginning no tasks are running so all values are false . ; cost denotes total cost to assign tasks ; truecount denotes number of occupied cores ; iterate through each task and find the total cost . ; ele denotes type of task . ; Case 1 : if same type of task is currently running cost for this is 0. ; Case 2 : same type of task is not currently running . ; Subcase 1 : if there is at least one free core then assign this task to that core at a cost of 1 unit . ; Subcase 2 : No core is free ; set minimum frequency to a big number ; set index of minimum frequency task to 0. ; find the minimum frequency task type ( miniind ) and frequency ( mini ) . ; If minimum frequency is zero then just stop the task and start the present task in that core . Cost for this is 1 unit . ; If minimum frequency is nonzero then find the farthest position where one of the ongoing task will rehappen . Stop that task and start present task in that core . ; find out the farthest position using find function ; return total cost ; Driver Code ; Test case 1 ; Test case 2 ; Test case 3
def find ( arr , pos , m , isRunning ) : NEW_LINE INDENT d = [ 0 ] * ( m + 1 ) NEW_LINE for i in range ( m - 1 , pos , - 1 ) : NEW_LINE INDENT if isRunning [ arr [ i ] ] : NEW_LINE INDENT d [ arr [ i ] ] = i NEW_LINE DEDENT DEDENT maxipos = 0 NEW_LINE for ele in d : NEW_LINE INDENT maxipos = max ( ele , maxipos ) NEW_LINE DEDENT return maxipos NEW_LINE DEDENT def mincost ( n , m , arr ) : NEW_LINE INDENT freqarr = [ [ ] for i in range ( m ) ] NEW_LINE newvec = [ 0 ] * ( m + 1 ) NEW_LINE freqarr [ m - 1 ] = newvec [ : ] NEW_LINE for i in range ( m - 2 , - 1 , - 1 ) : NEW_LINE INDENT nv = freqarr [ i + 1 ] [ : ] NEW_LINE nv [ arr [ i + 1 ] ] += 1 NEW_LINE freqarr [ i ] = nv [ : ] NEW_LINE DEDENT isRunning = [ False ] * ( m + 1 ) NEW_LINE cost = 0 NEW_LINE truecount = 0 NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT ele = arr [ i ] NEW_LINE if isRunning [ ele ] == True : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT if truecount < n : NEW_LINE INDENT cost += 1 NEW_LINE truecount += 1 NEW_LINE isRunning [ ele ] = True NEW_LINE DEDENT else : NEW_LINE INDENT mini = 100000 NEW_LINE miniind = 0 NEW_LINE for j in range ( 1 , m + 1 ) : NEW_LINE INDENT if isRunning [ j ] and mini > freqarr [ i ] [ j ] : NEW_LINE INDENT mini = freqarr [ i ] [ j ] NEW_LINE miniind = j NEW_LINE DEDENT DEDENT if mini == 0 : NEW_LINE INDENT isRunning [ miniind ] = False NEW_LINE isRunning [ ele ] = True NEW_LINE cost += 1 NEW_LINE DEDENT else : NEW_LINE INDENT farpos = find ( arr , i , m , isRunning ) NEW_LINE isRunning [ arr [ farpos ] ] = False NEW_LINE isRunning [ ele ] = True NEW_LINE cost += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return cost NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n1 , m1 = 3 , 6 NEW_LINE arr1 = [ 1 , 2 , 1 , 3 , 4 , 1 ] NEW_LINE print ( mincost ( n1 , m1 , arr1 ) ) NEW_LINE n2 , m2 = 2 , 6 NEW_LINE arr2 = [ 1 , 2 , 1 , 3 , 2 , 1 ] NEW_LINE print ( mincost ( n2 , m2 , arr2 ) ) NEW_LINE n3 , m3 = 3 , 31 NEW_LINE arr3 = [ 7 , 11 , 17 , 10 , 7 , 10 , 2 , 9 , 2 , 18 , 8 , 10 , 20 , 10 , 3 , 20 , 17 , 17 , 17 , 1 , 15 , 10 , 8 , 3 , 3 , 18 , 13 , 2 , 10 , 10 , 11 ] NEW_LINE print ( mincost ( n3 , m3 , arr3 ) ) NEW_LINE DEDENT
Minimum Fibonacci terms with sum equal to K | Function to calculate Fibonacci Terms ; Calculate all Fibonacci terms which are less than or equal to K . ; If next term is greater than K do not push it in vector and return . ; Function to find the minimum number of Fibonacci terms having sum equal to K . ; Vector to store Fibonacci terms . ; Subtract Fibonacci terms from sum K until sum > 0. ; Divide sum K by j - th Fibonacci term to find how many terms it contribute in sum . ; Driver code
def calcFiboTerms ( fiboTerms , K ) : NEW_LINE INDENT i = 3 NEW_LINE fiboTerms . append ( 0 ) NEW_LINE fiboTerms . append ( 1 ) NEW_LINE fiboTerms . append ( 1 ) NEW_LINE while True : NEW_LINE INDENT nextTerm = ( fiboTerms [ i - 1 ] + fiboTerms [ i - 2 ] ) NEW_LINE if nextTerm > K : NEW_LINE INDENT return NEW_LINE DEDENT fiboTerms . append ( nextTerm ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT def findMinTerms ( K ) : NEW_LINE INDENT fiboTerms = [ ] NEW_LINE calcFiboTerms ( fiboTerms , K ) NEW_LINE count , j = 0 , len ( fiboTerms ) - 1 NEW_LINE while K > 0 : NEW_LINE INDENT count += K // fiboTerms [ j ] NEW_LINE K %= fiboTerms [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT K = 17 NEW_LINE print ( findMinTerms ( K ) ) NEW_LINE DEDENT
Smallest number with sum of digits as N and divisible by 10 ^ N | Python program to find smallest number to find smallest number with N as sum of digits and divisible by 10 ^ N . ; If N = 0 the string will be 0 ; If n is not perfectly divisible by 9 output the remainder ; Print 9 N / 9 times ; Append N zero 's to the number so as to make it divisible by 10^N ; Driver Code
import math NEW_LINE def digitsNum ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT print ( "0" , end = " " ) NEW_LINE DEDENT if ( N % 9 != 0 ) : NEW_LINE INDENT print ( N % 9 , end = " " ) NEW_LINE DEDENT for i in range ( 1 , int ( N / 9 ) + 1 ) : NEW_LINE INDENT print ( "9" , end = " " ) NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( "0" , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT N = 5 NEW_LINE print ( " The ▁ number ▁ is ▁ : ▁ " , end = " " ) NEW_LINE digitsNum ( N ) NEW_LINE
Divide 1 to n into two groups with minimum sum difference | Python program to divide n integers in two groups such that absolute difference of their sum is minimum ; To print vector along size ; Print vector size ; Print vector elements ; To divide n in two groups such that absolute difference of their sum is minimum ; Find sum of all elements upto n ; Sum of elements of group1 ; If sum is greater then or equal to 0 include i in group 1 otherwise include in group2 ; Decrease sum of group1 ; Print both the groups ; driver code
import math NEW_LINE def printVector ( v ) : NEW_LINE INDENT print ( len ( v ) ) NEW_LINE for i in range ( 0 , len ( v ) ) : NEW_LINE INDENT print ( v [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def findTwoGroup ( n ) : NEW_LINE INDENT sum = n * ( n + 1 ) / 2 NEW_LINE group1Sum = sum / 2 NEW_LINE group1 = [ ] NEW_LINE group2 = [ ] NEW_LINE for i in range ( n , 0 , - 1 ) : NEW_LINE INDENT if ( group1Sum - i >= 0 ) : NEW_LINE INDENT group1 . append ( i ) NEW_LINE group1Sum -= i NEW_LINE DEDENT else : NEW_LINE INDENT group2 . append ( i ) NEW_LINE DEDENT DEDENT printVector ( group1 ) NEW_LINE printVector ( group2 ) NEW_LINE DEDENT n = 5 NEW_LINE findTwoGroup ( n ) NEW_LINE
Maximum number of customers that can be satisfied with given quantity | Python3 program to find maximum number of customers that can be satisfied ; print maximum number of satisfied customers and their indexes ; Creating an vector of pair of total demand and customer number ; Sorting the customers according to their total demand ; Taking the first k customers that can be satisfied by total amount d ; Driver Code ; Initializing variables
v = [ ] NEW_LINE def solve ( n , d , a , b , arr ) : NEW_LINE INDENT first , second = 0 , 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT m = arr [ i ] [ 0 ] NEW_LINE t = arr [ i ] [ 1 ] NEW_LINE v . append ( [ a * m + b * t , i + 1 ] ) NEW_LINE DEDENT v . sort ( ) NEW_LINE ans = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if v [ i ] [ first ] <= d : NEW_LINE INDENT ans . append ( v [ i ] [ second ] ) NEW_LINE d -= v [ i ] [ first ] NEW_LINE DEDENT DEDENT print ( len ( ans ) ) NEW_LINE for i in range ( len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE d = 5 NEW_LINE a = 1 NEW_LINE b = 1 NEW_LINE arr = [ [ 2 , 0 ] , [ 3 , 2 ] , [ 4 , 4 ] , [ 10 , 0 ] , [ 0 , 1 ] ] NEW_LINE solve ( n , d , a , b , arr ) NEW_LINE DEDENT
Partition into two subarrays of lengths k and ( N | Function to calculate max_difference ; Sum of the array ; Sort the array in descending order ; Calculating max_difference ; Driver Code
def maxDifference ( arr , N , k ) : NEW_LINE INDENT S = 0 NEW_LINE S1 = 0 NEW_LINE max_difference = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT S += arr [ i ] NEW_LINE DEDENT arr . sort ( reverse = True ) NEW_LINE M = max ( k , N - k ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT S1 += arr [ i ] NEW_LINE DEDENT max_difference = S1 - ( S - S1 ) NEW_LINE return max_difference NEW_LINE DEDENT arr = [ 8 , 4 , 5 , 2 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE k = 2 NEW_LINE print ( maxDifference ( arr , N , k ) ) NEW_LINE
Minimum sum of product of two arrays | Function to find the minimum product ; Find product of current elements and update result . ; If both product and b [ i ] are negative , we must increase value of a [ i ] to minimize result . ; If both product and a [ i ] are negative , we must decrease value of a [ i ] to minimize result . ; Similar to above two cases for positive product . ; Check if current difference becomes higher than the maximum difference so far . ; Driver function
def minproduct ( a , b , n , k ) : NEW_LINE INDENT diff = 0 NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT pro = a [ i ] * b [ i ] NEW_LINE res = res + pro NEW_LINE if ( pro < 0 and b [ i ] < 0 ) : NEW_LINE INDENT temp = ( a [ i ] + 2 * k ) * b [ i ] NEW_LINE DEDENT elif ( pro < 0 and a [ i ] < 0 ) : NEW_LINE INDENT temp = ( a [ i ] - 2 * k ) * b [ i ] NEW_LINE DEDENT elif ( pro > 0 and a [ i ] < 0 ) : NEW_LINE INDENT temp = ( a [ i ] + 2 * k ) * b [ i ] NEW_LINE DEDENT elif ( pro > 0 and a [ i ] > 0 ) : NEW_LINE INDENT temp = ( a [ i ] - 2 * k ) * b [ i ] NEW_LINE DEDENT d = abs ( pro - temp ) NEW_LINE if ( d > diff ) : NEW_LINE INDENT diff = d NEW_LINE DEDENT DEDENT return res - diff NEW_LINE DEDENT a = [ 2 , 3 , 4 , 5 , 4 ] NEW_LINE b = [ 3 , 4 , 2 , 3 , 2 ] NEW_LINE n = 5 NEW_LINE k = 3 NEW_LINE print ( minproduct ( a , b , n , k ) ) NEW_LINE
Split n into maximum composite numbers | Function to calculate the maximum number of composite numbers adding upto n ; 4 is the smallest composite number ; stores the remainder when n is divided n is divided by 4 ; if remainder is 0 , then it is perfectly divisible by 4. ; if the remainder is 1 ; If the number is less then 9 , that is 5 , then it cannot be expressed as 4 is the only composite number less than 5 ; If the number is greater then 8 , and has a remainder of 1 , then express n as n - 9 a and it is perfectly divisible by 4 and for 9 , count 1. ; When remainder is 2 , just subtract 6 from n , so that n is perfectly divisible by 4 and count 1 for 6 which is subtracted . ; if the number is 7 , 11 which cannot be expressed as sum of any composite numbers ; when the remainder is 3 , then subtract 15 from it and n becomes perfectly divisible by 4 and we add 2 for 9 and 6 , which is getting subtracted to make n perfectly divisible by 4. ; Driver Code
def count ( n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT rem = n % 4 NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT return n // 4 NEW_LINE DEDENT if ( rem == 1 ) : NEW_LINE INDENT if ( n < 9 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return ( n - 9 ) // 4 + 1 NEW_LINE DEDENT if ( rem == 2 ) : NEW_LINE INDENT return ( n - 6 ) // 4 + 1 NEW_LINE DEDENT if ( rem == 3 ) : NEW_LINE INDENT if ( n < 15 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return ( n - 15 ) // 4 + 2 NEW_LINE DEDENT DEDENT n = 90 NEW_LINE print ( count ( n ) ) NEW_LINE n = 143 NEW_LINE print ( count ( n ) ) NEW_LINE
Policemen catch thieves | Returns maximum number of thieves that can be caught . ; store indices in list ; track lowest current indices of thief : thi [ l ] , police : pol [ r ] ; can be caught ; increment the minimum index ; Driver program
def policeThief ( arr , n , k ) : NEW_LINE INDENT i = 0 NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE res = 0 NEW_LINE thi = [ ] NEW_LINE pol = [ ] NEW_LINE while i < n : NEW_LINE INDENT if arr [ i ] == ' P ' : NEW_LINE INDENT pol . append ( i ) NEW_LINE DEDENT elif arr [ i ] == ' T ' : NEW_LINE INDENT thi . append ( i ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT while l < len ( thi ) and r < len ( pol ) : NEW_LINE INDENT if ( abs ( thi [ l ] - pol [ r ] ) <= k ) : NEW_LINE INDENT res += 1 NEW_LINE l += 1 NEW_LINE r += 1 NEW_LINE DEDENT elif thi [ l ] < pol [ r ] : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT r += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ ' P ' , ' T ' , ' T ' , ' P ' , ' T ' ] NEW_LINE k = 2 NEW_LINE n = len ( arr1 ) NEW_LINE print ( ( " Maximum ▁ thieves ▁ caught : ▁ { } " . format ( policeThief ( arr1 , n , k ) ) ) ) NEW_LINE arr2 = [ ' T ' , ' T ' , ' P ' , ' P ' , ' T ' , ' P ' ] NEW_LINE k = 2 NEW_LINE n = len ( arr2 ) NEW_LINE print ( ( " Maximum ▁ thieves ▁ caught : ▁ { } " . format ( policeThief ( arr2 , n , k ) ) ) ) NEW_LINE arr3 = [ ' P ' , ' T ' , ' P ' , ' T ' , ' T ' , ' P ' ] NEW_LINE k = 3 NEW_LINE n = len ( arr3 ) NEW_LINE print ( ( " Maximum ▁ thieves ▁ caught : ▁ { } " . format ( policeThief ( arr3 , n , k ) ) ) ) NEW_LINE DEDENT
Minimum rotations to unlock a circular lock | function for min rotation ; iterate till input and unlock code become 0 ; input and unlock last digit as reminder ; find min rotation ; update code and input ; Driver Code
def minRotation ( input , unlock_code ) : NEW_LINE INDENT rotation = 0 ; NEW_LINE while ( input > 0 or unlock_code > 0 ) : NEW_LINE INDENT input_digit = input % 10 ; NEW_LINE code_digit = unlock_code % 10 ; NEW_LINE rotation += min ( abs ( input_digit - code_digit ) , 10 - abs ( input_digit - code_digit ) ) ; NEW_LINE input = int ( input / 10 ) ; NEW_LINE unlock_code = int ( unlock_code / 10 ) ; NEW_LINE DEDENT return rotation ; NEW_LINE DEDENT input = 28756 ; NEW_LINE unlock_code = 98234 ; NEW_LINE print ( " Minimum ▁ Rotation ▁ = " , minRotation ( input , unlock_code ) ) ; NEW_LINE
Job Scheduling with two jobs allowed at a time | Python3 program to check if all jobs can be scheduled if two jobs are allowed at a time . ; making a pair of starting and ending time of job ; sorting according to starting time of job ; starting first and second job simultaneously ; Checking if starting time of next new job is greater than ending time of currently scheduled first job ; Checking if starting time of next new job is greater than ending time of ocurrently scheduled second job ; Driver Code ; startin = [ 1 , 2 , 4 ] starting time of jobs endin = [ 2 , 3 , 5 ] ending times of jobs
def checkJobs ( startin , endin , n ) : NEW_LINE INDENT a = [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT a . append ( [ startin [ i ] , endin [ i ] ] ) NEW_LINE DEDENT a . sort ( ) NEW_LINE tv1 = a [ 0 ] [ 1 ] NEW_LINE tv2 = a [ 1 ] [ 1 ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( a [ i ] [ 0 ] >= tv1 ) : NEW_LINE INDENT tv1 = tv2 NEW_LINE tv2 = a [ i ] [ 1 ] NEW_LINE DEDENT elif ( a [ i ] [ 0 ] >= tv2 ) : NEW_LINE INDENT tv2 = a [ i ] [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE print ( checkJobs ( startin , endin , n ) ) NEW_LINE DEDENT
Minimum cost for acquiring all coins with k extra coins allowed with every coin | Python3 program to acquire all n coins at minimum cost with multiple values of k . ; Converts coin [ ] to prefix sum array ; sort the coins values ; maintain prefix sum array ; Function to calculate min cost when we can get k extra coins after paying cost of one . ; calculate no . of coins needed ; return sum of from prefix array ; Driver code
import math as mt NEW_LINE def preprocess ( coin , n ) : NEW_LINE INDENT coin . sort ( ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT coin [ i ] += coin [ i - 1 ] NEW_LINE DEDENT DEDENT def minCost ( coin , n , k ) : NEW_LINE INDENT coins_needed = mt . ceil ( 1.0 * n / ( k + 1 ) ) NEW_LINE return coin [ coins_needed - 1 ] NEW_LINE DEDENT coin = [ 8 , 5 , 3 , 10 , 2 , 1 , 15 , 25 ] NEW_LINE n = len ( coin ) NEW_LINE preprocess ( coin , n ) NEW_LINE k = 3 NEW_LINE print ( minCost ( coin , n , k ) ) NEW_LINE k = 7 NEW_LINE print ( minCost ( coin , n , k ) ) NEW_LINE
Program for Worst Fit algorithm in Memory Management | Function to allocate memory to blocks as per worst fit algorithm ; Initially no block is assigned to any process ; pick each process and find suitable blocks according to its size ad assign to it ; Find the best fit block for current process ; If we could find a block for current process ; allocate block j to p [ i ] process ; Reduce available memory in this block . ; Driver code
def worstFit ( blockSize , m , processSize , n ) : NEW_LINE INDENT allocation = [ - 1 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT wstIdx = - 1 NEW_LINE for j in range ( m ) : NEW_LINE INDENT if blockSize [ j ] >= processSize [ i ] : NEW_LINE INDENT if wstIdx == - 1 : NEW_LINE INDENT wstIdx = j NEW_LINE DEDENT elif blockSize [ wstIdx ] < blockSize [ j ] : NEW_LINE INDENT wstIdx = j NEW_LINE DEDENT DEDENT DEDENT if wstIdx != - 1 : NEW_LINE INDENT allocation [ i ] = wstIdx NEW_LINE blockSize [ wstIdx ] -= processSize [ i ] NEW_LINE DEDENT DEDENT print ( " Process ▁ No . ▁ Process ▁ Size ▁ Block ▁ no . " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( i + 1 , " ▁ " , processSize [ i ] , end = " ▁ " ) NEW_LINE if allocation [ i ] != - 1 : NEW_LINE INDENT print ( allocation [ i ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Allocated " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT blockSize = [ 100 , 500 , 200 , 300 , 600 ] NEW_LINE processSize = [ 212 , 417 , 112 , 426 ] NEW_LINE m = len ( blockSize ) NEW_LINE n = len ( processSize ) NEW_LINE worstFit ( blockSize , m , processSize , n ) NEW_LINE DEDENT
Maximize array sum after K negations | Set 1 | This function does k operations on array in a way that maximize the array sum . index -- > stores the index of current minimum element for j 'th operation ; Modify array K number of times ; Find minimum element in array for current operation and modify it i . e ; arr [ j ] -- > - arr [ j ] ; this the condition if we find 0 as minimum element , so it will useless to replace 0 by - ( 0 ) for remaining operations ; Modify element of array ; Calculate sum of array ; Driver code
def maximumSum ( arr , n , k ) : NEW_LINE INDENT for i in range ( 1 , k + 1 ) : NEW_LINE INDENT min = + 2147483647 NEW_LINE index = - 1 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ j ] < min ) : NEW_LINE INDENT min = arr [ j ] NEW_LINE index = j NEW_LINE DEDENT DEDENT if ( min == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT arr [ index ] = - arr [ index ] NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT arr = [ - 2 , 0 , 5 , - 1 , 2 ] NEW_LINE k = 4 NEW_LINE n = len ( arr ) NEW_LINE print ( maximumSum ( arr , n , k ) ) NEW_LINE
Maximize array sum after K negations | Set 1 | Python3 program to find maximum array sum after at most k negations ; Sorting given array using in - built java sort function ; If we find a 0 in our sorted array , we stop ; Calculating sum ; Driver code
def sol ( arr , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE Sum = 0 NEW_LINE i = 0 NEW_LINE while ( k > 0 ) : NEW_LINE INDENT if ( arr [ i ] >= 0 ) : NEW_LINE INDENT k = 0 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = ( - 1 ) * arr [ i ] NEW_LINE k = k - 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT for j in range ( len ( arr ) ) : NEW_LINE INDENT Sum += arr [ j ] NEW_LINE DEDENT return Sum NEW_LINE DEDENT arr = [ - 2 , 0 , 5 , - 1 , 2 ] NEW_LINE print ( sol ( arr , 4 ) ) NEW_LINE
Maximize array sum after K negations | Set 1 | Function to calculate sum of the array ; Iterate from 0 to n - 1 ; Function to maximize sum ; Iterate from 0 to n - 1 ; Driver Code ; Function Call
def sumArray ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT def maximizeSum ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE i = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( k and arr [ i ] < 0 ) : NEW_LINE INDENT arr [ i ] *= - 1 NEW_LINE k -= 1 NEW_LINE continue NEW_LINE DEDENT break NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT if ( k == 0 or k % 2 == 0 ) : NEW_LINE INDENT return sumArray ( arr , n ) NEW_LINE DEDENT if ( i != 0 and abs ( arr [ i ] ) >= abs ( arr [ i - 1 ] ) ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT arr [ i ] *= - 1 NEW_LINE return sumArray ( arr , n ) NEW_LINE DEDENT n = 5 NEW_LINE k = 4 NEW_LINE arr = [ - 3 , - 2 , - 1 , 5 , 6 ] NEW_LINE print ( maximizeSum ( arr , n , k ) ) NEW_LINE
Bin Packing Problem ( Minimize number of used Bins ) | Returns number of bins required using first fit online algorithm ; Initialize result ( Count of bins ) ; Create an array to store remaining space in bins there can be at most n bins ; Place items one by one ; Find the first bin that can accommodate weight [ i ] ; If no bin could accommodate weight [ i ] ; Driver program
def firstFit ( weight , n , c ) : NEW_LINE INDENT res = 0 NEW_LINE bin_rem = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < res ) : NEW_LINE INDENT if ( bin_rem [ j ] >= weight [ i ] ) : NEW_LINE INDENT bin_rem [ j ] = bin_rem [ j ] - weight [ i ] NEW_LINE break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j == res ) : NEW_LINE INDENT bin_rem [ res ] = c - weight [ i ] NEW_LINE res = res + 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT weight = [ 2 , 5 , 4 , 7 , 1 , 3 , 8 ] NEW_LINE c = 10 NEW_LINE n = len ( weight ) NEW_LINE print ( " Number ▁ of ▁ bins ▁ required ▁ in ▁ First ▁ Fit ▁ : ▁ " , firstFit ( weight , n , c ) ) NEW_LINE
Minimum cost to reduce A and B to 0 using square root or divide by 2 | Python program for the above approach ; Function to return the minimum cost of converting A and B to 0 ; If both A and B doesn 't change in this recusrive call, then return INT_MAX to save the code from going into infinite loop ; Base Case ; If the answer of this recursive call is already memoised ; If A is reduced to A / 2 ; If B is reduced to B / 2 ; If both A and B is reduced to sqrt ( A * B ) ; Return the minimum of the value given by the above three subproblems , also memoize the value while returning ; Driver Code
import math as Math NEW_LINE def getMinOperations ( A , B , prevA , prevB , dp ) : NEW_LINE INDENT if ( A == prevA and B == prevB ) : NEW_LINE INDENT return 10 ** 9 ; NEW_LINE DEDENT if ( A == 0 and B == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ A ] [ B ] != - 1 ) : NEW_LINE INDENT return dp [ A ] [ B ] ; NEW_LINE DEDENT ans1 = getMinOperations ( A // 2 , B , A , B , dp ) ; NEW_LINE if ( ans1 != 10 ** 9 ) : NEW_LINE INDENT ans1 += 1 ; NEW_LINE DEDENT ans2 = getMinOperations ( A , B // 2 , A , B , dp ) ; NEW_LINE if ( ans2 != 10 ** 9 ) : NEW_LINE INDENT ans2 += 1 ; NEW_LINE DEDENT ans3 = getMinOperations ( Math . floor ( Math . sqrt ( A * B ) ) , Math . floor ( Math . sqrt ( A * B ) ) , A , B , dp ) ; NEW_LINE if ( ans3 != 10 ** 9 ) : NEW_LINE INDENT ans3 += 2 ; NEW_LINE DEDENT dp [ A ] [ B ] = min ( ans1 , min ( ans2 , ans3 ) ) NEW_LINE return dp [ A ] [ B ] ; NEW_LINE DEDENT A = 53 NEW_LINE B = 16 NEW_LINE mx = max ( A , B ) ; NEW_LINE dp = [ [ - 1 for i in range ( mx + 1 ) ] for i in range ( mx + 1 ) ] NEW_LINE print ( getMinOperations ( A , B , - 1 , - 1 , dp ) ) ; NEW_LINE
Maximize count of indices with same element by pairing rows from given Matrices | Function to find the maximum defined score ; If all students are assigned ; Check if row is not paired yet ; Check for all indexes ; If values at current indexes are same increase curSum ; Further recursive call ; Store the ans for current mask and return ; Utility function to find the maximum defined score ; Create a mask with all set bits 1 -> row is not paired yet 0 -> row is already paired ; Initialise dp array with - 1 ; Driver Code
def maxScoreSum ( a , b , row , mask , dp ) : NEW_LINE INDENT if ( row >= len ( a ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ mask ] != - 1 ) : NEW_LINE INDENT return dp [ mask ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT if ( mask & ( 1 << i ) ) : NEW_LINE INDENT newMask = mask ^ ( 1 << i ) NEW_LINE curSum = 0 NEW_LINE for j in range ( len ( a [ i ] ) ) : NEW_LINE INDENT if ( a [ row ] [ j ] == b [ i ] [ j ] ) : NEW_LINE INDENT curSum += 1 NEW_LINE DEDENT DEDENT ans = max ( ans , curSum + maxScoreSum ( a , b , row + 1 , newMask , dp ) ) NEW_LINE DEDENT DEDENT dp [ mask ] = ans NEW_LINE return dp [ mask ] NEW_LINE DEDENT def maxScoreSumUtil ( a , b , N , M ) : NEW_LINE INDENT row = 0 NEW_LINE mask = pow ( 2 , M ) - 1 NEW_LINE dp = [ - 1 ] * ( mask + 1 ) NEW_LINE return maxScoreSum ( a , b , row , mask , dp ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE M = 3 NEW_LINE a = [ [ 1 , 1 , 0 ] , [ 1 , 0 , 1 ] , [ 0 , 0 , 1 ] ] NEW_LINE b = [ [ 1 , 0 , 0 ] , [ 0 , 0 , 1 ] , [ 1 , 1 , 0 ] ] NEW_LINE print ( maxScoreSumUtil ( a , b , N , M ) ) NEW_LINE DEDENT
Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays | Function to find the maximum sum of differences of subarrays by splitting array into non - overlapping subarrays ; Stores the answer for prefix and initialize with zero ; Assume i - th index as right endpoint ; Choose the current value as the maximum and minimum ; Find the left endpoint and update the array dp [ ] ; Return answer ; Driver Code
def maxDiffSum ( arr , n ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxVal = arr [ i ] NEW_LINE minVal = arr [ i ] NEW_LINE for j in range ( i , - 1 , - 1 ) : NEW_LINE INDENT minVal = min ( minVal , arr [ j ] ) NEW_LINE maxVal = max ( maxVal , arr [ j ] ) NEW_LINE if ( j - 1 >= 0 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , maxVal - minVal + dp [ j - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , maxVal - minVal ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n - 1 ] NEW_LINE DEDENT arr = [ 8 , 1 , 7 , 9 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maxDiffSum ( arr , N ) ) NEW_LINE
Count of N | python 3 program for the above approach ; Find the value of x raised to the yth power modulo MOD ; Stores the value of x ^ y ; Iterate until y is positive ; Function to perform the Modular Multiplicative Inverse using the Fermat 's little theorem ; Modular division x / y , find modular multiplicative inverse of y and multiply by x ; Function to find Binomial Coefficient C ( n , k ) in O ( k ) time ; Base Case ; Update the value of p and q ; Function to find the count of arrays having K as the first element satisfying the given criteria ; Stores the resultant count of arrays ; Find the factorization of K ; Stores the count of the exponent of the currentprime factor ; N is one last prime factor , for c = 1 -> C ( N - 1 + 1 , 1 ) = N ; Return the totol count ; Driver Code
MOD = 1000000007 NEW_LINE from math import sqrt NEW_LINE def modPow ( x , y ) : NEW_LINE INDENT r = 1 NEW_LINE a = x NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) == 1 ) : NEW_LINE INDENT r = ( r * a ) % MOD NEW_LINE DEDENT a = ( a * a ) % MOD NEW_LINE y /= 2 NEW_LINE DEDENT return r NEW_LINE DEDENT def modInverse ( x ) : NEW_LINE INDENT return modPow ( x , MOD - 2 ) NEW_LINE DEDENT def modDivision ( p , q ) : NEW_LINE INDENT return ( p * modInverse ( q ) ) % MOD NEW_LINE DEDENT def C ( n , k ) : NEW_LINE INDENT if ( k > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT p = 1 NEW_LINE q = 1 NEW_LINE for i in range ( 1 , k + 1 , 1 ) : NEW_LINE INDENT q = ( q * i ) % MOD NEW_LINE p = ( p * ( n - i + 1 ) ) % MOD NEW_LINE DEDENT return modDivision ( p , q ) NEW_LINE DEDENT def countArrays ( N , K ) : NEW_LINE INDENT res = 1 NEW_LINE for p in range ( 2 , int ( sqrt ( K ) ) , 1 ) : NEW_LINE INDENT c = 0 NEW_LINE while ( K % p == 0 ) : NEW_LINE INDENT K /= p NEW_LINE c += 1 NEW_LINE DEDENT res = ( res * C ( N - 1 + c , c ) ) % MOD NEW_LINE DEDENT if ( N > 1 ) : NEW_LINE INDENT res = ( res * N ) % MOD NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE K = 5 NEW_LINE print ( countArrays ( N , K ) ) NEW_LINE DEDENT
Minimum number of days to debug all programs | Python 3 program for the above approach ; Function to calculate the minimum work sessions ; Break condition ; All bits are set ; Check if already calculated ; Store the answer ; Check if ith bit is set or unset ; Including in current work session ; Including in next work session ; Resultant answer will be minimum of both ; Function to initialize DP array and solve the problem ; Initialize dp table with - 1 ; Resultant mask ; no . of minimum work sessions is even ; no . of minimum work sessions is odd ; Driver code
import sys NEW_LINE def minSessions ( codeTime , dp , ones , n , mask , currTime , WorkingSessionTime ) : NEW_LINE INDENT if ( currTime > WorkingSessionTime ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT if ( mask == ones ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ mask ] [ currTime ] != - 1 ) : NEW_LINE INDENT return dp [ mask ] [ currTime ] NEW_LINE DEDENT ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( mask & ( 1 << i ) ) == 0 ) : NEW_LINE INDENT inc = minSessions ( codeTime , dp , ones , n , mask | ( 1 << i ) , currTime + codeTime [ i ] , WorkingSessionTime ) NEW_LINE inc_next = 1 + minSessions ( codeTime , dp , ones , n , mask | ( 1 << i ) , codeTime [ i ] , WorkingSessionTime ) NEW_LINE ans = min ( [ ans , inc , inc_next ] ) NEW_LINE DEDENT DEDENT dp [ mask ] [ currTime ] = ans NEW_LINE return ans NEW_LINE DEDENT def solve ( codeTime , n , WorkingSessionTime ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( 15 ) ] for j in range ( 1 << 14 ) ] NEW_LINE ones = ( 1 << n ) - 1 NEW_LINE ans = minSessions ( codeTime , dp , ones , n , 0 , 0 , WorkingSessionTime ) NEW_LINE if ( WorkingSessionTime < 6 ) : NEW_LINE INDENT if ( ans % 2 == 0 ) : NEW_LINE INDENT ans = ans // 2 NEW_LINE DEDENT else : NEW_LINE INDENT ans = ( ans / 2 ) + 1 NEW_LINE DEDENT DEDENT return int ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT codeTime = [ 1 , 2 , 3 , 1 , 1 , 3 ] NEW_LINE n = len ( codeTime ) NEW_LINE WorkingSessionTime = 4 NEW_LINE print ( solve ( codeTime , n , WorkingSessionTime ) ) NEW_LINE DEDENT
Count of non | Python 3 program for the above approach ; Define the dp table globally ; Recursive function to calculate total number of valid non - decreasing strings ; If already calculated state ; Base Case ; Stores the total count of strings formed ; Fill the value in dp matrix ; Function to find the total number of non - decreasing string formed by replacing the '? ; Initialize all value of dp table with - 1 ; Left and Right limits ; Iterate through all the characters of the string S ; Change R to the current character ; Call the recursive function ; Change L to R and R to 9 ; Reinitialize the length of ? to 0 ; Increment the length of the segment ; Update the ans ; Return the total count ; Driver Code
MAXN = 100005 NEW_LINE dp = [ [ - 1 for x in range ( 10 ) ] for y in range ( MAXN ) ] NEW_LINE def solve ( len , gap ) : NEW_LINE INDENT if ( dp [ len ] [ gap ] != - 1 ) : NEW_LINE INDENT return dp [ len ] [ gap ] NEW_LINE DEDENT if ( len == 0 or gap == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( gap < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( gap + 1 ) : NEW_LINE INDENT ans += solve ( len - 1 , gap - i ) NEW_LINE DEDENT dp [ len ] [ gap ] = ans NEW_LINE return dp [ len ] [ gap ] NEW_LINE DEDENT ' NEW_LINE def countValidStrings ( S ) : NEW_LINE INDENT global dp NEW_LINE N = len ( S ) NEW_LINE L , R = 1 , 9 NEW_LINE cnt = 0 NEW_LINE ans = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] != ' ? ' ) : NEW_LINE INDENT R = ord ( S [ i ] ) - ord ( '0' ) NEW_LINE ans *= solve ( cnt , R - L ) NEW_LINE L = R NEW_LINE R = 9 NEW_LINE cnt = 0 NEW_LINE DEDENT else : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT ans *= solve ( cnt , R - L ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "1 ? ? ?2" NEW_LINE print ( countValidStrings ( S ) ) NEW_LINE DEDENT
Count of binary arrays of size N with sum of product of adjacent pairs equal to K | Function to return the number of total possible combinations of 0 and 1 to form an array of size N having sum of product of consecutive elements K ; If value is greater than K , then return 0 as no combination is possible to have sum K ; Check if the result of this recursive call is memoised already , if it is then just return the previously calculated result ; Check if the value is equal to K at N , if it is then return 1 as this combination is possible . Otherwise return 0. ; If previous element is 1 ; If current element is 1 as well , then add 1 to value ; If current element is 0 , then value will remain same ; If previous element is 0 , then value will remain same irrespective of the current element ; Memoise and return the ans ; Driver Code ; As the array can be started by 0 or 1 , so take both cases while calculating the total possible combinations
def combinationsPossible ( N , idx , prev , val , K , dp ) : NEW_LINE INDENT if ( val > K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ val ] [ idx ] [ prev ] != - 1 ) : NEW_LINE INDENT return dp [ val ] [ idx ] [ prev ] NEW_LINE DEDENT if ( idx == N - 1 ) : NEW_LINE INDENT if ( val == K ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT ans = 0 NEW_LINE if ( prev == 1 ) : NEW_LINE INDENT ans += combinationsPossible ( N , idx + 1 , 1 , val + 1 , K , dp ) NEW_LINE ans += combinationsPossible ( N , idx + 1 , 0 , val , K , dp ) NEW_LINE DEDENT else : NEW_LINE INDENT ans += combinationsPossible ( N , idx + 1 , 1 , val , K , dp ) NEW_LINE ans += combinationsPossible ( N , idx + 1 , 0 , val , K , dp ) NEW_LINE DEDENT dp [ val ] [ idx ] [ prev ] = ans NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 3 NEW_LINE dp = [ [ [ - 1 for i in range ( 2 ) ] for j in range ( N + 1 ) ] for k in range ( K + 1 ) ] NEW_LINE print ( combinationsPossible ( N , 0 , 0 , 0 , K , dp ) + combinationsPossible ( N , 0 , 1 , 0 , K , dp ) ) NEW_LINE DEDENT
Count ways to split an array into subarrays such that sum of the i | Python3 program for the above approach ; Function to count ways to split an array into subarrays such that sum of the i - th subarray is divisible by i ; Stores the prefix sum of array ; Find the prefix sum ; Initialize dp [ ] [ ] array ; Stores the count of splitting ; Iterate over the range [ 0 , N ] ; Update the dp table ; If the last index is reached , then add it to the variable ans ; Return the possible count of splitting of array into subarrays ; Driver Code
import numpy as np NEW_LINE def countOfWays ( arr , N ) : NEW_LINE INDENT pre = [ 0 ] * ( N + 1 ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT pre [ i + 1 ] = pre [ i ] + arr [ i ] ; NEW_LINE DEDENT dp = np . zeros ( ( N + 2 , N + 2 ) ) ; NEW_LINE dp [ 1 ] [ 0 ] += 1 ; NEW_LINE ans = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N , 0 , - 1 ) : NEW_LINE INDENT dp [ j + 1 ] [ pre [ i + 1 ] % ( j + 1 ) ] += dp [ j ] [ pre [ i + 1 ] % j ] ; NEW_LINE if ( i == N - 1 ) : NEW_LINE INDENT ans += dp [ j ] [ pre [ i + 1 ] % j ] ; NEW_LINE DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( countOfWays ( arr , N ) ) ; NEW_LINE DEDENT
Domino and Tromino tiling problem | Function to find the total number of ways to tile a 2 * N board using the given types of tile ; If N is less than 3 ; Store all dp - states ; Base Case ; Traverse the range [ 2 , N ] ; Update the value of dp [ i ] [ 0 ] ; Update the value of dp [ i ] [ 1 ] ; Update the value of dp [ i ] [ 2 ] ; Return the number of ways as the value of dp [ N ] [ 0 ] ; Driver Code
MOD = 1e9 + 7 NEW_LINE def numTilings ( N ) : NEW_LINE INDENT if ( N < 3 ) : NEW_LINE INDENT return N NEW_LINE DEDENT dp = [ [ 0 ] * 3 for i in range ( N + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = dp [ 1 ] [ 0 ] = 1 NEW_LINE dp [ 1 ] [ 1 ] = dp [ 1 ] [ 2 ] = 1 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 2 ] [ 0 ] + dp [ i - 2 ] [ 1 ] + dp [ i - 2 ] [ 2 ] ) % MOD NEW_LINE dp [ i ] [ 1 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 2 ] ) % MOD NEW_LINE dp [ i ] [ 2 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] ) % MOD NEW_LINE DEDENT return int ( dp [ N ] [ 0 ] ) NEW_LINE DEDENT N = 3 NEW_LINE print ( numTilings ( N ) ) NEW_LINE
Count of N | Store the recurring recursive states ; Function to find the number of strings of length N such that it is a concatenation it substrings ; Single character cant be repeated ; Check if this state has been already calculated ; Stores the resultant count for the current recursive calls ; Iterate over all divisors ; Non - Repeated = Total - Repeated ; Non - Repeated = Total - Repeated ; Store the result for the further calculation ; Return resultant count ; Driver Code ; Function Call
dp = { } NEW_LINE def countStrings ( N ) : NEW_LINE INDENT if N == 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if dp . get ( N , - 1 ) != - 1 : NEW_LINE INDENT return dp [ N ] NEW_LINE DEDENT ret = 0 NEW_LINE for div in range ( 1 , int ( N ** .5 ) + 1 ) : NEW_LINE INDENT if N % div == 0 : NEW_LINE INDENT ret += ( 1 << div ) - countStrings ( div ) NEW_LINE div2 = N // div NEW_LINE if div2 != div and div != 1 : NEW_LINE INDENT ret += ( 1 << div2 ) - countStrings ( div2 ) NEW_LINE DEDENT DEDENT DEDENT dp [ N ] = ret NEW_LINE return ret NEW_LINE DEDENT N = 6 NEW_LINE print ( countStrings ( N ) ) NEW_LINE
Count N | python program for the above approach ; Function to count N - digit numbers such that each position is divisible by the digit occurring at that position ; Stores the answer . ; Iterate from indices 1 to N ; Stores count of digits that can be placed at the current index ; Iterate from digit 1 to 9 ; If index is divisible by digit ; Multiply answer with possible choices ; Given Input ; Function call
mod = 1000000000 + 7 NEW_LINE def countOfNumbers ( N ) : NEW_LINE INDENT ans = 1 NEW_LINE for index in range ( 1 , N + 1 ) : NEW_LINE INDENT choices = 0 NEW_LINE for digit in range ( 1 , 10 ) : NEW_LINE INDENT if ( index % digit == 0 ) : NEW_LINE INDENT choices += 1 NEW_LINE DEDENT DEDENT ans = ( ans * choices ) % mod NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT N = 5 NEW_LINE countOfNumbers ( N ) NEW_LINE
Maximum number of groups that can receive fresh donuts distributed in batches of size K | Recursive function to find the maximum number of groups that will receive fresh donuts ; Store the result for the current state ; Check if the leftover donuts from the previous batch is 0 ; If true , then one by one give the fresh donuts to each group ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] ; Otherwise , traverse the given array , arr [ ] ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] ; Return the value of q ; Function to find the maximum number of groups that will receive fresh donuts ; Stores count of remainder by K ; Traverse the array arr [ ] ; Stores maximum number of groups ; Return the answer ; Driver Code
def dfs ( arr , left , K ) : NEW_LINE INDENT q = 0 NEW_LINE if ( left == 0 ) : NEW_LINE INDENT for i in range ( 1 , K , 1 ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT arr [ i ] -= 1 NEW_LINE q = max ( q , 1 + dfs ( arr , K - i , K ) ) NEW_LINE arr [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 1 , K , 1 ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT arr [ i ] -= 1 NEW_LINE nleft = left - i if i <= left else K + left - i NEW_LINE q = max ( q , dfs ( arr , nleft , K ) ) NEW_LINE arr [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT return q NEW_LINE DEDENT def maxGroups ( K , arr , n ) : NEW_LINE INDENT V = [ 0 for i in range ( K ) ] NEW_LINE for x in range ( n ) : NEW_LINE INDENT V [ arr [ x ] % K ] += 1 NEW_LINE DEDENT ans = V [ 0 ] + dfs ( V , 0 , K ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( maxGroups ( K , arr , n ) ) NEW_LINE DEDENT
Maximum jumps to reach end of Array with condition that index i can make arr [ i ] jumps | Function to find the maximum jumps to reach end of array ; Stores the jumps needed to reach end from each index ; Traverse the array ; Check if j is less than N ; Add dp [ j ] to the value of dp [ i ] ; Update the value of ans ; Print the value of ans ; Driver Code
def findMaxJumps ( arr , N ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE ans = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT dp [ i ] = arr [ i ] NEW_LINE j = i + arr [ i ] NEW_LINE if ( j < N ) : NEW_LINE INDENT dp [ i ] = dp [ i ] + dp [ j ] NEW_LINE DEDENT ans = max ( ans , dp [ i ] ) NEW_LINE i -= 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 7 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE findMaxJumps ( arr , N ) NEW_LINE DEDENT
Longest subsequence with non negative prefix sum at each position | Function to find the length of the longest subsequence with non negative prefix sum at each position ; Initialize dp array with - 1 ; Maximum subsequence sum by including no elements till position 'i ; Maximum subsequence sum by including first element at first position ; Iterate over all the remaining positions ; If the current element is excluded ; If current element is included and if total sum is positive or not ; Select the maximum j by which a non negative prefix sum subsequence can be obtained ; Print the answer ; Driver Code
def longestSubsequence ( arr , N ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( N + 1 ) ] for i in range ( N ) ] NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 0 NEW_LINE DEDENT dp [ 0 ] [ 1 ] = arr [ 0 ] if arr [ 0 ] >= 0 else - 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 1 , i + 2 ) : NEW_LINE INDENT if ( dp [ i - 1 ] [ j ] != - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j ] ) NEW_LINE DEDENT if ( dp [ i - 1 ] [ j - 1 ] >= 0 and dp [ i - 1 ] [ j - 1 ] + arr [ i ] >= 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - 1 ] + arr [ i ] ) NEW_LINE DEDENT DEDENT DEDENT ans = 0 NEW_LINE for j in range ( N + 1 ) : NEW_LINE INDENT if ( dp [ N - 1 ] [ j ] >= 0 ) : NEW_LINE INDENT ans = j NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 4 , - 4 , 1 , - 3 , 1 , - 3 ] NEW_LINE N = len ( arr ) NEW_LINE longestSubsequence ( arr , N ) NEW_LINE
Count of strictly increasing N | Declaration of dp table ; Function to find the count of all N digit numbers such that all the digit is less than its adjacent digits ; Base Case : If i = n , then return 1 as valid number has been formed ; If the state has already been computed , then return it ; Stores the total count of ways for the current recursive call ; If i = 0 , any digit from [ 1 - 9 ] can be placed and also if N = 1 , then 0 can also be placed ; If i = 1 , any digit from [ 0 - 9 ] can be placed such that digit is not equal to previous digit ; If the current digit is not same as the prev ; Place the current digit such that it is less than the previous digit ; Place current digit such that it is more than the previous digit ; Return the resultant total count ; Function to find all N - digit numbers satisfying the given criteria ; Function call to count all possible ways ; Driver Code
dp = [ [ [ - 1 for x in range ( 2 ) ] for y in range ( 10 ) ] for z in range ( 100 ) ] NEW_LINE def solve ( i , n , prev , sign ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT val = dp [ i ] [ prev ] [ sign ] NEW_LINE if ( val != - 1 ) : NEW_LINE INDENT return val NEW_LINE DEDENT val = 0 NEW_LINE if ( i == 0 ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT digit = 0 NEW_LINE DEDENT else : NEW_LINE INDENT digit = 1 NEW_LINE DEDENT while digit <= 9 : NEW_LINE INDENT val += solve ( i + 1 , n , digit , sign ) NEW_LINE digit += 1 NEW_LINE DEDENT DEDENT elif ( i == 1 ) : NEW_LINE INDENT for digit in range ( 10 ) : NEW_LINE INDENT if ( digit != prev ) : NEW_LINE INDENT val += solve ( i + 1 , n , digit , ( digit > prev ) ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT if ( sign == 1 ) : NEW_LINE INDENT for digit in range ( prev - 1 , - 1 , - 1 ) : NEW_LINE INDENT val += solve ( i + 1 , n , digit , 0 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for digit in range ( prev + 1 , 10 ) : NEW_LINE INDENT val += solve ( i + 1 , n , digit , 1 ) NEW_LINE DEDENT DEDENT DEDENT return val NEW_LINE DEDENT def countNdigitNumber ( N ) : NEW_LINE INDENT print ( solve ( 0 , N , 0 , 0 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE countNdigitNumber ( N ) NEW_LINE DEDENT
Total count of sorted numbers upto N digits in range [ L , R ] ( Magnificent necklace combinatorics problem ) | Function to count total number of ways ; Stores all DP - states ; Stores the result ; Traverse the range [ 0 , N ] ; Traverse the range [ 1 , R - L ] ; Update dp [ i ] [ j ] ; Assign dp [ 0 ] [ R - L ] to ans ; Traverse the range [ 1 , N ] ; Traverse the range [ 1 , R - L ] ; Update dp [ i ] [ j ] ; Increment ans by dp [ i - 1 ] [ j ] ; Return ans ; Driver Code ; Input ; Function call
def Count ( N , L , R ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( R - L + 1 ) ] for i in range ( N ) ] NEW_LINE ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , len ( dp [ 0 ] ) ) : NEW_LINE INDENT dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + 1 NEW_LINE DEDENT ans = dp [ 0 ] [ R - L ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 1 , len ( dp [ 0 ] ) ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] NEW_LINE DEDENT ans += dp [ i ] [ R - L ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE L = 6 NEW_LINE R = 9 NEW_LINE print ( Count ( N , L , R ) ) NEW_LINE DEDENT
Length of largest common subarray in all the rows of given Matrix | Function to find longest common subarray in all the rows of the matrix ; Array to store the position of element in every row ; Traverse the matrix ; Store the position of every element in every row ; Variable to store length of largest common Subarray ; Traverse through the matrix column ; Variable to check if every row has arr [ i ] [ j ] next to arr [ i - 1 ] [ j ] or not ; Traverse through the matrix rows ; Check if arr [ i ] [ j ] is next to arr [ i ] [ j - 1 ] in every row or not ; If every row has arr [ 0 ] [ j ] next to arr [ 0 ] [ j - 1 ] increment len by 1 and update the value of ans ; Driver Code ; Given Input ; Function Call
def largestCommonSubarray ( arr , n , m ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( m + 1 ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT dp [ i ] [ arr [ i ] [ j ] ] = j NEW_LINE DEDENT DEDENT ans = 1 NEW_LINE len1 = 1 NEW_LINE for i in range ( 1 , m , 1 ) : NEW_LINE INDENT check = True NEW_LINE for j in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( dp [ j ] [ arr [ 0 ] [ i - 1 ] ] + 1 != dp [ j ] [ arr [ 0 ] [ i ] ] ) : NEW_LINE INDENT check = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( check ) : NEW_LINE INDENT len1 += 1 NEW_LINE ans = max ( ans , len1 ) NEW_LINE DEDENT else : NEW_LINE INDENT len1 = 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE m = 5 NEW_LINE arr = [ [ 4 , 5 , 1 , 2 , 3 , 6 , 7 ] , [ 1 , 2 , 4 , 5 , 7 , 6 , 3 ] , [ 2 , 7 , 3 , 4 , 5 , 1 , 6 ] ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( arr [ 0 ] ) NEW_LINE print ( largestCommonSubarray ( arr , N , M ) ) NEW_LINE DEDENT
Maximize sum that can be obtained from two given arrays based on given conditions | Function to find the maximum sum that can be obtained from two given arrays based on the following conditions ; Stores the maximum sum from 0 to i ; Initialize the value of dp [ 0 ] [ 0 ] and dp [ 0 ] [ 1 ] ; Traverse the array A [ ] and B [ ] ; If A [ i ] is considered ; If B [ i ] is not considered ; If B [ i ] is considered ; If i = 1 , then consider the value of dp [ i ] [ 1 ] as b [ i ] ; Return maximum sum ; Driver code ; Given input ; Function call
def MaximumSum ( a , b , n ) : NEW_LINE INDENT dp = [ [ - 1 for j in range ( 2 ) ] for i in range ( n ) ] NEW_LINE dp [ 0 ] [ 0 ] = a [ 0 ] NEW_LINE dp [ 0 ] [ 1 ] = b [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] [ 0 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) + a [ i ] NEW_LINE dp [ i ] [ 1 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) NEW_LINE if ( i - 2 >= 0 ) : NEW_LINE INDENT dp [ i ] [ 1 ] = max ( dp [ i ] [ 1 ] , max ( dp [ i - 2 ] [ 0 ] , dp [ i - 2 ] [ 1 ] ) + b [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ 1 ] = max ( dp [ i ] [ 1 ] , b [ i ] ) NEW_LINE DEDENT DEDENT return max ( dp [ n - 1 ] [ 0 ] , dp [ n - 1 ] [ 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 10 , 1 , 10 , 10 ] NEW_LINE B = [ 5 , 50 , 1 , 5 ] NEW_LINE N = len ( A ) NEW_LINE print ( MaximumSum ( A , B , N ) ) NEW_LINE DEDENT
Lexicographically Kth | Python3 program for the above approach ; Function to fill dp array ; Initialize all the entries with 0 ; Update dp [ 0 ] [ 0 ] to 1 ; Traverse the dp array ; Update the value of dp [ i ] [ j ] ; Recursive function to find the Kth lexicographical smallest string ; Handle the base cases ; If there are more than or equal to K strings which start with a , then the first character is 'a ; Otherwise the first character of the resultant string is 'b ; Function to find the Kth lexicographical smallest string ; Function call to fill the dp array ; Print the resultant ; Given Input ; Function Call
from typing import Mapping NEW_LINE MAX = 30 NEW_LINE def findNumString ( X , Y , dp ) : NEW_LINE INDENT for i in range ( 0 , MAX ) : NEW_LINE INDENT for j in range ( 0 , MAX ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 0 , X + 1 ) : NEW_LINE INDENT for j in range ( 0 , Y + 1 ) : NEW_LINE INDENT if ( i > 0 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i - 1 ] [ j ] NEW_LINE DEDENT if ( j > 0 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def kthString ( X , Y , K , dp ) : NEW_LINE INDENT x1 = " " NEW_LINE y1 = " " NEW_LINE for i in range ( 0 , Y ) : NEW_LINE INDENT x1 += ' b ' NEW_LINE DEDENT for i in range ( 0 , X ) : NEW_LINE INDENT y1 += ' a ' NEW_LINE DEDENT if ( X == 0 ) : NEW_LINE INDENT return x1 NEW_LINE DEDENT if ( Y == 0 ) : NEW_LINE INDENT return y1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( K <= dp [ X - 1 ] [ Y ] ) : NEW_LINE INDENT return " a " + kthString ( X - 1 , Y , K , dp ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT else : NEW_LINE INDENT return " b " + kthString ( X , Y - 1 , K - dp [ X - 1 ] [ Y ] , dp ) NEW_LINE DEDENT DEDENT def kthStringUtil ( X , Y , K ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( MAX ) ] for col in range ( MAX ) ] NEW_LINE findNumString ( X , Y , dp ) NEW_LINE print ( kthString ( X , Y , K , dp ) ) NEW_LINE DEDENT X = 4 NEW_LINE Y = 3 NEW_LINE K = 4 NEW_LINE kthStringUtil ( X , Y , K ) NEW_LINE
Maximum Tip Calculator | Function that finds the maximum tips from the given arrays as per the given conditions ; Base Condition ; If both have non - zero count then return max element from both array ; Traverse first array , as y count has become 0 ; Traverse 2 nd array , as x count has become 0 ; Drive Code ; Function Call
def maximumTip ( arr1 , arr2 , n , x , y ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if x != 0 and y != 0 : NEW_LINE INDENT return max ( arr1 [ n - 1 ] + maximumTip ( arr1 , arr2 , n - 1 , x - 1 , y ) , arr2 [ n - 1 ] + maximumTip ( arr1 , arr2 , n - 1 , x , y - 1 ) ) NEW_LINE DEDENT if y == 0 : NEW_LINE INDENT return arr1 [ n - 1 ] + maximumTip ( arr1 , arr2 , n - 1 , x - 1 , y ) NEW_LINE DEDENT else : NEW_LINE INDENT return arr2 [ n - 1 ] + maximumTip ( arr1 , arr2 , n - 1 , x , y - 1 ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE X = 3 NEW_LINE Y = 3 NEW_LINE A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE B = [ 5 , 4 , 3 , 2 , 1 ] NEW_LINE print ( maximumTip ( A , B , N , X , Y ) ) NEW_LINE
Number of ways such that only K bars are visible from the left | Function to calculate the number of bars that are visible from the left for a particular arrangement ; If current element is greater than the last greater element , it is visible ; Function to calculate the number of rearrangements where K bars are visiblef from the left ; Vector to store current permutation ; Check for all permutations ; If current permutation meets the conditions , increment answer ; Driver code ; Input ; Function call
def noOfbarsVisibleFromLeft ( v ) : NEW_LINE INDENT last = 0 NEW_LINE ans = 0 NEW_LINE for u in v : NEW_LINE INDENT if ( last < u ) : NEW_LINE INDENT ans += 1 NEW_LINE last = u NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def nextPermutation ( nums ) : NEW_LINE INDENT i = len ( nums ) - 2 NEW_LINE while i > - 1 : NEW_LINE INDENT if nums [ i ] < nums [ i + 1 ] : NEW_LINE INDENT j = len ( nums ) - 1 NEW_LINE while j > i : NEW_LINE INDENT if nums [ j ] > nums [ i ] : NEW_LINE INDENT break NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT nums [ i ] , nums [ j ] = nums [ j ] , nums [ i ] NEW_LINE break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT nums [ i + 1 : ] = reversed ( nums [ i + 1 : ] ) NEW_LINE return nums NEW_LINE DEDENT def KvisibleFromLeft ( N , K ) : NEW_LINE INDENT v = [ 0 ] * ( N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT v [ i ] = i + 1 NEW_LINE DEDENT ans = 0 NEW_LINE temp = list ( v ) NEW_LINE while True : NEW_LINE INDENT if ( noOfbarsVisibleFromLeft ( v ) == K ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT v = nextPermutation ( v ) NEW_LINE if v == temp : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 2 NEW_LINE print ( KvisibleFromLeft ( N , K ) ) NEW_LINE DEDENT
Number of ways such that only K bars are visible from the left | Function to calculate the number of permutations of N , where only K bars are visible from the left . ; Only ascending order is possible ; N is placed at the first position The nest N - 1 are arranged in ( N - 1 ) ! ways ; Recursing ; Driver code ; Input ; Function call
def KvisibleFromLeft ( N , K ) : NEW_LINE INDENT if ( N == K ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( K == 1 ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT ans *= i NEW_LINE DEDENT return ans NEW_LINE DEDENT return KvisibleFromLeft ( N - 1 , K - 1 ) + ( N - 1 ) * KvisibleFromLeft ( N - 1 , K ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 2 NEW_LINE print ( KvisibleFromLeft ( N , K ) ) NEW_LINE DEDENT
Minimum deletions in Array to make difference of adjacent elements non | Function for finding minimum deletions so that the array becomes non decreasing and the difference between adjacent elements also becomes non decreasing ; initialize answer to a large value ; generating all subsets ; checking the first condition ; checking the second condition ; if both conditions are satisfied consider the answer for minimum ; Driver code ; Input ; Function call
def minimumDeletions ( A , N ) : NEW_LINE INDENT ans = 10 ** 8 NEW_LINE for i in range ( 1 , ( 1 << N ) ) : NEW_LINE INDENT temp = [ ] NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( ( i & ( 1 << j ) ) != 0 ) : NEW_LINE INDENT temp . append ( A [ j ] ) NEW_LINE DEDENT DEDENT flag = 0 NEW_LINE for j in range ( 1 , len ( temp ) ) : NEW_LINE INDENT if ( temp [ j ] < temp [ j - 1 ] ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT for j in range ( 1 , len ( temp ) - 1 ) : NEW_LINE INDENT if ( temp [ j ] - temp [ j - 1 ] > temp [ j + 1 ] - temp [ j ] ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT ans = min ( ans , N - len ( temp ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 4 , 5 , 7 , 20 , 21 ] NEW_LINE N = len ( A ) NEW_LINE print ( minimumDeletions ( A , N ) ) NEW_LINE DEDENT
Find maximum subset | Function to calculate maximum sum possible by taking at most K elements that is divisibly by D ; Variable to store final answer ; Traverse all subsets ; Update ans if necessary conditions are satisfied ; Driver code ; Input ; Function call
def maximumSum ( A , N , K , D ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( ( 1 << N ) ) : NEW_LINE INDENT sum = 0 NEW_LINE c = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( i >> j & 1 ) : NEW_LINE INDENT sum += A [ j ] NEW_LINE c += 1 NEW_LINE DEDENT DEDENT if ( sum % D == 0 and c <= K ) : NEW_LINE INDENT ans = max ( ans , sum ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 3 NEW_LINE D = 7 NEW_LINE A = [ 1 , 11 , 5 , 5 , 18 ] NEW_LINE print ( maximumSum ( A , N , K , D ) ) NEW_LINE DEDENT
Find the longest subsequence of a string that is a substring of another string | Function to find the longest subsequence that matches with the substring of other string ; Stores the lengths of strings X and Y ; Create a matrix ; Initialize the matrix ; Fill all the remaining rows ; If the characters are equal ; If not equal , then just move to next in subsequence string ; Find maximum length of the longest subsequence matching substring of other string ; Iterate through the last row of matrix ; Store the required string ; Backtrack from the cell ; If equal , then add the character to res string ; Return the required string ; Driver code
def longestSubsequence ( X , Y ) : NEW_LINE INDENT n = len ( X ) NEW_LINE m = len ( Y ) NEW_LINE mat = [ [ 0 for i in range ( m + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT for j in range ( 0 , m + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT mat [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT mat [ i ] [ j ] = 1 + mat [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT mat [ i ] [ j ] = mat [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT len1 = 0 NEW_LINE col = 0 NEW_LINE for i in range ( 0 , m + 1 ) : NEW_LINE INDENT if ( mat [ n ] [ i ] > len1 ) : NEW_LINE INDENT len1 = mat [ n ] [ i ] NEW_LINE col = i NEW_LINE DEDENT DEDENT res = " " NEW_LINE i = n NEW_LINE j = col NEW_LINE while ( len1 > 0 ) : NEW_LINE INDENT if ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT res = X [ i - 1 ] + res NEW_LINE i -= 1 NEW_LINE j -= 1 NEW_LINE len1 -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT X = " ABCD " NEW_LINE Y = " ACDBDCD " NEW_LINE print ( longestSubsequence ( X , Y ) ) NEW_LINE
Divide chocolate bar into pieces , minimizing the area of invalid pieces | Python3 program for the above approach ; Store valid dimensions ; Stores memoization ; Utility function to calculate minimum invalid area for Chocolate piece having dimension ( l , r ) ; Check whether current piece is valid or not If it is , then return zero for current dimension ; Making all possible horizontal cuts , one by one and calculating the sum of minimum invalid area for both the resulting pieces ; Making all possible vertical cuts , one by one and calculating the sum of minimum invalid area for both the resulting pieces ; Store the computed result ; Function to calculate minimum invalid area for Chocolate piece having dimension ( l , r ) ; Total number of valid dimensions ; Storing valid dimensions as for every ( x , y ) both ( x , y ) and ( y , x ) are valid ; Fill dp [ ] [ ] table with - 1 , indicating that results are not computed yet ; Stores minimum area ; PrminArea as the output ; Driver Code ; Given N & M ; Given valid dimensions ; Function Call
sz = 1001 NEW_LINE ok = [ [ 0 for i in range ( sz ) ] for i in range ( sz ) ] NEW_LINE dp = [ [ 0 for i in range ( sz ) ] for i in range ( sz ) ] NEW_LINE def minInvalidAreaUtil ( l , b ) : NEW_LINE INDENT global dp , ok NEW_LINE if ( dp [ l ] [ b ] == - 1 ) : NEW_LINE INDENT if ( ok [ l ] [ b ] ) : NEW_LINE INDENT dp [ l ] [ b ] = 0 NEW_LINE return dp [ l ] [ b ] NEW_LINE DEDENT ans = l * b NEW_LINE for i in range ( 1 , b ) : NEW_LINE INDENT ans = min ( ans , minInvalidAreaUtil ( l , i ) + minInvalidAreaUtil ( l , b - i ) ) NEW_LINE DEDENT for i in range ( 1 , l ) : NEW_LINE INDENT ans = min ( ans , minInvalidAreaUtil ( i , b ) + minInvalidAreaUtil ( l - i , b ) ) NEW_LINE DEDENT dp [ l ] [ b ] = ans NEW_LINE DEDENT return dp [ l ] [ b ] NEW_LINE DEDENT def minInvalidArea ( N , M , dimensions ) : NEW_LINE INDENT global dp , ok NEW_LINE K = len ( dimensions ) NEW_LINE for i in range ( K ) : NEW_LINE INDENT ok [ dimensions [ i ] [ 0 ] ] [ dimensions [ i ] [ 1 ] ] = 1 NEW_LINE ok [ dimensions [ i ] [ 1 ] ] [ dimensions [ i ] [ 0 ] ] = 1 NEW_LINE DEDENT for i in range ( sz ) : NEW_LINE INDENT for j in range ( sz ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT minArea = minInvalidAreaUtil ( N , M ) NEW_LINE print ( minArea ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , M = 10 , 10 NEW_LINE dimensions = [ [ 3 , 5 ] ] NEW_LINE minInvalidArea ( N , M , dimensions ) NEW_LINE DEDENT
Count unordered pairs of equal elements for all subarrays | Function to count all pairs ( i , j ) such that arr [ i ] equals arr [ j ] in all possible subarrays of the array ; Stores the size of the array ; Stores the positions of all the distinct elements ; Append index corresponding to arr [ i ] in the map ; Traverse the map M ; Traverse the array ; Update the value of ans ; Update the value of the sum ; Print the value of ans ; Driver Code
def countPairs ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE ans = 0 NEW_LINE M = { } NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if arr [ i ] in M : NEW_LINE INDENT M [ arr [ i ] ] . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT M [ arr [ i ] ] = [ i ] NEW_LINE DEDENT DEDENT for key , value in M . items ( ) : NEW_LINE INDENT v = value NEW_LINE sum1 = 0 NEW_LINE for j in range ( len ( v ) ) : NEW_LINE INDENT ans += ( sum1 * ( N - v [ j ] ) ) NEW_LINE sum1 += v [ j ] + 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 1 ] NEW_LINE countPairs ( arr ) NEW_LINE DEDENT
Number of alternating substrings from a given Binary String | Function to count number of alternating substrings from a given binary string ; Initialize dp array , where dp [ i ] [ j ] stores the number of alternating strings starts with i and having j elements . ; Traverse the string from the end ; If i is equal to N - 1 ; Otherwise , ; Increment count of substrings starting at i and has 0 in the beginning ; Increment count of substrings starting at i and has 1 in the beginning ; Stores the result ; Iterate in the range [ 0 , N - 1 ] ; Update ans ; Return the ans ; Driver code ; Given Input ; Function call
def countAlternatingSubstrings ( S , N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( N ) ] for i in range ( 2 ) ] NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( i == N - 1 ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT dp [ 1 ] [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 + dp [ 1 ] [ i + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 1 ] [ i ] = 1 + dp [ 0 ] [ i + 1 ] NEW_LINE DEDENT DEDENT DEDENT ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT ans += max ( dp [ 0 ] [ i ] , dp [ 1 ] [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "0010" NEW_LINE N = len ( S ) NEW_LINE print ( countAlternatingSubstrings ( S , N ) ) NEW_LINE DEDENT
Count ways to place ' + ' and ' | Function to count number of ways ' + ' and ' - ' operators can be placed in front of array elements to make the sum of array elements equal to K ; Stores sum of the array ; Stores count of 0 s in A [ ] ; Traverse the array ; Update sum ; Update count of 0 s ; Conditions where no arrangements are possible which adds up to K ; Required sum ; Dp array ; Base cases ; Fill the dp array ; Return answer ; Driver Code ; Input ; Function call
def solve ( A , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE c = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE if ( A [ i ] == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( K > sum or ( sum + K ) % 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT sum = ( sum + K ) // 2 NEW_LINE dp = [ [ 0 for i in range ( sum + 1 ) ] for j in range ( N + 1 ) ] NEW_LINE for i in range ( sum + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 0 NEW_LINE DEDENT for i in range ( N + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT for j in range ( 1 , sum + 1 , 1 ) : NEW_LINE INDENT if ( A [ i - 1 ] <= j and A [ i - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j - A [ i - 1 ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return dp [ N ] [ sum ] + pow ( 2 , c ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 1 , 2 , 3 ] NEW_LINE N = len ( A ) NEW_LINE K = 3 NEW_LINE print ( solve ( A , N , K ) ) NEW_LINE DEDENT
Rearrange an array to maximize sum of Bitwise AND of same | Function to implement recursive DP ; If i is equal to N ; If dp [ i ] [ mask ] is not equal to - 1 ; Iterate over the array B [ ] ; If current element is not yet selected ; Update dp [ i ] [ mask ] ; Return dp [ i ] [ mask ] ; Function to obtain maximum sum of Bitwise AND of same - indexed elements from the arrays A [ ] and B [ ] ; Stores all dp - states ; Returns the maximum value returned by the function maximizeAnd ( ) ; Driver Code
def maximizeAnd ( i , mask , A , B , N , dp ) : NEW_LINE INDENT if ( i == N ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ mask ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ mask ] NEW_LINE DEDENT for j in range ( N ) : NEW_LINE INDENT if ( ( mask & ( 1 << j ) ) == 0 ) : NEW_LINE INDENT dp [ i ] [ mask ] = max ( dp [ i ] [ mask ] , ( A [ i ] & B [ j ] ) + maximizeAnd ( i + 1 , mask | ( 1 << j ) , A , B , N , dp ) ) NEW_LINE DEDENT DEDENT return dp [ i ] [ mask ] NEW_LINE DEDENT def maximizeAndUtil ( A , B , N ) : NEW_LINE INDENT temp = [ - 1 for i in range ( 1 << N + 1 ) ] NEW_LINE dp = [ temp for i in range ( N ) ] NEW_LINE return maximizeAnd ( 0 , 0 , A , B , N , dp ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 5 , 7 , 11 ] NEW_LINE B = [ 2 , 6 , 10 , 12 ] NEW_LINE N = len ( A ) NEW_LINE print ( maximizeAndUtil ( A , B , N ) ) NEW_LINE DEDENT
Find the winner of a game of removing at most 3 stones from a pile in each turn | Function to find the maximum score of Player 1 ; Base Case ; If the result is already computed , then return the result ; Variable to store maximum score ; Pick one stone ; Pick 2 stones ; Pick 3 stones ; Return the score of the player ; Function to find the winner of the game ; Create a 1D table , dp of size N ; Store the result ; Player 1 wins ; PLayer 2 wins ; Tie ; Given Input ; Function Call
def maximumStonesUtil ( arr , n , i , dp ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = dp [ i ] NEW_LINE if ( ans != - 1 ) : NEW_LINE INDENT return ans NEW_LINE DEDENT ans = - 2 ** 31 NEW_LINE ans = max ( ans , arr [ i ] - maximumStonesUtil ( arr , n , i + 1 , dp ) ) NEW_LINE if ( i + 1 < n ) : NEW_LINE INDENT ans = max ( ans , arr [ i ] + arr [ i + 1 ] - maximumStonesUtil ( arr , n , i + 2 , dp ) ) NEW_LINE DEDENT if ( i + 2 < n ) : NEW_LINE INDENT ans = max ( ans , arr [ i ] + arr [ i + 1 ] + arr [ i + 2 ] - maximumStonesUtil ( arr , n , i + 3 , dp ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def maximumStones ( arr , n ) : NEW_LINE INDENT dp = [ - 1 ] * n NEW_LINE res = maximumStonesUtil ( arr , n , 0 , dp ) NEW_LINE if ( res > 0 ) : NEW_LINE INDENT return " Player1" NEW_LINE DEDENT elif ( res < 0 ) : NEW_LINE INDENT return " Player2" NEW_LINE DEDENT else : NEW_LINE INDENT return " Tie " NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maximumStones ( arr , n ) ) NEW_LINE
Count ways to reach the Nth station | Function to find the number of ways to reach Nth station ; Declares the DP [ ] array ; Only 1 way to reach station 1 ; Find the remaining states from the 2 nd station ; If the train A is present at station i - 1 ; If the train B is present at station i - 2 ; If train C is present at station i - 3 ; The total number of ways to reach station i ; Return the total count of ways ; Driver Code
def numberOfWays ( N ) : NEW_LINE INDENT DP = [ [ 0 for i in range ( 5 ) ] for i in range ( N + 1 ) ] NEW_LINE DP [ 1 ] [ 1 ] = 1 NEW_LINE DP [ 1 ] [ 2 ] = 1 NEW_LINE DP [ 1 ] [ 3 ] = 1 NEW_LINE DP [ 1 ] [ 4 ] = 1 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( i - 1 > 0 and DP [ i - 1 ] [ 1 ] > 0 ) : NEW_LINE INDENT DP [ i ] [ 1 ] = DP [ i - 1 ] [ 4 ] NEW_LINE DEDENT if ( i - 2 > 0 and DP [ i - 2 ] [ 2 ] > 0 ) : NEW_LINE INDENT DP [ i ] [ 2 ] = DP [ i - 2 ] [ 4 ] NEW_LINE DEDENT if ( i - 3 > 0 and DP [ i - 3 ] [ 3 ] > 0 ) : NEW_LINE INDENT DP [ i ] [ 3 ] = DP [ i - 3 ] [ 4 ] NEW_LINE DEDENT DP [ i ] [ 4 ] = ( DP [ i ] [ 1 ] + DP [ i ] [ 2 ] + DP [ i ] [ 3 ] ) NEW_LINE DEDENT return DP [ N ] [ 4 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 15 NEW_LINE print ( numberOfWays ( N ) ) NEW_LINE DEDENT
Number of M | Function to find the number of M - length sorted arrays possible using numbers from the range [ 1 , N ] ; If size becomes equal to m , that means an array is found ; Include current element , increase size by 1 and remain on the same element as it can be included again ; Exclude current element ; Return the sum obtained in both the cases ; Driver Code ; Given Input ; Function Call
def countSortedArrays ( start , m , size , n ) : NEW_LINE INDENT if ( size == m ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( start > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT notTaken , taken = 0 , 0 NEW_LINE taken = countSortedArrays ( start , m , size + 1 , n ) NEW_LINE notTaken = countSortedArrays ( start + 1 , m , size , n ) NEW_LINE return taken + notTaken NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n , m = 2 , 3 NEW_LINE print ( countSortedArrays ( 1 , m , 0 , n ) ) NEW_LINE DEDENT
Maximum subarray sum possible after removing at most one subarray | Function to find maximum subarray sum possible after removing at most one subarray ; Calculate the preSum [ ] array ; Update the value of sum ; Update the value of maxSum ; Update the value of preSum [ i ] ; Calculate the postSum [ ] array ; Update the value of sum ; Update the value of maxSum ; Update the value of postSum [ i ] ; Stores the resultant maximum sum of subarray ; Update the value of ans ; Print resultant sum ; Driver code
def maximumSum ( arr , n ) : NEW_LINE INDENT preSum = [ 0 ] * n NEW_LINE sum = 0 NEW_LINE maxSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = max ( arr [ i ] , sum + arr [ i ] ) NEW_LINE maxSum = max ( maxSum , sum ) NEW_LINE preSum [ i ] = maxSum NEW_LINE DEDENT sum = 0 NEW_LINE maxSum = 0 NEW_LINE postSum = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum = max ( arr [ i ] , sum + arr [ i ] ) NEW_LINE maxSum = max ( maxSum , sum ) NEW_LINE postSum [ i ] = maxSum NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = max ( ans , preSum [ i ] + postSum [ i + 1 ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 7 , 6 , - 1 , - 4 , - 5 , 7 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE maximumSum ( arr , N ) NEW_LINE
Count all unique outcomes possible by performing S flips on N coins | Function to recursively count the number of unique outcomes possible S flips are performed on N coins ; Base Cases ; Recursive Calls ; Driver Code
def numberOfUniqueOutcomes ( N , S ) : NEW_LINE INDENT if ( S < N ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( N == 1 or N == S ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( numberOfUniqueOutcomes ( N - 1 , S - 1 ) + numberOfUniqueOutcomes ( N - 1 , S - 2 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , S = 3 , 4 NEW_LINE print ( numberOfUniqueOutcomes ( N , S ) ) NEW_LINE DEDENT
Length of longest increasing subsequence in a string | Function to find length of longest increasing subsequence in a string ; Stores at every i - th index , the length of the longest increasing subsequence ending with character i ; Size of string ; Stores the length of LIS ; Iterate over each character of the string ; Store position of the current character ; Stores the length of LIS ending with current character ; Check for all characters less then current character ; Include current character ; Update length of longest increasing subsequence ; Updating LIS for current character ; Return the length of LIS ; Driver Code
def lisOtimised ( s ) : NEW_LINE INDENT dp = [ 0 ] * 30 NEW_LINE N = len ( s ) NEW_LINE lis = - 10 ** 9 NEW_LINE for i in range ( N ) : NEW_LINE INDENT val = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE curr = 0 NEW_LINE for j in range ( val ) : NEW_LINE INDENT curr = max ( curr , dp [ j ] ) NEW_LINE DEDENT curr += 1 NEW_LINE lis = max ( lis , curr ) NEW_LINE dp [ val ] = max ( dp [ val ] , curr ) NEW_LINE DEDENT return lis NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " fdryutiaghfse " NEW_LINE print ( lisOtimised ( s ) ) NEW_LINE DEDENT
Sum of length of two smallest subsets possible from a given array with sum at least K | Python3 program for the above approach ; Function to calculate sum of lengths of two smallest subsets with sum >= K ; Sort the array in ascending order ; Stores suffix sum of the array ; Update the suffix sum array ; Stores all dp - states ; Initialize all dp - states with a maximum possible value ; Base Case ; Traverse the array arr [ ] ; Iterate over the range [ 0 , K ] ; If A [ i ] is equal to at least the required sum j for the current state ; If the next possible state doesn 't exist ; Otherwise , update the current state to the minimum of the next state and state including the current element A [ i ] ; Traverse the suffix sum array ; If suffix [ i ] - dp [ i ] [ K ] >= K ; Sum of lengths of the two smallest subsets is obtained ; Return - 1 , if there doesn 't exist any subset of sum >= K ; Driver Code
MAX = 1e9 NEW_LINE def MinimumLength ( A , N , K ) : NEW_LINE INDENT A . sort ( ) NEW_LINE suffix = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT suffix [ i ] = suffix [ i + 1 ] + A [ i ] NEW_LINE DEDENT dp = [ [ 0 ] * ( K + 1 ) ] * ( N + 1 ) NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT for j in range ( K + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = MAX NEW_LINE DEDENT DEDENT dp [ N ] [ 0 ] = 0 NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( K , - 1 , - 1 ) : NEW_LINE INDENT if ( j <= A [ i ] ) : NEW_LINE INDENT dp [ i ] [ j ] = A [ i ] NEW_LINE continue NEW_LINE DEDENT if ( dp [ i + 1 ] [ j - A [ i ] ] == MAX ) : NEW_LINE INDENT dp [ i ] [ j ] = MAX NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i + 1 ] [ j ] , dp [ i + 1 ] [ j - A [ i ] ] + A [ i ] ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( suffix [ i ] - dp [ i ] [ K ] >= K ) : NEW_LINE INDENT return N - i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 7 , 4 , 5 , 6 , 8 ] NEW_LINE K = 13 NEW_LINE N = len ( arr ) NEW_LINE print ( MinimumLength ( arr , N , K ) ) NEW_LINE
Count distinct possible Bitwise XOR values of subsets of an array | Stores the mask of the vector ; Stores the current 20 of dp [ ] ; Function to store the mask of given integer ; Iterate over the range [ 0 , 20 ] ; If i - th bit 0 ; If dp [ i ] is zero ; Store the position in dp ; Increment the answer ; Return from the loop ; mask = mask XOR dp [ i ] ; Function to find the 20 of the set having Bitwise XOR of all the subset of the given array ; Traverse the array ; Prthe answer ; Driver Code ; Function Call
dp = [ 0 ] * 20 NEW_LINE ans = 0 NEW_LINE def insertVector ( mask ) : NEW_LINE INDENT global dp , ans NEW_LINE for i in range ( 20 ) : NEW_LINE INDENT if ( ( mask & 1 << i ) == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( not dp [ i ] ) : NEW_LINE INDENT dp [ i ] = mask NEW_LINE ans += 1 NEW_LINE return NEW_LINE DEDENT mask ^= dp [ i ] NEW_LINE DEDENT DEDENT def maxSizeSet ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT insertVector ( arr [ i ] ) NEW_LINE DEDENT print ( ( 1 << ans ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE maxSizeSet ( arr , N ) NEW_LINE DEDENT
Maximize sum possible from an array by jumps of length i + K * arr [ i ] from any ith index | Function to find the maximum sum possible by jumps of length i + K * arr [ i ] from any i - th index ; Initialize an array dp [ ] ; Stores the maximum sum ; Iterate over the range [ N - 1 , 0 ] ; If length of the jump exceeds N ; Set dp [ i ] as arr [ i ] ; Otherwise , update dp [ i ] as sum of dp [ i + K * arr [ i ] ] and arr [ i ] ; Update the overall maximum sum ; Print the answer ; Driver Code
def maxSum ( arr , N , K ) : NEW_LINE INDENT dp = [ 0 for i in range ( N + 2 ) ] NEW_LINE maxval = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( ( i + K * arr [ i ] ) >= N ) : NEW_LINE INDENT dp [ i ] = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = dp [ i + K * arr [ i ] ] + arr [ i ] NEW_LINE DEDENT maxval = max ( maxval , dp [ i ] ) NEW_LINE i -= 1 NEW_LINE DEDENT print ( maxval ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 3 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE maxSum ( arr , N , K ) NEW_LINE DEDENT
Maximum sum submatrix | Function to find maximum sum submatrix ; Stores the number of rows and columns in the matrix ; Stores maximum submatrix sum ; Take each row as starting row ; Take each column as the starting column ; Take each row as the ending row ; Take each column as the ending column ; Stores the sum of submatrix having topleft index ( i , j ) and bottom right index ( k , l ) ; Iterate the submatrix row - wise and calculate its sum ; Update the maximum sum ; Prthe answer ; Driver Code
def maxSubmatrixSum ( matrix ) : NEW_LINE INDENT r = len ( matrix ) NEW_LINE c = len ( matrix [ 0 ] ) NEW_LINE maxSubmatrix = 0 NEW_LINE for i in range ( r ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT for k in range ( i , r ) : NEW_LINE INDENT for l in range ( j , c ) : NEW_LINE INDENT sumSubmatrix = 0 NEW_LINE for m in range ( i , k + 1 ) : NEW_LINE INDENT for n in range ( j , l + 1 ) : NEW_LINE INDENT sumSubmatrix += matrix [ m ] [ n ] NEW_LINE DEDENT DEDENT maxSubmatrix = max ( maxSubmatrix , sumSubmatrix ) NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( maxSubmatrix ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT matrix = [ [ 0 , - 2 , - 7 , 0 ] , [ 9 , 2 , - 6 , 2 ] , [ - 4 , 1 , - 4 , 1 ] , [ - 1 , 8 , 0 , - 2 ] ] NEW_LINE maxSubmatrixSum ( matrix ) NEW_LINE DEDENT
Maximize sum of subsets from two arrays having no consecutive values | Function to calculate maximum subset sum ; Initialize array to store dp states ; Base Cases ; Pre initializing for dp [ 0 ] & dp [ 1 ] ; Calculating dp [ index ] based on above formula ; Prmaximum subset sum ; Given arrays ; Length of the array
def maximumSubsetSum ( arr1 , arr2 , length ) : NEW_LINE INDENT dp = [ 0 ] * ( length + 1 ) NEW_LINE if ( length == 1 ) : NEW_LINE INDENT print ( max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) NEW_LINE return NEW_LINE DEDENT if ( length == 2 ) : NEW_LINE INDENT print ( max ( max ( arr1 [ 1 ] , arr2 [ 1 ] ) , max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0 ] = max ( arr1 [ 0 ] , arr2 [ 0 ] ) NEW_LINE dp [ 1 ] = max ( max ( arr1 [ 1 ] , arr2 [ 1 ] ) , max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) NEW_LINE index = 2 NEW_LINE while ( index < length ) : NEW_LINE INDENT dp [ index ] = max ( max ( arr1 [ index ] , arr2 [ index ] ) , max ( max ( arr1 [ index ] + dp [ index - 2 ] , arr2 [ index ] + dp [ index - 2 ] ) , dp [ index - 1 ] ) ) NEW_LINE index += 1 NEW_LINE DEDENT print ( dp [ length - 1 ] ) NEW_LINE DEDENT DEDENT arr1 = [ - 1 , - 2 , 4 , - 4 , 5 ] NEW_LINE arr2 = [ - 1 , - 2 , - 3 , 4 , 10 ] NEW_LINE length = 5 NEW_LINE maximumSubsetSum ( arr1 , arr2 , length ) NEW_LINE
Modify array by replacing every array element with minimum possible value of arr [ j ] + | j | Function to find minimum value of arr [ j ] + | j - i | for every array index ; Stores minimum of a [ j ] + | i - j | upto position i ; Stores minimum of a [ j ] + | i - j | upto position i from the end ; Traversing and storing minimum of a [ j ] + | i - j | upto i ; Traversing and storing minimum of a [ j ] + | i - j | upto i from the end ; Traversing from [ 0 , N ] and storing minimum of a [ j ] + | i - j | from starting and end ; Print the required array ; Driver code ; Given array arr ; Size of the array ; Function Call
def minAtEachIndex ( n , arr ) : NEW_LINE INDENT dp1 = [ 0 ] * n NEW_LINE dp2 = [ 0 ] * n NEW_LINE i = 0 NEW_LINE dp1 [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp1 [ i ] = min ( arr [ i ] , dp1 [ i - 1 ] + 1 ) NEW_LINE DEDENT dp2 [ n - 1 ] = arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT dp2 [ i ] = min ( arr [ i ] , dp2 [ i + 1 ] + 1 ) NEW_LINE DEDENT v = [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT v . append ( min ( dp1 [ i ] , dp2 [ i ] ) ) NEW_LINE DEDENT for x in v : NEW_LINE INDENT print ( x , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 2 , 5 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE minAtEachIndex ( N , arr ) NEW_LINE DEDENT
Count all N | Function to prthe count of arrays satisfying given condition ; First element of array is set as 1 ; Since the first element of arr is 1 , the second element can 't be 1 ; Traverse the remaining indices ; If arr [ i ] = 1 ; If arr [ i ] a 1 ; Since last element needs to be 1 ; Driver Code ; Stores the count of arrays where arr [ 0 ] = arr [ N - 1 ] = 1 ; Since arr [ 0 ] and arr [ N - 1 ] can be any number from 1 to M ; Pranswer
def totalArrays ( N , M ) : NEW_LINE INDENT end_with_one = [ 0 ] * ( N + 1 ) ; NEW_LINE end_not_with_one = [ 0 ] * ( N + 1 ) ; NEW_LINE end_with_one [ 0 ] = 1 ; NEW_LINE end_not_with_one [ 0 ] = 0 ; NEW_LINE end_with_one [ 1 ] = 0 ; NEW_LINE end_not_with_one [ 1 ] = M - 1 ; NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT end_with_one [ i ] = end_not_with_one [ i - 1 ] ; NEW_LINE end_not_with_one [ i ] = end_with_one [ i - 1 ] * ( M - 1 ) + end_not_with_one [ i - 1 ] * ( M - 2 ) ; NEW_LINE DEDENT return end_with_one [ N - 1 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 ; NEW_LINE M = 3 ; NEW_LINE temp = totalArrays ( N , M ) ; NEW_LINE ans = M * temp ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT
Count numbers from a given range whose product of digits is K | Function to find the product of digits of a number ; Stores product of digits of N ; Update res ; Update N ; Function to count numbers in the range [ 0 , X ] whose product of digit is K ; Stores count of numbers in the range [ L , R ] whose product of digit is K ; Iterate over the range [ L , R ] ; If product of digits of i equal to K ; Update cnt ; Driver Code
def prodOfDigit ( N ) : NEW_LINE INDENT res = 1 NEW_LINE while ( N ) : NEW_LINE INDENT res = res * ( N % 10 ) NEW_LINE N //= 10 NEW_LINE DEDENT return res NEW_LINE DEDENT def cntNumRange ( L , R , K ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( prodOfDigit ( i ) == K ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R , K = 20 , 10000 , 14 NEW_LINE print ( cntNumRange ( L , R , K ) ) NEW_LINE DEDENT
Median of Bitwise XOR of all submatrices starting from the top left corner | Function to find the median of bitwise XOR of all the submatrix whose topmost leftmost corner is ( 0 , 0 ) ; dp [ i ] [ j ] : Stores the bitwise XOR of submatrix having top left corner at ( 0 , 0 ) and bottom right corner at ( i , j ) ; Stores count of submatrix ; Base Case ; Base Case ; Fill dp using tabulation ; Fill dp [ i ] [ j ] ; Driver code
def findMedXOR ( mat , N , M ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( M ) ] for j in range ( N ) ] ; NEW_LINE med = [ 0 ] * ( N * M ) ; NEW_LINE dp [ 0 ] [ 0 ] = mat [ 0 ] [ 0 ] ; NEW_LINE med [ 0 ] = dp [ 0 ] [ 0 ] ; NEW_LINE len = 1 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] ^ mat [ i ] [ 0 ] ; NEW_LINE med [ len ] = dp [ i ] [ 0 ] ; NEW_LINE len += 1 ; NEW_LINE DEDENT for i in range ( 1 , M ) : NEW_LINE INDENT dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] ^ mat [ 0 ] [ i ] ; NEW_LINE med [ len ] = dp [ 0 ] [ i ] ; NEW_LINE len += 1 NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 1 , M ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ^ dp [ i ] [ j - 1 ] ^ dp [ i - 1 ] [ j - 1 ] ^ mat [ i ] [ j ] ; NEW_LINE med [ len ] = dp [ i ] [ j ] ; NEW_LINE len += 1 NEW_LINE DEDENT DEDENT med . sort ( ) ; NEW_LINE if ( len % 2 == 0 ) : NEW_LINE INDENT return ( med [ ( len // 2 ) ] + med [ ( len // 2 ) - 1 ] ) / 2.0 ; NEW_LINE DEDENT return med [ len // 2 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 2 ] , [ 2 , 3 ] ] ; NEW_LINE N = len ( mat [ 0 ] ) ; NEW_LINE M = 2 ; NEW_LINE print ( findMedXOR ( mat , N , M ) ) ; NEW_LINE DEDENT
Count ways to tile an N | Function to count the ways to tile N * 1 board using 1 * 1 and 2 * 1 tiles ; dp [ i ] : Stores count of ways to tile i * 1 board using given tiles ; Base Case ; Iterate over the range [ 2 , N ] ; Fill dp [ i ] using the recurrence relation ; Driver Code ; Given N ; Function Call
def countWaysToTileBoard ( N ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 1 ) NEW_LINE dp [ 0 ] = 1 NEW_LINE dp [ 1 ] = 2 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] = ( 2 * dp [ i - 1 ] + dp [ i - 2 ] ) NEW_LINE DEDENT print ( dp [ N ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE countWaysToTileBoard ( N ) NEW_LINE DEDENT
Subsequences generated by including characters or ASCII value of characters of given string | Function to print subsequences containing ASCII value of the characters or the the characters of the given string ; Base Case ; If length of the subsequence exceeds 0 ; Print the subsequence ; Stores character present at i - th index of str ; If the i - th character is not included in the subsequence ; Including the i - th character in the subsequence ; Include the ASCII value of the ith character in the subsequence ; Driver Code ; Stores length of str
def FindSub ( string , res , i ) : NEW_LINE INDENT if ( i == len ( string ) ) : NEW_LINE INDENT if ( len ( res ) > 0 ) : NEW_LINE INDENT print ( res , end = " ▁ " ) ; NEW_LINE DEDENT return ; NEW_LINE DEDENT ch = string [ i ] ; NEW_LINE FindSub ( string , res , i + 1 ) ; NEW_LINE FindSub ( string , res + ch , i + 1 ) ; NEW_LINE FindSub ( string , res + str ( ord ( ch ) ) , i + 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " ab " ; NEW_LINE res = " " ; NEW_LINE N = len ( string ) ; NEW_LINE FindSub ( string , res , 0 ) ; NEW_LINE DEDENT
Minimize given flips required to reduce N to 0 | Function to find the minimum count of operations required to Reduce N to 0 ; Stores count of bits in N ; Recurrence relation ; Driver code
import math NEW_LINE def MinOp ( N ) : NEW_LINE INDENT if ( N <= 1 ) : NEW_LINE INDENT return N ; NEW_LINE DEDENT bit = ( int ) ( math . log ( N ) / math . log ( 2 ) ) + 1 ; NEW_LINE return ( ( 1 << bit ) - 1 ) - MinOp ( N - ( 1 << ( bit - 1 ) ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 ; NEW_LINE print ( MinOp ( N ) ) ; NEW_LINE DEDENT
Maximum non | Function to find the maximum product from the top left and bottom right cell of the given matrix grid [ ] [ ] ; Store dimension of grid ; Stores maximum product path ; Stores minimum product path ; Traverse the grid and update maxPath and minPath array ; Initialize to inf and - inf ; Base Case ; Calculate for row : ; Update the maximum ; Update the minimum ; Calculate for column : ; Update the maximum ; Update the minimum ; Update maxPath and minPath ; If negative product ; Otherwise ; Given matrix mat [ ] [ ] ; Function Call
def maxProductPath ( grid ) : NEW_LINE INDENT n , m = len ( grid ) , len ( grid [ 0 ] ) NEW_LINE maxPath = [ [ 0 for i in range ( m ) ] for j in range ( n ) ] NEW_LINE minPath = [ [ 0 for i in range ( m ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT mn = float ( " inf " ) NEW_LINE mx = float ( " - inf " ) NEW_LINE if ( i == 0 and j == 0 ) : NEW_LINE INDENT mx = grid [ i ] [ j ] NEW_LINE mn = grid [ i ] [ j ] NEW_LINE DEDENT if i > 0 : NEW_LINE INDENT tempmx = max ( ( maxPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) , ( minPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) ) NEW_LINE mx = max ( mx , tempmx ) NEW_LINE tempmn = min ( ( maxPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) , ( minPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) ) NEW_LINE mn = min ( mn , tempmn ) NEW_LINE DEDENT if ( j > 0 ) : NEW_LINE INDENT tempmx = max ( ( maxPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) , ( minPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) ) NEW_LINE mx = max ( mx , tempmx ) NEW_LINE tempmn = min ( ( maxPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) , ( minPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) ) NEW_LINE mn = min ( mn , tempmn ) NEW_LINE DEDENT maxPath [ i ] [ j ] = mx NEW_LINE minPath [ i ] [ j ] = mn NEW_LINE DEDENT DEDENT if ( maxPath [ n - 1 ] [ m - 1 ] < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( maxPath [ n - 1 ] [ m - 1 ] ) NEW_LINE DEDENT DEDENT mat = [ [ 1 , - 2 , 1 ] , [ 1 , - 2 , 1 ] , [ 3 , - 4 , 1 ] ] NEW_LINE print ( maxProductPath ( mat ) ) NEW_LINE
Smallest submatrix required to be removed such that sum of the remaining matrix is divisible by K | Python3 program to implement the above approach ; Function to find the length of the smallest subarray to be removed such that sum of elements is equal to S % K ; Remainder when total_sum is divided by K ; Stores curr_remainder and the most recent index at which curr_remainder has occured ; Stores required answer ; Add current element to curr_sum and take mod ; Update current remainder index ; If mod already exists in map the subarray exists ; Update res ; If not possible ; Return the result ; Function to find the smallest submatrix rqured to be deleted to make the sum of the matrix divisible by K ; Stores the sum of element of the matrix ; Traverse the matrix mat [ ] [ ] ; Update S ; Stores smallest area need to be deleted to get sum divisible by K ; Stores leftmost column of each matrix ; Stores rightmost column of each matrix ; Stores number of coulmns deleted of a matrix ; Store area of the deleted matrix ; prefixRowSum [ i ] : Store sum of sub matrix whose topmost left and bottommost right position is ( 0 , left ) ( i , right ) ; Iterate over all possible values of ( left , right ) ; Initialize all possible values of prefixRowSum [ ] to 0 ; Traverse each row from left to right column ; Update row_sum [ i ] ; Update width ; If no submatrix of the length ( right - left + 1 ) found to get the required output ; Update area ; If area is less than min_area ; Update min_area ; Driver Code ; Stores number of rows in the matrix ; Stores number of column in the matrix
import sys NEW_LINE def removeSmallestSubarray ( arr , S , n , k ) : NEW_LINE INDENT target_remainder = S % k NEW_LINE map1 = { } NEW_LINE map1 [ 0 ] = - 1 NEW_LINE curr_remainder = 0 NEW_LINE res = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_remainder = ( curr_remainder + arr [ i ] + k ) % k NEW_LINE map1 [ curr_remainder ] = i NEW_LINE mod = ( curr_remainder - target_remainder + k ) % k NEW_LINE if ( mod in map1 ) : NEW_LINE INDENT res = min ( res , i - map1 [ mod ] ) NEW_LINE DEDENT DEDENT if ( res == sys . maxsize or res == n ) : NEW_LINE INDENT res = - 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def smstSubmatDeleted ( mat , N , M , K ) : NEW_LINE INDENT S = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT S += mat [ i ] [ j ] NEW_LINE DEDENT DEDENT min_area = N * M NEW_LINE left = 0 NEW_LINE right = 0 NEW_LINE width = 0 NEW_LINE area = 0 NEW_LINE prefixRowSm = [ 0 ] * N NEW_LINE for left in range ( M ) : NEW_LINE INDENT prefixRowSum = [ 0 ] * N NEW_LINE for right in range ( left , M ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT prefixRowSum [ i ] += mat [ i ] [ right ] NEW_LINE DEDENT width = removeSmallestSubarray ( prefixRowSum , S , N , K ) NEW_LINE if ( width != - 1 ) : NEW_LINE INDENT area = ( right - left + 1 ) * ( width ) NEW_LINE if ( area < min_area ) : NEW_LINE INDENT min_area = area NEW_LINE DEDENT DEDENT DEDENT DEDENT return min_area NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 6 , 2 , 6 ] , [ 3 , 2 , 8 ] , [ 2 , 5 , 3 ] ] NEW_LINE K = 3 NEW_LINE N = len ( mat ) NEW_LINE M = len ( mat [ 0 ] ) NEW_LINE print ( smstSubmatDeleted ( mat , N , M , K ) ) NEW_LINE DEDENT
Count N | to keep the string in lexicographically sorted order use start index to add the vowels starting the from that index ; base case : if string length is 0 add to the count ; if last character in string is ' e ' add vowels starting from ' e ' i . e ' e ' , ' i ' , ' o ' , 'u ; decrease the length of string ; char arr [ 5 ] = { ' a ' , ' e ' , ' i ' , ' o ' , ' u ' } ; starting from index 0 add the vowels to strings
def countstrings ( n , start ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT cnt = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( start , 5 ) : NEW_LINE INDENT cnt += countstrings ( n - 1 , i ) NEW_LINE DEDENT return cnt NEW_LINE DEDENT def countVowelStrings ( n ) : NEW_LINE INDENT return countstrings ( n , 0 ) NEW_LINE DEDENT n = 2 NEW_LINE print ( countVowelStrings ( n ) ) NEW_LINE
Count N | Function to count N - length strings consisting of vowels only sorted lexicographically ; Driver Code ; Function Call
def findNumberOfStrings ( n ) : NEW_LINE INDENT return int ( ( n + 1 ) * ( n + 2 ) * ( n + 3 ) * ( n + 4 ) / 24 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE print ( findNumberOfStrings ( N ) ) NEW_LINE DEDENT
Count unique paths with given sum in an N | Python3 program for the above approach ; Function for counting total no of paths possible with the sum is equal to X ; If the path of the sum from the root to current node is stored in sum ; If already computed ; Count different no of paths using all possible ways ; Return total no of paths ; Driver Code ; Stores the number of ways to obtains sums 0 to X ; Function call
mod = int ( 1e9 + 7 ) NEW_LINE def findTotalPath ( X , n , dp ) : NEW_LINE INDENT if ( X == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT ans = 0 NEW_LINE if ( dp [ X ] != - 1 ) : NEW_LINE INDENT return dp [ X ] NEW_LINE DEDENT for i in range ( 1 , min ( X , n ) + 1 ) : NEW_LINE INDENT ans = ans + findTotalPath ( X - i , n , dp ) % mod ; NEW_LINE ans %= mod ; NEW_LINE DEDENT dp [ X ] = ans NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE X = 2 NEW_LINE dp = [ - 1 ] * ( X + 1 ) NEW_LINE print ( findTotalPath ( X , n , dp ) ) NEW_LINE DEDENT
Count sequences of positive integers having product X | Python3 program for the above approach ; Function to prthe total number of possible sequences with product X ; Precomputation of binomial coefficients ; Max length of a subsequence ; Ways dp array ; Fill i slots using all the primes ; Subtract ways for all slots that exactly fill less than i slots ; Total possible sequences ; Print the resultant count ; Driver Code ; Function call
bin = [ [ 0 for i in range ( 3000 ) ] for i in range ( 3000 ) ] NEW_LINE def countWays ( arr ) : NEW_LINE INDENT mod = 10 ** 9 + 7 NEW_LINE bin [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , 3000 ) : NEW_LINE INDENT bin [ i ] [ 0 ] = 1 NEW_LINE for j in range ( 1 , i + 1 ) : NEW_LINE INDENT bin [ i ] [ j ] = ( bin [ i - 1 ] [ j ] + bin [ i - 1 ] [ j - 1 ] ) % mod NEW_LINE DEDENT DEDENT n = 0 NEW_LINE for x in arr : NEW_LINE INDENT n += x NEW_LINE DEDENT ways = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ways [ i ] = 1 NEW_LINE for j in range ( len ( arr ) ) : NEW_LINE INDENT ways [ i ] = ( ways [ i ] * bin [ arr [ j ] + i - 1 ] [ i - 1 ] ) % mod NEW_LINE DEDENT for j in range ( 1 , i ) : NEW_LINE INDENT ways [ i ] = ( ( ways [ i ] - bin [ i ] [ j ] * ways [ j ] ) % mod + mod ) % mod NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for x in ways : NEW_LINE INDENT ans = ( ans + x ) % mod NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 ] NEW_LINE countWays ( arr ) NEW_LINE DEDENT
Maximum subsequence sum obtained by concatenating disjoint subarrays whose lengths are prime | Python3 program for the above approach ; Function to return all prime numbers smaller than N ; Create a boolean array " prime [ 0 . . n ] " ; Initialize all its entries as true memset ( seive , true , sizeof ( seive ) ) ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it ; Stores all prime numbers smaller than MAX ; Store all prime numbers ; If p is prime ; Function to build the auxiliary DP array from the start ; Base Case ; Stores all prime numbers < N ; Stores prefix sum ; Update prefix sum ; Iterate over range ; Update each state i . e . . when current element is excluded ; Find start & end index of subarrays when prime [ i ] is taken ; Check if starting point lies in the array ; Include the elements al al + 1 . . . ar ; Check if element lies before start of selected subarray ; Update value of dp [ i ] ; Function to find the maximum sum subsequence with prime length ; Auxiliary DP array ; Build DP array ; Print the result ; Driver Code ; Given arr [ ] ; Size of array ; Function Call
MAX = 100005 NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT seive = [ True for i in range ( MAX ) ] NEW_LINE for p in range ( 2 , MAX ) : NEW_LINE INDENT if p * p > MAX : NEW_LINE INDENT break NEW_LINE DEDENT if ( seive [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , MAX , p ) : NEW_LINE INDENT seive [ i ] = False NEW_LINE DEDENT DEDENT DEDENT v = [ ] NEW_LINE for p in range ( 2 , MAX ) : NEW_LINE INDENT if ( seive [ p ] ) : NEW_LINE INDENT v . append ( p ) NEW_LINE DEDENT DEDENT return v NEW_LINE DEDENT def build ( dp , arr , N ) : NEW_LINE INDENT dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = 0 NEW_LINE prime = SieveOfEratosthenes ( ) NEW_LINE pref = [ 0 for i in range ( N + 1 ) ] NEW_LINE pref [ 0 ] = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + arr [ i - 1 ] NEW_LINE DEDENT for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] NEW_LINE for j in range ( len ( prime ) + 1 ) : NEW_LINE INDENT r = i - 1 NEW_LINE l = r - prime [ j ] + 1 NEW_LINE if ( l < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT temp = 0 NEW_LINE temp = pref [ r + 1 ] - pref [ l ] NEW_LINE if ( l - 2 >= 0 ) : NEW_LINE INDENT temp += dp [ l - 2 + 1 ] NEW_LINE DEDENT dp [ i ] = max ( dp [ i ] , temp ) NEW_LINE DEDENT DEDENT DEDENT def maxSumSubseq ( arr , N ) : NEW_LINE INDENT dp = [ 0 for i in range ( N + 1 ) ] NEW_LINE build ( dp , arr , N ) NEW_LINE print ( dp [ N ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 10 , 7 , 10 , 10 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE maxSumSubseq ( arr , N ) NEW_LINE DEDENT
Maximum possible score that can be obtained by constructing a Binary Tree based on given conditions | Function to find the maximum score for one possible tree having N nodes N - 1 Edges ; Number of nodes ; Initialize dp [ ] [ ] ; Score with 0 vertices is 0 ; Traverse the nodes from 1 to N ; Find maximum scores for each sum ; Iterate over degree of new node ; Update the current state ; Return maximum score for N node tree having 2 ( N - 1 ) sum of degree ; Driver Code ; Given array of scores ; Function Call
def maxScore ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE N += 1 NEW_LINE dp = [ [ - 100000 for i in range ( 2 * N ) ] for i in range ( N + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for s in range ( 1 , 2 * ( N - 1 ) + 1 ) : NEW_LINE INDENT j = 1 NEW_LINE while j <= N - 1 and j <= s : NEW_LINE INDENT dp [ i ] [ s ] = max ( dp [ i ] [ s ] , arr [ j - 1 ] + dp [ i - 1 ] [ s - j ] ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT return dp [ N ] [ 2 * ( N - 1 ) ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 0 ] NEW_LINE print ( maxScore ( arr ) ) NEW_LINE DEDENT
Minimize cost of choosing and skipping array elements to reach end of the given array | Function to find the minimum cost to reach the end of the array from the first element ; Store the results ; Consider first index cost ; Find answer for each position i ; First Element ; Second Element ; For remaining element ; Consider min cost for skipping ; Last index represents the minimum total cost ; Driver Code ; Given X ; Given array cost [ ] ; Function Call
def minimumCost ( cost , n , x ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 2 ) NEW_LINE dp [ 0 ] = cost [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( i == 1 ) : NEW_LINE INDENT dp [ i ] = cost [ i ] + dp [ i - 1 ] NEW_LINE DEDENT if ( i == 2 ) : NEW_LINE INDENT dp [ i ] = cost [ i ] + min ( dp [ i - 1 ] , x + dp [ i - 2 ] ) NEW_LINE DEDENT if ( i >= 3 ) : NEW_LINE INDENT dp [ i ] = ( cost [ i ] + min ( dp [ i - 1 ] , min ( x + dp [ i - 2 ] , 2 * x + dp [ i - 3 ] ) ) ) NEW_LINE DEDENT DEDENT print ( dp [ n - 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 4 NEW_LINE cost = [ 6 , 3 , 9 , 2 , 1 , 3 ] NEW_LINE N = len ( cost ) NEW_LINE minimumCost ( cost , N , X ) NEW_LINE DEDENT