text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Count Numbers with N digits which consists of odd number of 0 's | Function to count Numbers with N digits which consists of odd number of 0 's ; Driver code
def countNumbers ( N ) : NEW_LINE INDENT return ( pow ( 10 , N ) - pow ( 8 , N ) ) // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE print ( countNumbers ( n ) ) NEW_LINE DEDENT
Sum of all Primes in a given range using Sieve of Eratosthenes | Python 3 program to find sum of primes in range L to R ; prefix [ i ] is going to store sum of primes till i ( including i ) . ; Function to build the prefix sum array ; Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Build prefix array ; Function to return sum of prime in range ; Driver code
from math import sqrt NEW_LINE MAX = 10000 NEW_LINE prefix = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE def buildPrefix ( ) : NEW_LINE INDENT prime = [ True for i in range ( MAX + 1 ) ] NEW_LINE for p in range ( 2 , int ( sqrt ( MAX ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , MAX + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT prefix [ 0 ] = 0 NEW_LINE prefix [ 1 ] = 0 NEW_LINE for p in range ( 2 , MAX + 1 , 1 ) : NEW_LINE INDENT prefix [ p ] = prefix [ p - 1 ] NEW_LINE if ( prime [ p ] ) : NEW_LINE INDENT prefix [ p ] += p NEW_LINE DEDENT DEDENT DEDENT def sumPrimeRange ( L , R ) : NEW_LINE INDENT buildPrefix ( ) NEW_LINE return prefix [ R ] - prefix [ L - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 10 NEW_LINE R = 20 NEW_LINE print ( sumPrimeRange ( L , R ) ) NEW_LINE DEDENT
Sum of the first N terms of the series 5 , 12 , 23 , 38. ... | Function to calculate the sum ; Driver code ; number of terms to be included in sum ; find the Sn
def calculateSum ( n ) : NEW_LINE INDENT return ( 2 * ( n * ( n + 1 ) * ( 2 * n + 1 ) // 6 ) + n * ( n + 1 ) // 2 + 2 * ( n ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE print ( " Sum ▁ = " , calculateSum ( n ) ) NEW_LINE DEDENT
Program to find number of solutions in Quadratic Equation | function to check for solutions of equations ; If the expression is greater than 0 , then 2 solutions ; If the expression is equal 0 , then 1 solutions ; Else no solutions ; Driver code
def checkSolution ( a , b , c ) : NEW_LINE INDENT if ( ( b * b ) - ( 4 * a * c ) ) > 0 : NEW_LINE INDENT print ( "2 ▁ solutions " ) NEW_LINE DEDENT elif ( ( b * b ) - ( 4 * a * c ) ) == 0 : NEW_LINE INDENT print ( "1 ▁ solution " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ solutions " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a , b , c = 2 , 5 , 2 NEW_LINE checkSolution ( a , b , c ) NEW_LINE DEDENT
Program to convert KiloBytes to Bytes and Bits | Function to calculates the bits ; calculates Bits 1 kilobytes ( s ) = 8192 bits ; Function to calculates the bytes ; calculates Bytes 1 KB = 1024 bytes ; Driver code
def Bits ( kilobytes ) : NEW_LINE INDENT Bits = kilobytes * 8192 NEW_LINE return Bits NEW_LINE DEDENT def Bytes ( kilobytes ) : NEW_LINE INDENT Bytes = kilobytes * 1024 NEW_LINE return Bytes NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT kilobytes = 1 NEW_LINE print ( kilobytes , " Kilobytes ▁ = " , Bytes ( kilobytes ) , " Bytes ▁ and " , Bits ( kilobytes ) , " Bits " ) NEW_LINE DEDENT
Program to find the Hidden Number | Driver Code ; Getting the size of array ; Getting the array of size n ; Solution ; Finding sum of the . array elements ; Dividing sum by size n ; Print x , if found
if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE a = [ 1 , 2 , 3 ] NEW_LINE i = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT x = sum // n NEW_LINE if ( x * n == sum ) : NEW_LINE INDENT print ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT
Find sum of the series ? 3 + ? 12 + ... ... ... upto N terms | Function to find the sum ; Apply AP formula ; number of terms
import math NEW_LINE def findSum ( n ) : NEW_LINE INDENT return math . sqrt ( 3 ) * ( n * ( n + 1 ) / 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE print ( findSum ( n ) ) NEW_LINE DEDENT
Find the sum of the series x ( x + y ) + x ^ 2 ( x ^ 2 + y ^ 2 ) + x ^ 3 ( x ^ 3 + y ^ 3 ) + ... + x ^ n ( x ^ n + y ^ n ) | Function to return required sum ; sum of first series ; sum of second series ; Driver Code ; function call to print sum
def sum ( x , y , n ) : NEW_LINE INDENT sum1 = ( ( x ** 2 ) * ( x ** ( 2 * n ) - 1 ) ) // ( x ** 2 - 1 ) NEW_LINE sum2 = ( x * y * ( x ** n * y ** n - 1 ) ) // ( x * y - 1 ) NEW_LINE return ( sum1 + sum2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 2 NEW_LINE y = 2 NEW_LINE n = 2 NEW_LINE print ( sum ( x , y , n ) ) NEW_LINE DEDENT
Find any pair with given GCD and LCM | Function to print the pairs ; Driver Code
def printPair ( g , l ) : NEW_LINE INDENT print ( g , l ) NEW_LINE DEDENT g = 3 ; l = 12 ; NEW_LINE printPair ( g , l ) ; NEW_LINE
Sum of first n terms of a given series 3 , 6 , 11 , ... . . | Function to calculate the sum ; starting number ; common ratio of GP ; common difference Of AP ; no . of the terms for the sum ; Find the Sn
def calculateSum ( n ) : NEW_LINE INDENT a1 = 1 ; NEW_LINE a2 = 2 ; NEW_LINE r = 2 ; NEW_LINE d = 1 ; NEW_LINE return ( ( n ) * ( 2 * a1 + ( n - 1 ) * d ) / 2 + a2 * ( pow ( r , n ) - 1 ) / ( r - 1 ) ) ; NEW_LINE DEDENT n = 5 ; NEW_LINE print ( " Sum ▁ = " , int ( calculateSum ( n ) ) ) NEW_LINE
Maximum of sum and product of digits until number is reduced to a single digit | Function to sum the digits until it becomes a single digit ; Function to product the digits until it becomes a single digit ; Loop to do sum while sum is not less than or equal to 9 ; Function to find the maximum among repeated sum and repeated product ; Driver code
def repeatedSum ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 9 if ( n % 9 == 0 ) else ( n % 9 ) NEW_LINE DEDENT def repeatedProduct ( n ) : NEW_LINE INDENT prod = 1 NEW_LINE while ( n > 0 or prod > 9 ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT n = prod NEW_LINE prod = 1 NEW_LINE DEDENT prod *= n % 10 NEW_LINE n //= 10 NEW_LINE DEDENT return prod NEW_LINE DEDENT def maxSumProduct ( N ) : NEW_LINE INDENT if ( N < 10 ) : NEW_LINE INDENT return N NEW_LINE DEDENT return max ( repeatedSum ( N ) , repeatedProduct ( N ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 631 NEW_LINE print ( maxSumProduct ( n ) ) NEW_LINE DEDENT
Count numbers with exactly K non | To store digits of N ; visited map ; DP Table ; Push all the digits of N into digits vector ; Function returns the count ; If desired number is formed whose sum is odd ; If it is not present in map , mark it as true and return 1 ; Sum is present in map already ; Desired result not found ; If that state is already calculated just return that state value ; Upper limit ; To store the count of desired numbers ; If k is non - zero , i ranges from 0 to j else [ 1 , j ] ; If current digit is 0 , decrement k and recurse sum is not changed as we are just adding 0 that makes no difference ; If i is non zero , then k remains unchanged and value is added to sum ; Memoize and return ; Driver code ; K is the number of exact non - zero elements to have in number ; break N into its digits ; We keep record of 0 s we need to place in the number
digits = [ ] NEW_LINE vis = [ False for i in range ( 170 ) ] NEW_LINE dp = [ [ [ [ 0 for l in range ( 170 ) ] for k in range ( 2 ) ] for j in range ( 19 ) ] for i in range ( 19 ) ] NEW_LINE def ConvertIntoDigit ( n ) : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT dig = n % 10 ; NEW_LINE digits . append ( dig ) ; NEW_LINE n //= 10 ; NEW_LINE DEDENT digits . reverse ( ) NEW_LINE DEDENT def solve ( idx , k , tight , sum ) : NEW_LINE INDENT if ( idx == len ( digits ) and k == 0 and sum % 2 == 1 ) : NEW_LINE INDENT if ( not vis [ sum ] ) : NEW_LINE INDENT vis [ sum ] = True ; NEW_LINE return 1 ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT if ( idx > len ( digits ) ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ idx ] [ k ] [ tight ] [ sum ] ) : NEW_LINE INDENT return dp [ idx ] [ k ] [ tight ] [ sum ] ; NEW_LINE DEDENT j = 0 ; NEW_LINE if ( idx < len ( digits ) and tight == 0 ) : NEW_LINE INDENT j = digits [ idx ] ; NEW_LINE DEDENT else : NEW_LINE INDENT j = 9 ; NEW_LINE DEDENT cnt = 0 ; NEW_LINE for i in range ( 0 if k else 1 , j + 1 ) : NEW_LINE INDENT newtight = tight ; NEW_LINE if ( i < j ) : NEW_LINE INDENT newtight = 1 ; NEW_LINE DEDENT if ( i == 0 ) : NEW_LINE INDENT cnt += solve ( idx + 1 , k - 1 , newtight , sum ) ; NEW_LINE DEDENT else : NEW_LINE INDENT cnt += solve ( idx + 1 , k , newtight , sum + i ) ; NEW_LINE DEDENT DEDENT dp [ idx ] [ k ] [ tight ] [ sum ] = cnt NEW_LINE return cnt ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 169 NEW_LINE k = 2 ; NEW_LINE ConvertIntoDigit ( N ) ; NEW_LINE k = len ( digits ) - k ; NEW_LINE print ( solve ( 0 , k , 0 , 0 ) ) NEW_LINE DEDENT
Count of subsets of integers from 1 to N having no adjacent elements | Function to count subsets ; Driver Code
def countSubsets ( N ) : NEW_LINE INDENT if ( N <= 2 ) : NEW_LINE INDENT return N NEW_LINE DEDENT if ( N == 3 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT DP = [ 0 ] * ( N + 1 ) NEW_LINE DP [ 0 ] = 0 NEW_LINE DP [ 1 ] = 1 NEW_LINE DP [ 2 ] = 2 NEW_LINE DP [ 3 ] = 2 NEW_LINE for i in range ( 4 , N + 1 ) : NEW_LINE INDENT DP [ i ] = DP [ i - 2 ] + DP [ i - 3 ] NEW_LINE DEDENT return DP [ N ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 20 NEW_LINE print ( countSubsets ( N ) ) NEW_LINE DEDENT
Count the number of ordered sets not containing consecutive numbers | DP table ; Function to calculate the count of ordered set for a given size ; Base cases ; If subproblem has been soved before ; Store and return answer to this subproblem ; Function returns the count of all ordered sets ; Prestore the factorial value ; Iterate all ordered set sizes and find the count for each one maximum ordered set size will be smaller than N as all elements are distinct and non consecutive . ; Multiply ny size ! for all the arrangements because sets are ordered . ; Add to total answer ; Driver code
dp = [ [ - 1 for j in range ( 500 ) ] for i in range ( 500 ) ] NEW_LINE def CountSets ( x , pos ) : NEW_LINE INDENT if ( x <= 0 ) : NEW_LINE INDENT if ( pos == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( pos == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ x ] [ pos ] != - 1 ) : NEW_LINE INDENT return dp [ x ] [ pos ] NEW_LINE DEDENT answer = ( CountSets ( x - 1 , pos ) + CountSets ( x - 2 , pos - 1 ) ) NEW_LINE dp [ x ] [ pos ] = answer NEW_LINE return answer NEW_LINE DEDENT def CountOrderedSets ( n ) : NEW_LINE INDENT factorial = [ 0 for i in range ( 10000 ) ] NEW_LINE factorial [ 0 ] = 1 NEW_LINE for i in range ( 1 , 10000 ) : NEW_LINE INDENT factorial [ i ] = factorial [ i - 1 ] * i NEW_LINE DEDENT answer = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sets = CountSets ( n , i ) * factorial [ i ] NEW_LINE answer = answer + sets NEW_LINE DEDENT return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE print ( CountOrderedSets ( N ) ) NEW_LINE DEDENT
Count the Arithmetic sequences in the Array of size at least 3 | Function to find all arithmetic sequences of size atleast 3 ; If array size is less than 3 ; Finding arithmetic subarray length ; To store all arithmetic subarray of length at least 3 ; Check if current element makes arithmetic sequence with previous two elements ; Begin with a new element for new arithmetic sequences ; Accumulate result in till i . ; Return final count ; Driver code ; Function to find arithmetic sequences
def numberOfArithmeticSequences ( L , N ) : NEW_LINE INDENT if ( N <= 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 0 NEW_LINE res = 0 NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT if ( ( L [ i ] - L [ i - 1 ] ) == ( L [ i - 1 ] - L [ i - 2 ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = 0 NEW_LINE DEDENT res += count NEW_LINE DEDENT return res NEW_LINE DEDENT L = [ 1 , 3 , 5 , 6 , 7 , 8 ] NEW_LINE N = len ( L ) NEW_LINE print ( numberOfArithmeticSequences ( L , N ) ) NEW_LINE
Count triplet of indices ( i , j , k ) such that XOR of elements between [ i , j ) equals [ j , k ] | Function return the count of triplets having subarray XOR equal ; XOR value till i ; Count and ways array as defined above ; Using the formula stated ; Increase the frequency of x ; Add i + 1 to ways [ x ] for upcoming indices ; Driver code
def CountOfTriplets ( a , n ) : NEW_LINE INDENT answer = 0 NEW_LINE x = 0 NEW_LINE count = [ 0 for i in range ( 100005 ) ] NEW_LINE ways = [ 0 for i in range ( 100005 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT x ^= a [ i ] NEW_LINE answer += count [ x ] * i - ways [ x ] NEW_LINE count [ x ] += 1 NEW_LINE ways [ x ] += ( i + 1 ) NEW_LINE DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Arr = [ 3 , 6 , 12 , 8 , 6 , 2 , 1 , 5 ] NEW_LINE N = len ( Arr ) NEW_LINE print ( CountOfTriplets ( Arr , N ) ) NEW_LINE DEDENT
Count of subarrays of an Array having all unique digits | Function to obtain the mask for any integer ; Function to count the number of ways ; Subarray must not be empty ; If subproblem has been solved ; Excluding this element in the subarray ; If there are no common digits then only this element can be included ; Calculate the new mask if this element is included ; Store and return the answer ; Function to find the count of subarray with all digits unique ; Initializing dp ; Driver Code
def getmask ( val ) : NEW_LINE INDENT mask = 0 NEW_LINE if val == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT while ( val ) : NEW_LINE INDENT d = val % 10 ; NEW_LINE mask |= ( 1 << d ) NEW_LINE val = val // 10 NEW_LINE DEDENT return mask NEW_LINE DEDENT def countWays ( pos , mask , a , n ) : NEW_LINE INDENT if pos == n : NEW_LINE INDENT if mask > 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if dp [ pos ] [ mask ] != - 1 : NEW_LINE INDENT return dp [ pos ] [ mask ] NEW_LINE DEDENT count = 0 NEW_LINE count = ( count + countWays ( pos + 1 , mask , a , n ) ) NEW_LINE if ( getmask ( a [ pos ] ) & mask ) == 0 : NEW_LINE INDENT new_mask = ( mask | ( getmask ( a [ pos ] ) ) ) NEW_LINE count = ( count + countWays ( pos + 1 , new_mask , a , n ) ) NEW_LINE DEDENT dp [ pos ] [ mask ] = count NEW_LINE return count NEW_LINE DEDENT def numberOfSubarrays ( a , n ) : NEW_LINE INDENT return countWays ( 0 , 0 , a , n ) NEW_LINE DEDENT dp = [ [ - 1 for i in range ( cols ) ] for j in range ( rows ) ] NEW_LINE print ( numberOfSubarrays ( A , N ) ) NEW_LINE N = 4 NEW_LINE A = [ 1 , 12 , 23 , 34 ] NEW_LINE rows = 5000 NEW_LINE cols = 1100 NEW_LINE
Count of Fibonacci paths in a Binary tree | Vector to store the fibonacci series ; Binary Tree Node ; Function to create a new tree node ; Function to find the height of the given tree ; Function to make fibonacci series upto n terms ; Preorder Utility function to count exponent path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is not a number of pow ( x , y ) ; Increment count when encounter leaf node ; Left recursive call save the value of count ; Right recursive call and return value of count ; Function to find whether fibonacci path exists or not ; To find the height ; Making fibonacci series upto ht terms ; Driver code ; Create binary tree ; Function Call
fib = [ ] NEW_LINE class node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = node ( data ) NEW_LINE return temp NEW_LINE DEDENT def height ( root ) : NEW_LINE INDENT ht = 0 NEW_LINE if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( max ( height ( root . left ) , height ( root . right ) ) + 1 ) NEW_LINE DEDENT def FibonacciSeries ( n ) : NEW_LINE INDENT fib . append ( 0 ) NEW_LINE fib . append ( 1 ) NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT fib . append ( fib [ i - 1 ] + fib [ i - 2 ] ) NEW_LINE DEDENT DEDENT def CountPathUtil ( root , i , count ) : NEW_LINE INDENT if ( root == None or not ( fib [ i ] == root . data ) ) : NEW_LINE INDENT return count NEW_LINE DEDENT if ( not root . left and not root . right ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT count = CountPathUtil ( root . left , i + 1 , count ) NEW_LINE return CountPathUtil ( root . right , i + 1 , count ) NEW_LINE DEDENT def CountPath ( root ) : NEW_LINE INDENT ht = height ( root ) NEW_LINE FibonacciSeries ( ht ) NEW_LINE print ( CountPathUtil ( root , 0 , 0 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 0 ) NEW_LINE root . left = newNode ( 1 ) NEW_LINE root . right = newNode ( 1 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . left . right = newNode ( 4 ) NEW_LINE root . right . right = newNode ( 1 ) NEW_LINE root . right . right . left = newNode ( 2 ) NEW_LINE CountPath ( root ) NEW_LINE DEDENT
Numbers with a Fibonacci difference between Sum of digits at even and odd positions in a given range | Python3 program to count the numbers in the range having the difference between the sum of digits at even and odd positions as a Fibonacci Number ; To store all the Fibonacci numbers ; Function to generate Fibonacci numbers upto 100 ; Adding the first two Fibonacci numbers in the set ; Computing the remaining Fibonacci numbers using the first two Fibonacci numbers ; Function to return the count of required numbers from 0 to num ; Base Case ; Check if the difference is equal to any fibonacci number ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current position is odd add it to currOdd , otherwise to currEven ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Driver Code ; Generate fibonacci numbers
M = 18 NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE dp = [ [ [ [ - 1 for i in range ( 2 ) ] for j in range ( 90 ) ] for k in range ( 90 ) ] for l in range ( M ) ] NEW_LINE fib = set ( ) NEW_LINE def fibonacci ( ) : NEW_LINE INDENT prev = 0 NEW_LINE curr = 1 NEW_LINE fib . add ( prev ) NEW_LINE fib . add ( curr ) NEW_LINE while ( curr <= 100 ) : NEW_LINE INDENT temp = curr + prev NEW_LINE fib . add ( temp ) NEW_LINE prev = curr NEW_LINE curr = temp NEW_LINE DEDENT DEDENT def count ( pos , even , odd , tight , num ) : NEW_LINE INDENT if ( pos == len ( num ) ) : NEW_LINE INDENT if ( ( len ( num ) & 1 ) ) : NEW_LINE INDENT val = odd NEW_LINE odd = even NEW_LINE even = val NEW_LINE DEDENT d = even - odd NEW_LINE if ( d in fib ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( dp [ pos ] [ even ] [ odd ] [ tight ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ even ] [ odd ] [ tight ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( tight == 1 ) : NEW_LINE INDENT limit = 9 NEW_LINE DEDENT else : NEW_LINE INDENT limit = num [ pos ] NEW_LINE DEDENT for d in range ( limit ) : NEW_LINE INDENT currF = tight NEW_LINE currEven = even NEW_LINE currOdd = odd NEW_LINE if ( d < num [ pos ] ) : NEW_LINE INDENT currF = 1 NEW_LINE DEDENT if ( pos & 1 ) : NEW_LINE INDENT currOdd += d NEW_LINE DEDENT else : NEW_LINE INDENT currEven += d NEW_LINE DEDENT ans += count ( pos + 1 , currEven , currOdd , currF , num ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def solve ( x ) : NEW_LINE INDENT num = [ ] NEW_LINE while ( x > 0 ) : NEW_LINE INDENT num . append ( x % 10 ) NEW_LINE x //= 10 NEW_LINE DEDENT num = num [ : : - 1 ] NEW_LINE return count ( 0 , 0 , 0 , 0 , num ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT fibonacci ( ) NEW_LINE L = 1 NEW_LINE R = 50 NEW_LINE print ( solve ( R ) - solve ( L - 1 ) + 1 ) NEW_LINE L = 50 NEW_LINE R = 100 NEW_LINE print ( solve ( R ) - solve ( L - 1 ) + 2 ) NEW_LINE DEDENT
Count maximum occurrence of subsequence in string such that indices in subsequence is in A . P . | Python3 implementation to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Function to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Frequency for characters ; Loop to count the occurrence of ith character before jth character in the given String ; Increase the frequency of s [ i ] or c of String ; Maximum occurrence of subsequence of length 1 in given String ; Maximum occurrence of subsequence of length 2 in given String ; Driver Code
import sys NEW_LINE def maximumOccurrence ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE freq = [ 0 ] * ( 26 ) NEW_LINE dp = [ [ 0 for i in range ( 26 ) ] for j in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT c = ( ord ( s [ i ] ) - ord ( ' a ' ) ) NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT dp [ j ] += freq [ j ] NEW_LINE DEDENT freq += 1 NEW_LINE DEDENT answer = - sys . maxsize NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT answer = max ( answer , freq [ i ] ) NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT for j in range ( 26 ) : NEW_LINE INDENT answer = max ( answer , dp [ i ] [ j ] ) NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " xxxyy " NEW_LINE print ( maximumOccurrence ( s ) ) NEW_LINE DEDENT
Count the numbers with N digits and whose suffix is divisible by K | Python3 implementation to Count the numbers with N digits and whose suffix is divisible by K ; Suffix of length pos with remainder rem and Z representing whether the suffix has a non zero digit until now ; Base case ; If count of digits is less than n ; Placing all possible digits in remaining positions ; If remainder non zero and suffix has n digits ; If the subproblem is already solved ; Placing all digits at MSB of suffix and increasing it 's length by 1 ; Non zero digit is placed ; Store and return the solution to this subproblem ; Function to Count the numbers with N digits and whose suffix is divisible by K ; Since we need powers of 10 for counting , it 's better to pre store them along with their modulo with 1e9 + 7 for counting ; Since at each recursive step we increase the suffix length by 1 by placing digits at its leftmost position , we need powers of 10 modded with k , in order to fpos the new remainder efficiently ; Initialising dp table values - 1 represents subproblem hasn 't been solved yet memset(dp, -1, sizeof(dp)) ; Driver Code
mod = 1000000007 NEW_LINE dp = [ [ [ - 1 for i in range ( 2 ) ] for i in range ( 105 ) ] for i in range ( 1005 ) ] NEW_LINE powers = [ 0 ] * 1005 NEW_LINE powersModk = [ 0 ] * 1005 NEW_LINE def calculate ( pos , rem , z , k , n ) : NEW_LINE INDENT if ( rem == 0 and z ) : NEW_LINE INDENT if ( pos != n ) : NEW_LINE INDENT return ( powers [ n - pos - 1 ] * 9 ) % mod NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT if ( pos == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ pos ] [ rem ] [ z ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ rem ] [ z ] NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT count = ( count + ( calculate ( pos + 1 , ( rem + ( i * powersModk [ pos ] ) % k ) % k , z , k , n ) ) ) % mod NEW_LINE DEDENT else : NEW_LINE INDENT count = ( count + ( calculate ( pos + 1 , ( rem + ( i * powersModk [ pos ] ) % k ) % k , 1 , k , n ) ) ) % mod NEW_LINE DEDENT DEDENT dp [ pos ] [ rem ] [ z ] = count NEW_LINE return count NEW_LINE DEDENT def countNumbers ( n , k ) : NEW_LINE INDENT st = 1 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT powers [ i ] = st NEW_LINE st *= 10 NEW_LINE st %= mod NEW_LINE DEDENT st = 1 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT powersModk [ i ] = st NEW_LINE st *= 10 NEW_LINE st %= mod NEW_LINE DEDENT return calculate ( 0 , 0 , 0 , k , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE K = 2 NEW_LINE print ( countNumbers ( N , K ) ) NEW_LINE DEDENT
Shortest path with exactly k edges in a directed and weighted graph | Set 2 | Python3 implementation of the above approach ; Function to find the smallest path with exactly K edges ; Array to store dp ; Loop to solve DP ; Initialising next state ; Recurrence relation ; Returning final answer ; Driver code ; Input edges ; Source and Destination ; Number of edges in path ; Calling the function
inf = 100000000 NEW_LINE def smPath ( s , d , ed , n , k ) : NEW_LINE INDENT dis = [ inf ] * ( n + 1 ) NEW_LINE dis [ s ] = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT dis1 = [ inf ] * ( n + 1 ) NEW_LINE for it in ed : NEW_LINE INDENT dis1 [ it [ 1 ] ] = min ( dis1 [ it [ 1 ] ] , dis [ it [ 0 ] ] + it [ 2 ] ) NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT dis [ i ] = dis1 [ i ] NEW_LINE DEDENT DEDENT if ( dis [ d ] == inf ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return dis [ d ] NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE ed = [ [ 0 , 1 , 10 ] , [ 0 , 2 , 3 ] , [ 0 , 3 , 2 ] , [ 1 , 3 , 7 ] , [ 2 , 3 , 7 ] ] NEW_LINE s = 0 NEW_LINE d = 3 NEW_LINE k = 2 NEW_LINE print ( smPath ( s , d , ed , n , k ) ) NEW_LINE DEDENT
Path with smallest product of edges with weight > 0 | Python3 implementation of the approach . ; Function to return the smallest product of edges ; If the source is equal to the destination ; Array to store distances ; Initialising the array ; Bellman ford algorithm ; Loop to detect cycle ; Returning final answer ; Driver code ; Input edges ; Source and Destination ; Bellman ford
import sys NEW_LINE inf = sys . maxsize ; NEW_LINE def bellman ( s , d , ed , n ) : NEW_LINE INDENT if ( s == d ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT dis = [ 0 ] * ( n + 1 ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dis [ i ] = inf ; NEW_LINE DEDENT dis [ s ] = 1 ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for it in ed : NEW_LINE INDENT dis [ it [ 1 ] ] = min ( dis [ it [ 1 ] ] , dis [ it [ 0 ] ] * ed [ it ] ) ; NEW_LINE DEDENT DEDENT for it in ed : NEW_LINE INDENT if ( dis [ it [ 1 ] ] > dis [ it [ 0 ] ] * ed [ it ] ) : NEW_LINE INDENT return - 2 ; NEW_LINE DEDENT DEDENT if ( dis [ d ] == inf ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return dis [ d ] ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 ; NEW_LINE ed = { ( 1 , 2 ) : 0.5 , ( 1 , 3 ) : 1.9 , ( 2 , 3 ) : 3 } ; NEW_LINE s = 1 ; d = 3 ; NEW_LINE get = bellman ( s , d , ed , n ) ; NEW_LINE if ( get == - 2 ) : NEW_LINE INDENT print ( " Cycle ▁ Detected " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( get ) ; NEW_LINE DEDENT DEDENT
Find Maximum Length Of A Square Submatrix Having Sum Of Elements At | Python3 implementation of the above approach ; Function to return maximum length of square submatrix having sum of elements at - most K ; Matrix to store prefix sum ; Current maximum length ; Variable for storing maximum length of square ; Calculating prefix sum ; Checking whether there exits square with length cur_max + 1 or not ; Returning the maximum length ; Driver code
import numpy as np NEW_LINE def maxLengthSquare ( row , column , arr , k ) : NEW_LINE INDENT sum = np . zeros ( ( row + 1 , column + 1 ) ) ; NEW_LINE cur_max = 1 ; NEW_LINE max = 0 ; NEW_LINE for i in range ( 1 , row + 1 ) : NEW_LINE INDENT for j in range ( 1 , column + 1 ) : NEW_LINE INDENT sum [ i ] [ j ] = sum [ i - 1 ] [ j ] + sum [ i ] [ j - 1 ] + arr [ i - 1 ] [ j - 1 ] - sum [ i - 1 ] [ j - 1 ] ; NEW_LINE if ( i >= cur_max and j >= cur_max and sum [ i ] [ j ] - sum [ i - cur_max ] [ j ] - sum [ i ] [ j - cur_max ] + sum [ i - cur_max ] [ j - cur_max ] <= k ) : NEW_LINE INDENT max = cur_max ; NEW_LINE cur_max += 1 ; NEW_LINE DEDENT DEDENT DEDENT return max ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT row = 4 ; NEW_LINE column = 4 ; NEW_LINE matrix = [ [ 1 , 1 , 1 , 1 ] , [ 1 , 0 , 0 , 0 ] , [ 1 , 0 , 0 , 0 ] , [ 1 , 0 , 0 , 0 ] ] ; NEW_LINE k = 6 ; NEW_LINE ans = maxLengthSquare ( row , column , matrix , k ) ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT
Sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times | Python3 program to find sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times ; exactsum [ i ] [ j ] [ k ] stores the sum of all the numbers having exact i 4 ' s , ▁ j ▁ 5' s and k 6 's ; exactnum [ i ] [ j ] [ k ] stores numbers of numbers having exact i 4 ' s , ▁ j ▁ 5' s and k 6 's ; Utility function to calculate the sum for x 4 ' s , ▁ y ▁ 5' s and z 6 's ; Computing exactsum [ i ] [ j ] [ k ] as explained above ; Driver code
import numpy as np NEW_LINE N = 101 ; NEW_LINE mod = int ( 1e9 ) + 7 ; NEW_LINE exactsum = np . zeros ( ( N , N , N ) ) ; NEW_LINE exactnum = np . zeros ( ( N , N , N ) ) ; NEW_LINE def getSum ( x , y , z ) : NEW_LINE INDENT ans = 0 ; NEW_LINE exactnum [ 0 ] [ 0 ] [ 0 ] = 1 ; NEW_LINE for i in range ( x + 1 ) : NEW_LINE INDENT for j in range ( y + 1 ) : NEW_LINE INDENT for k in range ( z + 1 ) : NEW_LINE INDENT if ( i > 0 ) : NEW_LINE INDENT exactsum [ i ] [ j ] [ k ] += ( exactsum [ i - 1 ] [ j ] [ k ] * 10 + 4 * exactnum [ i - 1 ] [ j ] [ k ] ) % mod ; NEW_LINE exactnum [ i ] [ j ] [ k ] += exactnum [ i - 1 ] [ j ] [ k ] % mod ; NEW_LINE DEDENT if ( j > 0 ) : NEW_LINE INDENT exactsum [ i ] [ j ] [ k ] += ( exactsum [ i ] [ j - 1 ] [ k ] * 10 + 5 * exactnum [ i ] [ j - 1 ] [ k ] ) % mod ; NEW_LINE exactnum [ i ] [ j ] [ k ] += exactnum [ i ] [ j - 1 ] [ k ] % mod ; NEW_LINE DEDENT if ( k > 0 ) : NEW_LINE INDENT exactsum [ i ] [ j ] [ k ] += ( exactsum [ i ] [ j ] [ k - 1 ] * 10 + 6 * exactnum [ i ] [ j ] [ k - 1 ] ) % mod ; NEW_LINE exactnum [ i ] [ j ] [ k ] += exactnum [ i ] [ j ] [ k - 1 ] % mod ; NEW_LINE DEDENT ans += exactsum [ i ] [ j ] [ k ] % mod ; NEW_LINE ans %= mod ; NEW_LINE DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 1 ; y = 1 ; z = 1 ; NEW_LINE print ( ( getSum ( x , y , z ) % mod ) ) ; NEW_LINE DEDENT
Maximum value obtained by performing given operations in an Array | Python3 implementation of the above approach ; A function to calculate the maximum value ; basecases ; Loop to iterate and add the max value in the dp array ; Driver Code
import numpy as np NEW_LINE def findMax ( a , n ) : NEW_LINE INDENT dp = np . zeros ( ( n , 2 ) ) ; NEW_LINE dp [ 0 ] [ 0 ] = a [ 0 ] + a [ 1 ] ; NEW_LINE dp [ 0 ] [ 1 ] = a [ 0 ] * a [ 1 ] ; NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) + a [ i + 1 ] ; NEW_LINE dp [ i ] [ 1 ] = dp [ i - 1 ] [ 0 ] - a [ i ] + a [ i ] * a [ i + 1 ] ; NEW_LINE DEDENT print ( max ( dp [ n - 2 ] [ 0 ] , dp [ n - 2 ] [ 1 ] ) , end = " " ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , - 1 , - 5 , - 3 , 2 , 9 , - 4 ] ; NEW_LINE findMax ( arr , 7 ) ; NEW_LINE DEDENT
Optimal strategy for a Game with modifications | Python3 implementation of the above approach ; Function to return sum of subarray from l to r ; calculate sum by a loop from l to r ; dp to store the values of sub problems ; if length of the array is less than k return the sum ; if the value is previously calculated ; else calculate the value ; select all the sub array of length len_r ; get the sum of that sub array ; check if it is the maximum or not ; store it in the table ; Driver code
import numpy as np NEW_LINE def Sum ( arr , l , r ) : NEW_LINE INDENT s = 0 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT s += arr [ i ] ; NEW_LINE DEDENT return s ; NEW_LINE DEDENT dp = np . zeros ( ( 101 , 101 , 101 ) ) ; NEW_LINE def solve ( arr , l , r , k ) : NEW_LINE INDENT if ( r - l + 1 <= k ) : NEW_LINE INDENT return Sum ( arr , l , r ) ; NEW_LINE DEDENT if ( dp [ l ] [ r ] [ k ] ) : NEW_LINE INDENT return dp [ l ] [ r ] [ k ] ; NEW_LINE DEDENT sum_ = Sum ( arr , l , r ) ; NEW_LINE len_r = ( r - l + 1 ) - k ; NEW_LINE length = ( r - l + 1 ) ; NEW_LINE ans = 0 ; NEW_LINE for i in range ( length - len_r + 1 ) : NEW_LINE INDENT sum_sub = Sum ( arr , i + l , i + l + len_r - 1 ) ; NEW_LINE ans = max ( ans , ( sum_ - sum_sub ) + ( sum_sub - solve ( arr , i + l , i + l + len_r - 1 , k ) ) ) ; NEW_LINE DEDENT dp [ l ] [ r ] [ k ] = ans ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 15 , 20 , 9 , 2 , 5 ] ; k = 2 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( solve ( arr , 0 , n - 1 , k ) ) ; NEW_LINE DEDENT
Find the minimum difference path from ( 0 , 0 ) to ( N | Python3 implementation of the approach ; Function to return the minimum difference path from ( 0 , 0 ) to ( N - 1 , M - 1 ) ; Terminating case ; Base case ; If it is already visited ; Recursive calls ; Return the value ; Driver code ; Function call
import numpy as np NEW_LINE import sys NEW_LINE MAXI = 50 NEW_LINE INT_MAX = sys . maxsize NEW_LINE dp = np . ones ( ( MAXI , MAXI , MAXI * MAXI ) ) ; NEW_LINE dp *= - 1 NEW_LINE def minDifference ( x , y , k , b , c ) : NEW_LINE INDENT if ( x >= n or y >= m ) : NEW_LINE INDENT return INT_MAX ; NEW_LINE DEDENT if ( x == n - 1 and y == m - 1 ) : NEW_LINE INDENT diff = b [ x ] [ y ] - c [ x ] [ y ] ; NEW_LINE return min ( abs ( k - diff ) , abs ( k + diff ) ) ; NEW_LINE DEDENT ans = dp [ x ] [ y ] [ k ] ; NEW_LINE if ( ans != - 1 ) : NEW_LINE INDENT return ans ; NEW_LINE DEDENT ans = INT_MAX ; NEW_LINE diff = b [ x ] [ y ] - c [ x ] [ y ] ; NEW_LINE ans = min ( ans , minDifference ( x + 1 , y , abs ( k + diff ) , b , c ) ) ; NEW_LINE ans = min ( ans , minDifference ( x , y + 1 , abs ( k + diff ) , b , c ) ) ; NEW_LINE ans = min ( ans , minDifference ( x + 1 , y , abs ( k - diff ) , b , c ) ) ; NEW_LINE ans = min ( ans , minDifference ( x , y + 1 , abs ( k - diff ) , b , c ) ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; m = 2 ; b = [ [ 1 , 4 ] , [ 2 , 4 ] ] ; NEW_LINE c = [ [ 3 , 2 ] , [ 3 , 1 ] ] ; NEW_LINE print ( minDifference ( 0 , 0 , 0 , b , c ) ) ; NEW_LINE DEDENT
Longest subsequence having difference atmost K | Function to find the longest Special Sequence ; Creating a list with all 0 's of size equal to the length of string ; Supporting list with all 0 's of size 26 since the given string consists of only lower case alphabets ; Converting the ascii value to list indices ; Determining the lower bound ; Determining the upper bound ; Filling the dp array with values ; Filling the max_length array with max length of subsequence till now ; return the max length of subsequence ; driver code
def longest_subseq ( n , k , s ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE max_length = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE lower = max ( 0 , curr - k ) NEW_LINE upper = min ( 25 , curr + k ) NEW_LINE for j in range ( lower , upper + 1 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , max_length [ j ] + 1 ) NEW_LINE DEDENT max_length [ curr ] = max ( dp [ i ] , max_length [ curr ] ) NEW_LINE DEDENT return max ( dp ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE n = len ( s ) NEW_LINE k = 3 NEW_LINE print ( longest_subseq ( n , k , s ) ) NEW_LINE DEDENT main ( ) NEW_LINE
Maximum possible array sum after performing the given operation | Function to return the maximum possible sum after performing the given operation ; Dp vector to store the answer ; Base value ; Return the maximum sum ; Driver code
def max_sum ( a , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for j in range ( n + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 0 ; dp [ 0 ] [ 1 ] = - 999999 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT dp [ i + 1 ] [ 0 ] = max ( dp [ i ] [ 0 ] + a [ i ] , dp [ i ] [ 1 ] - a [ i ] ) ; NEW_LINE dp [ i + 1 ] [ 1 ] = max ( dp [ i ] [ 0 ] - a [ i ] , dp [ i ] [ 1 ] + a [ i ] ) ; NEW_LINE DEDENT return dp [ n ] [ 0 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ - 10 , 5 , - 4 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( max_sum ( a , n ) ) ; NEW_LINE DEDENT
Find the number of ways to reach Kth step in stair case | Python3 implementation of the approach ; Function to return the number of ways to reach the kth step ; Create the dp array ; Broken steps ; Calculate the number of ways for the rest of the positions ; If it is a blocked position ; Number of ways to get to the ith step ; Return the required answer ; Driver code
MOD = 1000000007 ; NEW_LINE def number_of_ways ( arr , n , k ) : NEW_LINE INDENT if ( k == 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT dp = [ - 1 ] * ( k + 1 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ arr [ i ] ] = 0 ; NEW_LINE DEDENT dp [ 0 ] = 1 ; NEW_LINE dp [ 1 ] = 1 if ( dp [ 1 ] == - 1 ) else dp [ 1 ] ; NEW_LINE for i in range ( 2 , k + 1 ) : NEW_LINE INDENT if ( dp [ i ] == 0 ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] ; NEW_LINE dp [ i ] %= MOD ; NEW_LINE DEDENT return dp [ k ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 6 ; NEW_LINE print ( number_of_ways ( arr , n , k ) ) ; NEW_LINE DEDENT
Minimum number of coins that can generate all the values in the given range | Python3 program to find minimum number of coins ; Function to find minimum number of coins ; Driver code
import math NEW_LINE def findCount ( n ) : NEW_LINE INDENT return int ( math . log ( n , 2 ) ) + 1 NEW_LINE DEDENT N = 10 NEW_LINE print ( findCount ( N ) ) NEW_LINE
Calculate the number of set bits for every number from 0 to N | Python 3 implementation of the approach ; Function to find the count of set bits in all the integers from 0 to n ; Driver code
def count ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def findSetBits ( n ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT print ( count ( i ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE findSetBits ( n ) NEW_LINE DEDENT
Count number of ways to arrange first N numbers | Python3 implementation of the approach ; Function to return the count of required arrangements ; Create a vector ; Store numbers from 1 to n ; To store the count of ways ; Initialize flag to true if first element is 1 else false ; Checking if the current permutation satisfies the given conditions ; If the current permutation is invalid then set the flag to false ; If valid arrangement ; Generate the all permutation ; Driver code
from itertools import permutations NEW_LINE def countWays ( n ) : NEW_LINE INDENT a = [ ] NEW_LINE i = 1 NEW_LINE while ( i <= n ) : NEW_LINE INDENT a . append ( i ) NEW_LINE i += 1 NEW_LINE DEDENT ways = 0 NEW_LINE INDENT flag = 1 if ( per [ 0 ] == 1 ) else 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( abs ( per [ i ] - per [ i - 1 ] ) > 2 ) : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT ways += 1 NEW_LINE DEDENT DEDENT return ways NEW_LINE for per in list ( permutations ( a ) ) : NEW_LINE DEDENT n = 6 NEW_LINE print ( countWays ( n ) ) NEW_LINE
Count number of ways to arrange first N numbers | Function to return the count of required arrangements ; Create the dp array ; Initialize the base cases as explained above ; ( 12 ) as the only possibility ; Generate answer for greater values ; dp [ n ] contains the desired answer ; Driver code
def countWays ( n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = 1 NEW_LINE dp [ 2 ] = 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + dp [ i - 3 ] + 1 NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT n = 6 NEW_LINE print ( countWays ( n ) ) NEW_LINE
Number of shortest paths to reach every cell from bottom | Function to find number of shortest paths ; Compute the grid starting from the bottom - left corner ; Print the grid ; Driver code ; Function call
def NumberOfShortestPaths ( n , m ) : NEW_LINE INDENT a = [ [ 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 a [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( j == 0 or i == n - 1 ) : NEW_LINE INDENT a [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT a [ i ] [ j ] = a [ i ] [ j - 1 ] + a [ i + 1 ] [ j ] NEW_LINE DEDENT DEDENT i -= 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT print ( a [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE m = 2 NEW_LINE NumberOfShortestPaths ( n , m ) NEW_LINE DEDENT
Maximum sum combination from two arrays | Function to maximum sum combination from two arrays ; To store dp value ; For loop to calculate the value of dp ; Return the required answer ; Driver code ; Function call
def Max_Sum ( arr1 , arr2 , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = arr1 [ i ] NEW_LINE dp [ i ] [ 1 ] = arr2 [ i ] NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ 0 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] + arr1 [ i ] ) NEW_LINE dp [ i ] [ 1 ] = max ( dp [ i - 1 ] [ 1 ] , dp [ i - 1 ] [ 0 ] + arr2 [ i ] ) NEW_LINE DEDENT DEDENT return max ( dp [ n - 1 ] [ 0 ] , dp [ n - 1 ] [ 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 9 , 3 , 5 , 7 , 3 ] NEW_LINE arr2 = [ 5 , 8 , 1 , 4 , 5 ] NEW_LINE n = len ( arr1 ) NEW_LINE print ( Max_Sum ( arr1 , arr2 , n ) ) NEW_LINE DEDENT
Partition the array in K segments such that bitwise AND of individual segment sum is maximized | Function to check whether a k segment partition is possible such that bitwise AND is 'mask ; dp [ i ] [ j ] stores whether it is possible to partition first i elements into j segments such that all j segments are 'good ; Initialising dp ; Filling dp in bottom - up manner ; Finding a cut such that first l elements can be partitioned into j - 1 ' good ' segments and arr [ l + 1 ] + ... + arr [ i ] is a ' good ' segment ; Function to find maximum possible AND ; Array to store prefix sums ; Maximum no of bits in the possible answer ; This will store the final answer ; Constructing answer greedily selecting from the higher most bit ; Checking if array can be partitioned such that the bitwise AND is ans | ( 1 << i ) ; if possible , update the answer ; Return the final answer ; Driver code ; n = 11 , first element is zero to make array 1 based indexing . So , number of elements are 10 ; Function call
' NEW_LINE def checkpossible ( mask , arr , prefix , n , k ) : NEW_LINE ' NEW_LINE INDENT dp = [ [ 0 for i in range ( k + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , k + 1 ) : NEW_LINE INDENT for l in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( dp [ l ] [ j - 1 ] and ( ( ( prefix [ i ] - prefix [ l ] ) & mask ) == mask ) ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT return dp [ n ] [ k ] NEW_LINE DEDENT def Partition ( arr , n , k ) : NEW_LINE INDENT prefix = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + arr [ i ] NEW_LINE DEDENT LOGS = 20 NEW_LINE ans = 0 NEW_LINE for i in range ( LOGS , - 1 , - 1 ) : NEW_LINE INDENT if ( checkpossible ( ans | ( 1 << i ) , arr , prefix , n , k ) ) : NEW_LINE INDENT ans = ans | ( 1 << i ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 0 , 1 , 2 , 7 , 10 , 23 , 21 , 6 , 8 , 7 , 3 ] NEW_LINE k = 2 NEW_LINE n = len ( arr ) - 1 NEW_LINE print ( Partition ( arr , n , k ) ) NEW_LINE
Cost Based Tower of Hanoi | Python3 implementation of the approach ; Function to initialize the dp table ; Initialize with maximum value ; Function to return the minimum cost ; Base case ; If problem is already solved , return the pre - calculated answer ; Number of the auxiliary disk ; Initialize the minimum cost as Infinity ; Calculationg the cost for first case ; Calculating the cost for second case ; Minimum of both the above cases ; Store it in the dp table ; Return the minimum cost ; Driver code
import numpy as np NEW_LINE import sys NEW_LINE RODS = 3 NEW_LINE N = 3 NEW_LINE dp = np . zeros ( ( N + 1 , RODS + 1 , RODS + 1 ) ) ; NEW_LINE def initialize ( ) : NEW_LINE INDENT for i in range ( N + 1 ) : NEW_LINE INDENT for j in range ( 1 , RODS + 1 ) : NEW_LINE INDENT for k in range ( 1 , RODS + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = sys . maxsize ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def mincost ( idx , src , dest , costs ) : NEW_LINE INDENT if ( idx > N ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ idx ] [ src ] [ dest ] != sys . maxsize ) : NEW_LINE INDENT return dp [ idx ] [ src ] [ dest ] ; NEW_LINE DEDENT rem = 6 - ( src + dest ) ; NEW_LINE ans = sys . maxsize ; NEW_LINE case1 = costs [ src - 1 ] [ dest - 1 ] + mincost ( idx + 1 , src , rem , costs ) + mincost ( idx + 1 , rem , dest , costs ) ; NEW_LINE case2 = ( costs [ src - 1 ] [ rem - 1 ] + mincost ( idx + 1 , src , dest , costs ) + mincost ( idx + 1 , dest , src , costs ) + costs [ rem - 1 ] [ dest - 1 ] + mincost ( idx + 1 , src , dest , costs ) ) ; NEW_LINE ans = min ( case1 , case2 ) ; NEW_LINE dp [ idx ] [ src ] [ dest ] = ans ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT costs = [ [ 0 , 1 , 2 ] , [ 2 , 0 , 1 ] , [ 3 , 2 , 0 ] ] ; NEW_LINE initialize ( ) ; NEW_LINE print ( mincost ( 1 , 1 , 3 , costs ) ) ; NEW_LINE DEDENT
Minimum time required to rot all oranges | Dynamic Programming | Python 3 implementation of the approach ; DP table to memoize the values ; Visited array to keep track of visited nodes in order to avoid infinite loops ; Function to return the minimum of four numbers ; Function to return the minimum distance to any rotten orange from [ i , j ] ; If i , j lie outside the array ; If 0 then it can 't lead to any path so return INT_MAX ; If 2 then we have reached our rotten oranges so return from here ; If this node is already visited then return to avoid infinite loops ; Mark the current node as visited ; Check in all four possible directions ; Take the minimum of all ; If result already exists in the table check if min_value is less than existing value ; Function to return the minimum time required to rot all the oranges ; Calculate the minimum distances to any rotten orange from all the fresh oranges ; Pick the maximum distance of fresh orange to some rotten orange ; If all oranges can be rotten ; Driver Code
C = 5 NEW_LINE R = 3 NEW_LINE INT_MAX = 10000000 NEW_LINE table = [ [ 0 for i in range ( C ) ] for j in range ( R ) ] NEW_LINE visited = [ [ 0 for i in range ( C ) ] for j in range ( R ) ] NEW_LINE def min ( p , q , r , s ) : NEW_LINE INDENT if ( p < q ) : NEW_LINE INDENT temp1 = p NEW_LINE DEDENT else : NEW_LINE INDENT temp1 = q NEW_LINE DEDENT if ( r < s ) : NEW_LINE INDENT temp2 = r NEW_LINE DEDENT else : NEW_LINE INDENT temp2 = s NEW_LINE DEDENT if ( temp1 < temp2 ) : NEW_LINE INDENT return temp1 NEW_LINE DEDENT return temp2 NEW_LINE DEDENT def Distance ( arr , i , j ) : NEW_LINE INDENT if ( i >= R or j >= C or i < 0 or j < 0 ) : NEW_LINE INDENT return INT_MAX NEW_LINE DEDENT elif ( arr [ i ] [ j ] == 0 ) : NEW_LINE INDENT table [ i ] [ j ] = INT_MAX NEW_LINE return INT_MAX NEW_LINE DEDENT elif ( arr [ i ] [ j ] == 2 ) : NEW_LINE INDENT table [ i ] [ j ] = 0 NEW_LINE return 0 NEW_LINE DEDENT elif ( visited [ i ] [ j ] ) : NEW_LINE INDENT return INT_MAX NEW_LINE DEDENT else : NEW_LINE INDENT visited [ i ] [ j ] = 1 NEW_LINE temp1 = Distance ( arr , i + 1 , j ) NEW_LINE temp2 = Distance ( arr , i - 1 , j ) NEW_LINE temp3 = Distance ( arr , i , j + 1 ) NEW_LINE temp4 = Distance ( arr , i , j - 1 ) NEW_LINE min_value = 1 + min ( temp1 , temp2 , temp3 , temp4 ) NEW_LINE if table [ i ] [ j ] > 0 and table [ i ] [ j ] < INT_MAX : NEW_LINE INDENT if min_value < table [ i ] [ j ] : NEW_LINE INDENT table [ i ] [ j ] = min_value NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT table [ i ] [ j ] = min_value NEW_LINE DEDENT visited [ i ] [ j ] = 0 NEW_LINE DEDENT return table [ i ] [ j ] NEW_LINE DEDENT def minTime ( arr ) : NEW_LINE INDENT max = 0 NEW_LINE for i in range ( R ) : NEW_LINE INDENT for j in range ( C ) : NEW_LINE INDENT if ( arr [ i ] [ j ] == 1 ) : NEW_LINE INDENT Distance ( arr , i , j ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( R ) : NEW_LINE INDENT for j in range ( C ) : NEW_LINE INDENT if ( arr [ i ] [ j ] == 1 and table [ i ] [ j ] > max ) : NEW_LINE INDENT max = table [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT if ( max < INT_MAX ) : NEW_LINE INDENT return max NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 2 , 1 , 0 , 2 , 1 ] , [ 0 , 0 , 1 , 2 , 1 ] , [ 1 , 0 , 0 , 2 , 1 ] ] NEW_LINE print ( minTime ( arr ) ) NEW_LINE DEDENT
Maximum sum of non | Python3 program to implement above approach ; Variable to store states of dp ; Variable to check if a given state has been solved ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Variable to store prefix sum for sub - array { i , j } ; Required recurrence relation ; Returning the value ; Driver code ; Input array
maxLen = 10 NEW_LINE dp = [ 0 ] * maxLen ; NEW_LINE visit = [ 0 ] * maxLen ; NEW_LINE def maxSum ( arr , i , n , k ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( visit [ i ] ) : NEW_LINE INDENT return dp [ i ] ; NEW_LINE DEDENT visit [ i ] = 1 ; NEW_LINE tot = 0 ; NEW_LINE dp [ i ] = maxSum ( arr , i + 1 , n , k ) ; NEW_LINE j = i NEW_LINE while ( j < i + k and j < n ) : NEW_LINE INDENT tot += arr [ j ] ; NEW_LINE dp [ i ] = max ( dp [ i ] , tot + maxSum ( arr , j + 2 , n , k ) ) ; NEW_LINE j += 1 NEW_LINE DEDENT return dp [ i ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 1 , 2 , - 3 , 4 , 5 ] ; NEW_LINE k = 2 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxSum ( arr , 0 , n , k ) ) ; NEW_LINE DEDENT
Maximum subset sum such that no two elements in set have same digit in them | Python3 implementation of above approach ; Function to create mask for every number ; Recursion for Filling DP array ; Base Condition ; Recurrence Relation ; Function to find Maximum Subset Sum ; Initialize DP array ; Iterate over all possible masks of 10 bit number ; Driver Code
dp = [ 0 ] * 1024 ; NEW_LINE def get_binary ( u ) : NEW_LINE INDENT ans = 0 ; NEW_LINE while ( u ) : NEW_LINE INDENT rem = u % 10 ; NEW_LINE ans |= ( 1 << rem ) ; NEW_LINE u //= 10 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def recur ( u , array , n ) : NEW_LINE INDENT if ( u == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ u ] != - 1 ) : NEW_LINE INDENT return dp [ u ] ; NEW_LINE DEDENT temp = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT mask = get_binary ( array [ i ] ) ; NEW_LINE if ( ( mask u ) == u ) : NEW_LINE INDENT dp [ u ] = max ( max ( 0 , dp [ u ^ mask ] ) + array [ i ] , dp [ u ] ) ; NEW_LINE DEDENT DEDENT return dp [ u ] ; NEW_LINE DEDENT def solve ( array , n ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i < ( 1 << 10 ) ) : NEW_LINE INDENT dp [ i ] = - 1 ; NEW_LINE i += 1 NEW_LINE DEDENT ans = 0 ; NEW_LINE i = 0 NEW_LINE while ( i < ( 1 << 10 ) ) : NEW_LINE INDENT ans = max ( ans , recur ( i , array , n ) ) ; NEW_LINE i += 1 NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT array = [ 22 , 132 , 4 , 45 , 12 , 223 ] ; NEW_LINE n = len ( array ) ; NEW_LINE print ( solve ( array , n ) ) ; NEW_LINE DEDENT
Minimize the sum after choosing elements from the given three arrays | Python3 implementation of the above approach ; Function to return the minimized sum ; If all the indices have been used ; If this value is pre - calculated then return its value from dp array instead of re - computing it ; If A [ i - 1 ] was chosen previously then only B [ i ] or C [ i ] can chosen now choose the one which leads to the minimum sum ; If B [ i - 1 ] was chosen previously then only A [ i ] or C [ i ] can chosen now choose the one which leads to the minimum sum ; If C [ i - 1 ] was chosen previously then only A [ i ] or B [ i ] can chosen now choose the one which leads to the minimum sum ; Driver code ; Initialize the dp [ ] [ ] array ; min ( start with A [ 0 ] , start with B [ 0 ] , start with C [ 0 ] )
import numpy as np NEW_LINE SIZE = 3 ; NEW_LINE N = 3 ; NEW_LINE def minSum ( A , B , C , i , n , curr , dp ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ n ] [ curr ] != - 1 ) : NEW_LINE INDENT return dp [ n ] [ curr ] ; NEW_LINE DEDENT if ( curr == 0 ) : NEW_LINE INDENT dp [ n ] [ curr ] = min ( B [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 1 , dp ) , C [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 2 , dp ) ) ; NEW_LINE return dp [ n ] [ curr ] NEW_LINE DEDENT if ( curr == 1 ) : NEW_LINE INDENT dp [ n ] [ curr ] = min ( A [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 0 , dp ) , C [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 2 , dp ) ) ; NEW_LINE return dp [ n ] [ curr ] NEW_LINE DEDENT dp [ n ] [ curr ] = min ( A [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 0 , dp ) , B [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 1 , dp ) ) ; NEW_LINE return dp [ n ] [ curr ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 50 , 1 ] ; NEW_LINE B = [ 50 , 50 , 50 ] ; NEW_LINE C = [ 50 , 50 , 50 ] ; NEW_LINE dp = np . zeros ( ( SIZE , N ) ) ; NEW_LINE for i in range ( SIZE ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 ; NEW_LINE DEDENT DEDENT print ( min ( A [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 0 , dp ) , min ( B [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 1 , dp ) , C [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 2 , dp ) ) ) ) ; NEW_LINE DEDENT
Maximise matrix sum by following the given Path | Python3 implementation of the approach ; To store the states of the DP ; Function to return the maximum of the three integers ; Function to return the maximum score ; Base cases ; If the state has already been solved then return it ; Marking the state as solved ; Growing phase ; Shrinking phase ; Returning the solved state ; Driver code
import numpy as np NEW_LINE n = 3 NEW_LINE dp = np . zeros ( ( n , n , 2 ) ) ; NEW_LINE v = np . zeros ( ( n , n , 2 ) ) ; NEW_LINE def max_three ( a , b , c ) : NEW_LINE INDENT m = a ; NEW_LINE if ( m < b ) : NEW_LINE INDENT m = b ; NEW_LINE DEDENT if ( m < c ) : NEW_LINE INDENT m = c ; NEW_LINE DEDENT return m ; NEW_LINE DEDENT def maxScore ( arr , i , j , s ) : NEW_LINE INDENT if ( i > n - 1 or i < 0 or j > n - 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( i == 0 and j == n - 1 ) : NEW_LINE INDENT return arr [ i ] [ j ] ; NEW_LINE DEDENT if ( v [ i ] [ j ] [ s ] ) : NEW_LINE INDENT return dp [ i ] [ j ] [ s ] ; NEW_LINE DEDENT v [ i ] [ j ] [ s ] = 1 ; NEW_LINE if ( not bool ( s ) ) : NEW_LINE INDENT dp [ i ] [ j ] [ s ] = arr [ i ] [ j ] + max_three ( maxScore ( arr , i + 1 , j , s ) , maxScore ( arr , i , j + 1 , s ) , maxScore ( arr , i - 1 , j , not bool ( s ) ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] [ s ] = arr [ i ] [ j ] + max ( maxScore ( arr , i - 1 , j , s ) , maxScore ( arr , i , j + 1 , s ) ) ; NEW_LINE DEDENT return dp [ i ] [ j ] [ s ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 1 , 1 ] , [ 1 , 5 , 1 ] , [ 1 , 1 , 1 ] , ] ; NEW_LINE print ( maxScore ( arr , 0 , 0 , 0 ) ) ; NEW_LINE DEDENT
Find maximum topics to prepare in order to pass the exam | Python3 implementation of the approach ; Function to return the maximum marks by considering topics which can be completed in the given time duration ; If we are given 0 time then nothing can be done So all values are 0 ; If we are given 0 topics then the time required will be 0 for sure ; Calculating the maximum marks that can be achieved under the given time constraints ; If time taken to read that topic is more than the time left now at position j then do no read that topic ; Two cases arise : 1 ) Considering current topic 2 ) Ignoring current topic We are finding maximum of ( current topic weightage + topics which can be done in leftover time - current topic time ) and ignoring current topic weightage sum ; Moving upwards in table from bottom right to calculate the total time taken to read the topics which can be done in given time and have highest weightage sum ; It means we have not considered reading this topic for max weightage sum ; Adding the topic time ; Evaluating the left over time after considering this current topic ; One topic completed ; It contains the maximum weightage sum formed by considering the topics ; Condition when exam cannot be passed ; Return the marks that can be obtained after passing the exam ; Driver code ; Number of topics , hours left and the passing marks ; n + 1 is taken for simplicity in loops Array will be indexed starting from 1
import numpy as np NEW_LINE def MaximumMarks ( marksarr , timearr , h , n , p ) : NEW_LINE INDENT no_of_topics = n + 1 ; NEW_LINE total_time = h + 1 ; NEW_LINE T = np . zeros ( ( no_of_topics , total_time ) ) ; NEW_LINE for i in range ( no_of_topics ) : NEW_LINE INDENT T [ i ] [ 0 ] = 0 ; NEW_LINE DEDENT for j in range ( total_time ) : NEW_LINE INDENT T [ 0 ] [ j ] = 0 ; NEW_LINE DEDENT for i in range ( 1 , no_of_topics ) : NEW_LINE INDENT for j in range ( 1 , total_time ) : NEW_LINE INDENT if ( j < timearr [ i ] ) : NEW_LINE INDENT T [ i ] [ j ] = T [ i - 1 ] [ j ] ; NEW_LINE DEDENT else : NEW_LINE INDENT T [ i ] [ j ] = max ( marksarr [ i ] + T [ i - 1 ] [ j - timearr [ i ] ] , T [ i - 1 ] [ j ] ) ; NEW_LINE DEDENT DEDENT DEDENT i = no_of_topics - 1 ; j = total_time - 1 ; NEW_LINE sum = 0 ; NEW_LINE while ( i > 0 and j > 0 ) : NEW_LINE INDENT if ( T [ i ] [ j ] == T [ i - 1 ] [ j ] ) : NEW_LINE INDENT i -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT sum += timearr [ i ] ; NEW_LINE j -= timearr [ i ] ; NEW_LINE i -= 1 ; NEW_LINE DEDENT DEDENT marks = T [ no_of_topics - 1 ] [ total_time - 1 ] ; NEW_LINE if ( marks < p ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 ; h = 10 ; p = 10 ; NEW_LINE marksarr = [ 0 , 6 , 4 , 2 , 8 ] ; NEW_LINE timearr = [ 0 , 4 , 6 , 2 , 7 ] ; NEW_LINE print ( MaximumMarks ( marksarr , timearr , h , n , p ) ) ; NEW_LINE DEDENT
Minimize the number of steps required to reach the end of the array | Python3 implementation of the above approach ; variable to store states of dp ; variable to check if a given state has been solved ; Function to find the minimum number of steps required to reach the end of the array ; base case ; to check if a state has been solved ; required recurrence relation ; returning the value ; Driver code
maxLen = 10 NEW_LINE maskLen = 130 NEW_LINE dp = [ [ 0 for i in range ( maskLen ) ] for i in range ( maxLen ) ] NEW_LINE v = [ [ False for i in range ( maskLen ) ] for i in range ( maxLen ) ] NEW_LINE def minSteps ( arr , i , mask , n ) : NEW_LINE INDENT if ( i == n - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( i > n - 1 or i < 0 ) : NEW_LINE INDENT return 9999999 NEW_LINE DEDENT if ( ( mask >> i ) & 1 ) : NEW_LINE INDENT return 9999999 NEW_LINE DEDENT if ( v [ i ] [ mask ] == True ) : NEW_LINE INDENT return dp [ i ] [ mask ] NEW_LINE DEDENT v [ i ] [ mask ] = True NEW_LINE dp [ i ] [ mask ] = 1 + min ( minSteps ( arr , i - arr [ i ] , ( mask | ( 1 << i ) ) , n ) , minSteps ( arr , i + arr [ i ] , ( mask | ( 1 << i ) ) , n ) ) NEW_LINE return dp [ i ] [ mask ] NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 2 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE ans = minSteps ( arr , 0 , 0 , n ) NEW_LINE if ( ans >= 9999999 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT
Optimal Strategy for a Game | Set 2 | python3 program to find out maximum value from a given sequence of coins ; For both of your choices , the opponent gives you total Sum minus maximum of his value ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Driver code
def oSRec ( arr , i , j , Sum ) : NEW_LINE INDENT if ( j == i + 1 ) : NEW_LINE INDENT return max ( arr [ i ] , arr [ j ] ) NEW_LINE DEDENT return max ( ( Sum - oSRec ( arr , i + 1 , j , Sum - arr [ i ] ) ) , ( Sum - oSRec ( arr , i , j - 1 , Sum - arr [ j ] ) ) ) NEW_LINE DEDENT def optimalStrategyOfGame ( arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE Sum = sum ( arr ) NEW_LINE return oSRec ( arr , 0 , n - 1 , Sum ) NEW_LINE DEDENT arr1 = [ 8 , 15 , 3 , 7 ] NEW_LINE n = len ( arr1 ) NEW_LINE print ( optimalStrategyOfGame ( arr1 , n ) ) NEW_LINE arr2 = [ 2 , 2 , 2 , 2 ] NEW_LINE n = len ( arr2 ) NEW_LINE print ( optimalStrategyOfGame ( arr2 , n ) ) NEW_LINE arr3 = [ 20 , 30 , 2 , 2 , 2 , 10 ] NEW_LINE n = len ( arr3 ) NEW_LINE print ( optimalStrategyOfGame ( arr3 , n ) ) NEW_LINE
Minimum number of sub | Function that returns true if n is a power of 5 ; Function to return the decimal value of binary equivalent ; Function to return the minimum cuts required ; Allocating memory for dp [ ] array ; From length 1 to n ; If previous character is '0' then ignore to avoid number with leading 0 s . ; Ignore s [ j ] = '0' starting numbers ; Number formed from s [ j ... . i ] ; Check for power of 5 ; Assigning min value to get min cut possible ; ( n + 1 ) to check if all the strings are traversed and no divisible by 5 is obtained like 000000 ; Driver code
def ispower ( n ) : NEW_LINE INDENT if ( n < 125 ) : NEW_LINE INDENT return ( n == 1 or n == 5 or n == 25 ) NEW_LINE DEDENT if ( n % 125 != 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return ispower ( n // 125 ) NEW_LINE DEDENT DEDENT def number ( s , i , j ) : NEW_LINE INDENT ans = 0 NEW_LINE for x in range ( i , j ) : NEW_LINE INDENT ans = ans * 2 + ( ord ( s [ x ] ) - ord ( '0' ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def minCuts ( s , n ) : NEW_LINE INDENT dp = [ n + 1 for i in range ( n + 1 ) ] NEW_LINE dp [ 0 ] = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( s [ i - 1 ] == '0' ) : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( i ) : NEW_LINE INDENT if ( s [ j ] == '0' ) : NEW_LINE INDENT continue NEW_LINE DEDENT num = number ( s , j , i ) NEW_LINE if ( not ispower ( num ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT dp [ i ] = min ( dp [ i ] , dp [ j ] + 1 ) NEW_LINE DEDENT DEDENT if dp [ n ] < n + 1 : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "101101101" NEW_LINE n = len ( s ) NEW_LINE print ( minCuts ( s , n ) ) NEW_LINE DEDENT
Minimum number of cubes whose sum equals to given number N | Function to return the minimum number of cubes whose sum is k ; If k is less than the 2 ^ 3 ; Initialize with the maximum number of cubes required ; Driver code
def MinOfCubed ( k ) : NEW_LINE INDENT if ( k < 8 ) : NEW_LINE INDENT return k ; NEW_LINE DEDENT res = k ; NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT if ( ( i * i * i ) > k ) : NEW_LINE INDENT return res ; NEW_LINE DEDENT res = min ( res , MinOfCubed ( k - ( i * i * i ) ) + 1 ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT num = 15 ; NEW_LINE print ( MinOfCubed ( num ) ) ; NEW_LINE
Minimum number of cubes whose sum equals to given number N | Python implementation of the approach ; Function to return the minimum number of cubes whose sum is k ; While current perfect cube is less than current element ; If i is a perfect cube ; i = ( i - 1 ) + 1 ^ 3 ; Next perfect cube ; Re - initialization for next element ; Driver code
import sys NEW_LINE def MinOfCubedDP ( k ) : NEW_LINE INDENT DP = [ 0 ] * ( k + 1 ) ; NEW_LINE j = 1 ; NEW_LINE t = 1 ; NEW_LINE DP [ 0 ] = 0 ; NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT DP [ i ] = sys . maxsize ; NEW_LINE while ( j <= i ) : NEW_LINE INDENT if ( j == i ) : NEW_LINE INDENT DP [ i ] = 1 ; NEW_LINE DEDENT elif ( DP [ i ] > DP [ i - j ] ) : NEW_LINE INDENT DP [ i ] = DP [ i - j ] + 1 ; NEW_LINE DEDENT t += 1 ; NEW_LINE j = t * t * t ; NEW_LINE DEDENT t = j = 1 ; NEW_LINE DEDENT return DP [ k ] ; NEW_LINE DEDENT num = 15 ; NEW_LINE print ( MinOfCubedDP ( num ) ) ; NEW_LINE
Maximum Subarray Sum after inverting at most two elements | Function to return the maximum required sub - array sum ; Creating one based indexing ; 2d array to contain solution for each step ; Case 1 : Choosing current or ( current + previous ) whichever is smaller ; Case 2 : ( a ) Altering sign and add to previous case 1 or value 0 ; Case 2 : ( b ) Adding current element with previous case 2 and updating the maximum ; Case 3 : ( a ) Altering sign and add to previous case 2 ; Case 3 : ( b ) Adding current element with previous case 3 ; Updating the maximum value of variable ans ; Return the final solution ; Driver code
def maxSum ( a , n ) : NEW_LINE INDENT ans = 0 NEW_LINE arr = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT arr [ i ] = a [ i - 1 ] NEW_LINE DEDENT dp = [ [ 0 for i in range ( 3 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = max ( arr [ i ] , dp [ i - 1 ] [ 0 ] + arr [ i ] ) NEW_LINE dp [ i ] [ 1 ] = max ( 0 , dp [ i - 1 ] [ 0 ] ) - arr [ i ] NEW_LINE if i >= 2 : NEW_LINE INDENT dp [ i ] [ 1 ] = max ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 1 ] + arr [ i ] ) NEW_LINE DEDENT if i >= 2 : NEW_LINE INDENT dp [ i ] [ 2 ] = dp [ i - 1 ] [ 1 ] - arr [ i ] NEW_LINE DEDENT if i >= 3 : NEW_LINE INDENT dp [ i ] [ 2 ] = max ( dp [ i ] [ 2 ] , dp [ i - 1 ] [ 2 ] + arr [ i ] ) NEW_LINE DEDENT ans = max ( ans , dp [ i ] [ 0 ] ) NEW_LINE ans = max ( ans , dp [ i ] [ 1 ] ) NEW_LINE ans = max ( ans , dp [ i ] [ 2 ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 5 , 3 , 2 , 7 , - 8 , 3 , 7 , - 9 , 10 , 12 , - 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSum ( arr , n ) ) NEW_LINE DEDENT
Maximum sum possible for a sub | Function to return the maximum sum possible ; dp [ i ] represent the maximum sum so far after reaching current position i ; Initialize dp [ 0 ] ; Initialize the dp values till k since any two elements included in the sub - sequence must be atleast k indices apart , and thus first element and second element will be k indices apart ; Fill remaining positions ; Return the maximum sum ; Driver code
def maxSum ( arr , k , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return arr [ 0 ] ; NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return max ( arr [ 0 ] , arr [ 1 ] ) ; NEW_LINE DEDENT dp = [ 0 ] * n ; NEW_LINE dp [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT dp [ i ] = max ( arr [ i ] , dp [ i - 1 ] ) ; NEW_LINE DEDENT for i in range ( k + 1 , n ) : NEW_LINE INDENT dp [ i ] = max ( arr [ i ] , dp [ i - ( k + 1 ) ] + arr [ i ] ) ; NEW_LINE DEDENT max_element = max ( dp ) ; NEW_LINE return max_element ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 7 , 1 , 3 , 8 , 2 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE print ( maxSum ( arr , k , n ) ) ; NEW_LINE DEDENT
Minimum cost to form a number X by adding up powers of 2 | Function to return the minimum cost ; Re - compute the array ; Add answers for set bits ; If bit is set ; Increase the counter ; Right shift the number ; Driver code
def MinimumCost ( a , n , x ) : NEW_LINE INDENT for i in range ( 1 , n , 1 ) : NEW_LINE INDENT a [ i ] = min ( a [ i ] , 2 * a [ i - 1 ] ) NEW_LINE DEDENT ind = 0 NEW_LINE sum = 0 NEW_LINE while ( x ) : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT sum += a [ ind ] NEW_LINE DEDENT ind += 1 NEW_LINE x = x >> 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 20 , 50 , 60 , 90 ] NEW_LINE x = 7 NEW_LINE n = len ( a ) NEW_LINE print ( MinimumCost ( a , n , x ) ) NEW_LINE DEDENT
Ways to form an array having integers in given range such that total sum is divisible by 2 | Function to return the number of ways to form an array of size n such that sum of all elements is divisible by 2 ; Represents first and last numbers of each type ( modulo 0 and 1 ) ; Count of numbers of each type between range ; Base Cases ; Ways to form array whose sum upto i numbers modulo 2 is 0 ; Ways to form array whose sum upto i numbers modulo 2 is 1 ; Return the required count of ways ; Driver Code
def countWays ( n , l , r ) : NEW_LINE INDENT tL , tR = l , r NEW_LINE L = [ 0 for i in range ( 2 ) ] NEW_LINE R = [ 0 for i in range ( 2 ) ] NEW_LINE L [ l % 2 ] = l NEW_LINE R [ r % 2 ] = r NEW_LINE l += 1 NEW_LINE r -= 1 NEW_LINE if ( l <= tR and r >= tL ) : NEW_LINE INDENT L [ l % 2 ] , R [ r % 2 ] = l , r NEW_LINE DEDENT cnt0 , cnt1 = 0 , 0 NEW_LINE if ( R [ 0 ] and L [ 0 ] ) : NEW_LINE INDENT cnt0 = ( R [ 0 ] - L [ 0 ] ) // 2 + 1 NEW_LINE DEDENT if ( R [ 1 ] and L [ 1 ] ) : NEW_LINE INDENT cnt1 = ( R [ 1 ] - L [ 1 ] ) // 2 + 1 NEW_LINE DEDENT dp = [ [ 0 for i in range ( 2 ) ] for i in range ( n + 1 ) ] NEW_LINE dp [ 1 ] [ 0 ] = cnt0 NEW_LINE dp [ 1 ] [ 1 ] = cnt1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = ( cnt0 * dp [ i - 1 ] [ 0 ] + cnt1 * dp [ i - 1 ] [ 1 ] ) NEW_LINE dp [ i ] [ 1 ] = ( cnt0 * dp [ i - 1 ] [ 1 ] + cnt1 * dp [ i - 1 ] [ 0 ] ) NEW_LINE DEDENT return dp [ n ] [ 0 ] NEW_LINE DEDENT n , l , r = 2 , 1 , 3 NEW_LINE print ( countWays ( n , l , r ) ) NEW_LINE
Color N boxes using M colors such that K boxes have different color from the box on its left | Python3 Program to Paint N boxes using M colors such that K boxes have color different from color of box on its left ; This function returns the required number of ways where idx is the current index and diff is number of boxes having different color from box on its left ; Base Case ; If already computed ; Either paint with same color as previous one ; Or paint with remaining ( M - 1 ) colors ; Driver code ; Multiply M since first box can be painted with any of the M colors and start solving from 2 nd box
M = 1001 ; NEW_LINE MOD = 998244353 ; NEW_LINE dp = [ [ - 1 ] * M ] * M NEW_LINE def solve ( idx , diff , N , M , K ) : NEW_LINE INDENT if ( idx > N ) : NEW_LINE INDENT if ( diff == K ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( dp [ idx ] [ diff ] != - 1 ) : NEW_LINE INDENT return dp [ idx ] ; NEW_LINE DEDENT ans = solve ( idx + 1 , diff , N , M , K ) ; NEW_LINE ans += ( M - 1 ) * solve ( idx + 1 , diff + 1 , N , M , K ) ; NEW_LINE dp [ idx ] [ diff ] = ans % MOD ; NEW_LINE return dp [ idx ] [ diff ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE M = 3 NEW_LINE K = 0 NEW_LINE print ( M * solve ( 2 , 0 , N , M , K ) ) NEW_LINE DEDENT
Maximum path sum in an Inverted triangle | SET 2 | Python program implementation of Max sum problem in a triangle ; Function for finding maximum sum ; Loop for bottom - up calculation ; For each element , check both elements just below the number and below left to the number add the maximum of them to it ; Return the maximum sum ; Driver Code
N = 3 NEW_LINE def maxPathSum ( tri ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( 0 , N - i ) : NEW_LINE INDENT if ( j - 1 >= 0 ) : NEW_LINE INDENT tri [ i ] [ j ] += max ( tri [ i + 1 ] [ j ] , tri [ i + 1 ] [ j - 1 ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT tri [ i ] [ j ] += tri [ i + 1 ] [ j ] ; NEW_LINE DEDENT ans = max ( ans , tri [ i ] [ j ] ) ; NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT tri = [ [ 1 , 5 , 3 ] , [ 4 , 8 , 0 ] , [ 1 , 0 , 0 ] ] NEW_LINE print ( maxPathSum ( tri ) ) NEW_LINE
Count no . of ordered subsets having a particular XOR value | Python 3 implementation of the approach ; Returns count of ordered subsets of arr [ ] with XOR value = K ; Find maximum element in arr [ ] ; Maximum possible XOR value ; The value of dp [ i ] [ j ] [ k ] is the number of subsets of length k having XOR of their elements as j from the set arr [ 0. . . i - 1 ] ; Initializing all the values of dp [ i ] [ j ] [ k ] as 0 ; The xor of empty subset is 0 ; Fill the dp table ; The answer is the number of subsets of all lengths from set arr [ 0. . n - 1 ] having XOR of elements as k ; Driver Code
from math import log2 NEW_LINE def subsetXOR ( arr , n , K ) : NEW_LINE INDENT max_ele = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > max_ele ) : NEW_LINE INDENT max_ele = arr [ i ] NEW_LINE DEDENT DEDENT m = ( 1 << int ( log2 ( max_ele ) + 1 ) ) - 1 NEW_LINE dp = [ [ [ 0 for i in range ( n + 1 ) ] for j in range ( m + 1 ) ] for k in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( m + 1 ) : NEW_LINE INDENT for k in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = 0 NEW_LINE DEDENT DEDENT DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( m + 1 ) : NEW_LINE INDENT for k in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = dp [ i - 1 ] [ j ] [ k ] NEW_LINE if ( k != 0 ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] += k * dp [ i - 1 ] [ j ^ arr [ i - 1 ] ] [ k - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans += dp [ n ] [ K ] [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE k = 1 NEW_LINE n = len ( arr ) NEW_LINE print ( subsetXOR ( arr , n , k ) ) NEW_LINE DEDENT
Possible cuts of a number such that maximum parts are divisible by 3 | Python3 program to find the maximum number of numbers divisible by 3 in a large number ; This will contain the count of the splits ; This will keep sum of all successive integers , when they are indivisible by 3 ; This is the condition of finding a split ; Driver code
def get_max_splits ( num_string ) : NEW_LINE INDENT count = 0 NEW_LINE running_sum = 0 NEW_LINE for i in range ( len ( num_string ) ) : NEW_LINE INDENT current_num = int ( num_string [ i ] ) NEW_LINE running_sum += current_num NEW_LINE if current_num % 3 == 0 or ( running_sum != 0 and running_sum % 3 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE running_sum = 0 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT print get_max_splits ( "12345" ) NEW_LINE
Count of Numbers in a Range where digit d occurs exactly K times | Python Program to find the count of numbers in a range where digit d occurs exactly K times ; states - position , count , tight , nonz ; d is required digit and K is occurrence ; This function returns the count of required numbers from 0 to num ; Last position ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; Nonz is true if we placed a non zero digit at the starting of the number ; At this position , number becomes smaller ; Next recursive call , also set nonz to 1 if current digit is non zero ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver Code
M = 20 NEW_LINE dp = [ ] NEW_LINE d , K = None , None NEW_LINE def count ( pos , cnt , tight , nonz , num : list ) : NEW_LINE INDENT if pos == len ( num ) : NEW_LINE INDENT if cnt == K : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if dp [ pos ] [ cnt ] [ tight ] [ nonz ] != - 1 : NEW_LINE INDENT return dp [ pos ] [ cnt ] [ tight ] [ nonz ] NEW_LINE DEDENT ans = 0 NEW_LINE limit = 9 if tight else num [ pos ] NEW_LINE for dig in range ( limit + 1 ) : NEW_LINE INDENT currCnt = cnt NEW_LINE if dig == d : NEW_LINE INDENT if d != 0 or not d and nonz : NEW_LINE INDENT currCnt += 1 NEW_LINE DEDENT DEDENT currTight = tight NEW_LINE if dig < num [ pos ] : NEW_LINE INDENT currTight = 1 NEW_LINE DEDENT ans += count ( pos + 1 , currCnt , currTight , ( nonz or dig != 0 ) , num ) NEW_LINE DEDENT dp [ pos ] [ cnt ] [ tight ] [ nonz ] = ans NEW_LINE return dp [ pos ] [ cnt ] [ tight ] [ nonz ] NEW_LINE DEDENT def solve ( x ) : NEW_LINE INDENT global dp , K , d NEW_LINE num = [ ] NEW_LINE while x : NEW_LINE INDENT num . append ( x % 10 ) NEW_LINE x //= 10 NEW_LINE DEDENT num . reverse ( ) NEW_LINE dp = [ [ [ [ - 1 , - 1 ] for i in range ( 2 ) ] for j in range ( M ) ] for k in range ( M ) ] NEW_LINE return count ( 0 , 0 , 0 , 0 , num ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 11 NEW_LINE R = 100 NEW_LINE d = 2 NEW_LINE K = 1 NEW_LINE print ( solve ( R ) - solve ( L - 1 ) ) NEW_LINE DEDENT
Count of Numbers in Range where first digit is equal to last digit of the number | Python3 program to implement the above approach ; Base Case ; Calculating the last digit ; Calculating the first digit ; Driver Code
def solve ( x ) : NEW_LINE INDENT ans , temp = 0 , x NEW_LINE if ( x < 10 ) : NEW_LINE INDENT return x NEW_LINE DEDENT last = x % 10 NEW_LINE while ( x ) : NEW_LINE INDENT first = x % 10 NEW_LINE x = x // 10 NEW_LINE DEDENT if ( first <= last ) : NEW_LINE INDENT ans = 9 + temp // 10 NEW_LINE DEDENT else : NEW_LINE INDENT ans = 8 + temp // 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT L , R = 2 , 60 NEW_LINE print ( solve ( R ) - solve ( L - 1 ) ) NEW_LINE L , R = 1 , 1000 NEW_LINE print ( solve ( R ) - solve ( L - 1 ) ) NEW_LINE
Form N | function returns the minimum cost to form a n - copy string Here , x -> Cost to add / remove a single character ' G ' and y -> cost to append the string to itself ; base case : ro form a 1 - copy string we need tp perform an operation of type 1 ( i , e Add ) ; case1 . Perform a Add operation on ( i - 1 ) copy string case2 . perform a type 2 operation on ( ( i + 1 ) / 2 ) - copy string ; case1 . Perform a Add operation on ( i - 1 ) - copy string case2 . Perform a type operation on ( i / 2 ) - copy string ; Driver code
def findMinimumCost ( n , x , y ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE dp [ 1 ] = x NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if i & 1 : NEW_LINE INDENT dp [ i ] = min ( dp [ i - 1 ] + x , dp [ ( i + 1 ) // 2 ] + y + x ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = min ( dp [ i - 1 ] + x , dp [ i // 2 ] + y ) NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT n , x , y = 4 , 2 , 1 NEW_LINE print ( findMinimumCost ( n , x , y ) ) NEW_LINE
Minimum steps to reach any of the boundary edges of a matrix | Set 1 | Python program to find Minimum steps to reach any of the boundary edges of a matrix ; Function to find out minimum steps ; boundary edges reached ; already had a route through this point , hence no need to re - visit ; visiting a position ; vertically up ; horizontally right ; horizontally left ; vertically down ; minimum of every path ; Function that returns the minimum steps ; index to store the location at which you are standing ; find '2' in the matrix ; Initialize dp matrix with - 1 ; Initialize vis matrix with false ; Call function to find out minimum steps using memoization and recursion ; if not possible ; Driver Code
r = 4 NEW_LINE col = 5 NEW_LINE def findMinSteps ( mat , n , m , dp , vis ) : NEW_LINE INDENT if ( n == 0 or m == 0 or n == ( r - 1 ) or m == ( col - 1 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ n ] [ m ] != - 1 ) : NEW_LINE INDENT return dp [ n ] [ m ] NEW_LINE DEDENT vis [ n ] [ m ] = True NEW_LINE ans1 , ans2 , ans3 , ans4 = 10 ** 9 , 10 ** 9 , 10 ** 9 , 10 ** 9 NEW_LINE if ( mat [ n - 1 ] [ m ] == 0 ) : NEW_LINE INDENT if ( vis [ n - 1 ] [ m ] == False ) : NEW_LINE INDENT ans1 = 1 + findMinSteps ( mat , n - 1 , m , dp , vis ) NEW_LINE DEDENT DEDENT if ( mat [ n ] [ m + 1 ] == 0 ) : NEW_LINE INDENT if ( vis [ n ] [ m + 1 ] == False ) : NEW_LINE INDENT ans2 = 1 + findMinSteps ( mat , n , m + 1 , dp , vis ) NEW_LINE DEDENT DEDENT if ( mat [ n ] [ m - 1 ] == 0 ) : NEW_LINE INDENT if ( vis [ n ] [ m - 1 ] == False ) : NEW_LINE INDENT ans3 = 1 + findMinSteps ( mat , n , m - 1 , dp , vis ) NEW_LINE DEDENT DEDENT if ( mat [ n + 1 ] [ m ] == 0 ) : NEW_LINE INDENT if ( vis [ n + 1 ] [ m ] == False ) : NEW_LINE INDENT ans4 = 1 + findMinSteps ( mat , n + 1 , m , dp , vis ) NEW_LINE DEDENT DEDENT dp [ n ] [ m ] = min ( ans1 , min ( ans2 , min ( ans3 , ans4 ) ) ) NEW_LINE return dp [ n ] [ m ] NEW_LINE DEDENT def minimumSteps ( mat , n , m ) : NEW_LINE INDENT twox = - 1 NEW_LINE twoy = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 2 ) : NEW_LINE INDENT twox = i NEW_LINE twoy = j NEW_LINE break NEW_LINE DEDENT DEDENT if ( twox != - 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT dp = [ [ - 1 for i in range ( col ) ] for i in range ( r ) ] NEW_LINE vis = [ [ False for i in range ( col ) ] for i in range ( r ) ] NEW_LINE res = findMinSteps ( mat , twox , twoy , dp , vis ) NEW_LINE if ( res >= 10 ** 9 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return res NEW_LINE DEDENT DEDENT mat = [ [ 1 , 1 , 1 , 0 , 1 ] , [ 1 , 0 , 2 , 0 , 1 ] , [ 0 , 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 1 , 0 ] ] NEW_LINE print ( minimumSteps ( mat , r , col ) ) NEW_LINE
Count the number of special permutations | function to return the number of ways to chooser objects out of n objects ; function to return the number of degrangemnets of n ; function to return the required number of permutations ; ways to chose i indices from n indices ; Dearrangements of ( n - i ) indices ; Driver Code
def nCr ( n , r ) : NEW_LINE INDENT ans = 1 NEW_LINE if r > n - r : NEW_LINE INDENT r = n - r NEW_LINE DEDENT for i in range ( r ) : NEW_LINE INDENT ans *= ( n - i ) NEW_LINE ans /= ( i + 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def countDerangements ( n ) : NEW_LINE INDENT der = [ 0 for i in range ( n + 3 ) ] NEW_LINE der [ 0 ] = 1 NEW_LINE der [ 1 ] = 0 NEW_LINE der [ 2 ] = 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT der [ i ] = ( i - 1 ) * ( der [ i - 1 ] + der [ i - 2 ] ) NEW_LINE DEDENT return der [ n ] NEW_LINE DEDENT def countPermutations ( n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n - k , n + 1 ) : NEW_LINE INDENT ways = nCr ( n , i ) NEW_LINE ans += ways * countDerangements ( n - i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT n , k = 5 , 3 NEW_LINE print ( countPermutations ( n , k ) ) NEW_LINE
Paths with maximum number of ' a ' from ( 1 , 1 ) to ( X , Y ) vertically or horizontally | Python3 program to find paths with maximum number of ' a ' from ( 1 , 1 ) to ( X , Y ) vertically or horizontally ; Function to answer queries ; Iterate till query ; Decrease to get 0 - based indexing ; Print answer ; Function that pre - computes the dp array ; Check for the first character ; Iterate in row and columns ; If not first row or not first column ; Not first row ; Not first column ; If it is not ' a ' then increase by 1 ; Driver code ; Character N X N array ; Queries ; Number of queries ; Function call to pre - compute ; function call to answer every query
n = 3 NEW_LINE dp = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE def answerQueries ( queries , q ) : NEW_LINE INDENT for i in range ( q ) : NEW_LINE INDENT x = queries [ i ] [ 0 ] NEW_LINE x -= 1 NEW_LINE y = queries [ i ] [ 1 ] NEW_LINE y -= 1 NEW_LINE print ( dp [ x ] [ y ] ) NEW_LINE DEDENT DEDENT def pre_compute ( a ) : NEW_LINE INDENT if a [ 0 ] [ 0 ] == ' a ' : NEW_LINE INDENT dp [ 0 ] [ 0 ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE DEDENT for row in range ( n ) : NEW_LINE INDENT for col in range ( n ) : NEW_LINE INDENT if ( row != 0 or col != 0 ) : NEW_LINE INDENT dp [ row ] [ col ] = 9999 NEW_LINE DEDENT if ( row != 0 ) : NEW_LINE INDENT dp [ row ] [ col ] = min ( dp [ row ] [ col ] , dp [ row - 1 ] [ col ] ) NEW_LINE DEDENT if ( col != 0 ) : NEW_LINE INDENT dp [ row ] [ col ] = min ( dp [ row ] [ col ] , dp [ row ] [ col - 1 ] ) NEW_LINE DEDENT if ( a [ row ] [ col ] != ' a ' and ( row != 0 or col != 0 ) ) : NEW_LINE INDENT dp [ row ] [ col ] += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ ( ' a ' , ' b ' , ' a ' ) , ( ' a ' , ' c ' , ' d ' ) , ( ' b ' , ' a ' , ' b ' ) ] NEW_LINE queries = [ ( 1 , 3 ) , ( 3 , 3 ) ] NEW_LINE q = 2 NEW_LINE pre_compute ( a ) NEW_LINE answerQueries ( queries , q ) NEW_LINE DEDENT
Ways to place K bishops on an NÃ — N chessboard so that no two attack | returns the number of squares in diagonal i ; returns the number of ways to fill a n * n chessboard with k bishops so that no two bishops attack each other . ; return 0 if the number of valid places to be filled is less than the number of bishops ; dp table to store the values ; Setting the base conditions ; calculate the required number of ways ; stores the answer ; Driver code
def squares ( i ) : NEW_LINE INDENT if ( ( i & 1 ) == 1 ) : NEW_LINE INDENT return int ( i / 4 ) * 2 + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return int ( ( i - 1 ) / 4 ) * 2 + 2 NEW_LINE DEDENT DEDENT def bishop_placements ( n , k ) : NEW_LINE INDENT if ( k > 2 * n - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT dp = [ [ 0 for i in range ( k + 1 ) ] for i in range ( n * 2 ) ] NEW_LINE for i in range ( n * 2 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 1 NEW_LINE DEDENT dp [ 1 ] [ 1 ] = 1 NEW_LINE for i in range ( 2 , n * 2 , 1 ) : NEW_LINE INDENT for j in range ( 1 , k + 1 , 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i - 2 ] [ j ] + dp [ i - 2 ] [ j - 1 ] * ( squares ( i ) - j + 1 ) ) NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 0 , k + 1 , 1 ) : NEW_LINE INDENT ans += ( dp [ n * 2 - 1 ] [ i ] * dp [ n * 2 - 2 ] [ k - i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 NEW_LINE k = 2 NEW_LINE ans = bishop_placements ( n , k ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Number of ways to partition a string into two balanced subsequences | For maximum length of input string ; Declaring the DP table ; Declaring the prefix array ; Function to calculate the number of valid assignments ; Return 1 if X is balanced . ; Increment the count if it is an opening bracket ; Decrement the count if it is a closing bracket ; Driver code ; Creating the prefix array ; Initial value for c_x and c_y is zero
MAX = 10 NEW_LINE F = [ [ - 1 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE C = [ None ] * MAX NEW_LINE def noOfAssignments ( S , n , i , c_x ) : NEW_LINE INDENT if F [ i ] [ c_x ] != - 1 : NEW_LINE INDENT return F [ i ] [ c_x ] NEW_LINE DEDENT if i == n : NEW_LINE INDENT F [ i ] [ c_x ] = not c_x NEW_LINE return F [ i ] [ c_x ] NEW_LINE DEDENT c_y = C [ i ] - c_x NEW_LINE if S [ i ] == ' ( ' : NEW_LINE INDENT F [ i ] [ c_x ] = noOfAssignments ( S , n , i + 1 , c_x + 1 ) + noOfAssignments ( S , n , i + 1 , c_x ) NEW_LINE return F [ i ] [ c_x ] NEW_LINE DEDENT F [ i ] [ c_x ] = 0 NEW_LINE if c_x : NEW_LINE INDENT F [ i ] [ c_x ] += noOfAssignments ( S , n , i + 1 , c_x - 1 ) NEW_LINE DEDENT if c_y : NEW_LINE INDENT F [ i ] [ c_x ] += noOfAssignments ( S , n , i + 1 , c_x ) NEW_LINE DEDENT return F [ i ] [ c_x ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " ( ) " NEW_LINE n = len ( S ) NEW_LINE C [ 0 ] = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if S [ i ] == ' ( ' : NEW_LINE INDENT C [ i + 1 ] = C [ i ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT C [ i + 1 ] = C [ i ] - 1 NEW_LINE DEDENT DEDENT print ( noOfAssignments ( S , n , 0 , 0 ) ) NEW_LINE DEDENT
Minimum sum falling path in a NxN grid | Python3 Program to minimum required sum ; Function to return minimum path falling sum ; R = Row and C = Column We begin from second last row and keep adding maximum sum . ; best = min ( A [ R + 1 ] [ C - 1 ] , A [ R + 1 ] [ C ] , A [ R + 1 ] [ C + 1 ] ) ; Driver code ; function to print required answer
import sys NEW_LINE n = 3 NEW_LINE def minFallingPathSum ( A ) : NEW_LINE INDENT for R in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT for C in range ( n ) : NEW_LINE INDENT best = A [ R + 1 ] [ C ] NEW_LINE if C > 0 : NEW_LINE INDENT best = min ( best , A [ R + 1 ] [ C - 1 ] ) NEW_LINE DEDENT if C + 1 < n : NEW_LINE INDENT best = min ( best , A [ R + 1 ] [ C + 1 ] ) NEW_LINE DEDENT A [ R ] [ C ] = A [ R ] [ C ] + best NEW_LINE DEDENT DEDENT ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = min ( ans , A [ 0 ] [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE print ( minFallingPathSum ( A ) ) NEW_LINE DEDENT
Find the maximum sum of Plus shape pattern in a 2 | Python 3 program to find the maximum value of a + shaped pattern in 2 - D array ; Function to return maximum Plus value ; Initializing answer with the minimum value ; Initializing all four arrays ; Initializing left and up array . ; Initializing right and down array . ; calculating value of maximum Plus ( + ) sign ; Driver code ; Function call to find maximum value
N = 100 NEW_LINE n = 3 NEW_LINE m = 4 NEW_LINE def maxPlus ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE left = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE right = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE up = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE down = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT left [ i ] [ j ] = ( max ( 0 , ( left [ i ] [ j - 1 ] if j else 0 ) ) + arr [ i ] [ j ] ) NEW_LINE up [ i ] [ j ] = ( max ( 0 , ( up [ i - 1 ] [ j ] if i else 0 ) ) + arr [ i ] [ j ] ) NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT right [ i ] [ j ] = max ( 0 , ( 0 if ( j + 1 == m ) else right [ i ] [ j + 1 ] ) ) + arr [ i ] [ j ] NEW_LINE down [ i ] [ j ] = max ( 0 , ( 0 if ( i + 1 == n ) else down [ i + 1 ] [ j ] ) ) + arr [ i ] [ j ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT for j in range ( 1 , m - 1 ) : NEW_LINE INDENT ans = max ( ans , up [ i - 1 ] [ j ] + down [ i + 1 ] [ j ] + left [ i ] [ j - 1 ] + right [ i ] [ j + 1 ] + arr [ i ] [ j ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 1 , 1 , 1 ] , [ - 6 , 1 , 1 , - 4 ] , [ 1 , 1 , 1 , 1 ] ] NEW_LINE print ( maxPlus ( arr ) ) NEW_LINE DEDENT
Total number of different staircase that can made from N boxes | Function to find the total number of different staircase that can made from N boxes ; DP table , there are two states . First describes the number of boxes and second describes the step ; Initialize all the elements of the table to zero ; Base case ; When step is equal to 2 ; When step is greater than 2 ; Count the total staircase from all the steps ; Driver Code
def countStaircases ( N ) : NEW_LINE INDENT memo = [ [ 0 for x in range ( N + 5 ) ] for y in range ( N + 5 ) ] NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT for j in range ( N + 1 ) : NEW_LINE INDENT memo [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT memo [ 3 ] [ 2 ] = memo [ 4 ] [ 2 ] = 1 NEW_LINE for i in range ( 5 , N + 1 ) : NEW_LINE INDENT for j in range ( 2 , i + 1 ) : NEW_LINE INDENT if ( j == 2 ) : NEW_LINE INDENT memo [ i ] [ j ] = memo [ i - j ] [ j ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT memo [ i ] [ j ] = ( memo [ i - j ] [ j ] + memo [ i - j ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT answer = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT answer = answer + memo [ N ] [ i ] NEW_LINE DEDENT return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 NEW_LINE print ( countStaircases ( N ) ) NEW_LINE DEDENT
Find maximum points which can be obtained by deleting elements from array | function to return maximum cost obtained ; find maximum element of the array . ; create and initialize count of all elements to zero . ; calculate frequency of all elements of array . ; stores cost of deleted elements . ; selecting minimum range from L and R . ; finds upto which elements are to be deleted when element num is selected . ; get maximum when selecting element num or not . ; Driver code ; size of array ; function call to find maximum cost
def maxCost ( a , n , l , r ) : NEW_LINE INDENT mx = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mx = max ( mx , a [ i ] ) NEW_LINE DEDENT count = [ 0 ] * ( mx + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ a [ i ] ] += 1 NEW_LINE DEDENT res = [ 0 ] * ( mx + 1 ) NEW_LINE res [ 0 ] = 0 NEW_LINE l = min ( l , r ) NEW_LINE for num in range ( 1 , mx + 1 ) : NEW_LINE INDENT k = max ( num - l - 1 , 0 ) NEW_LINE res [ num ] = max ( res [ num - 1 ] , num * count [ num ] + res [ k ] ) NEW_LINE DEDENT return res [ mx ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 1 , 2 , 3 , 2 , 2 , 1 ] NEW_LINE l , r = 1 , 1 NEW_LINE n = len ( a ) NEW_LINE print ( maxCost ( a , n , l , r ) ) NEW_LINE DEDENT
Count the number of ways to traverse a Matrix | Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Return 1 if it is the first row or first column ; Recursively find the no of way to reach the last cell . ; Driver code
def countPaths ( m , n ) : NEW_LINE INDENT if m == 1 or n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( countPaths ( m - 1 , n ) + countPaths ( m , n - 1 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE m = 5 NEW_LINE print ( countPaths ( n , m ) ) NEW_LINE DEDENT
Count the number of ways to traverse a Matrix | Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Driver code
def countPaths ( m , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( m + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i == 1 or j == 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ m ] [ n ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE m = 5 NEW_LINE print ( countPaths ( n , m ) ) NEW_LINE DEDENT
Minimum number of palindromes required to express N as a sum | Set 1 | Declaring the DP table as global variable ; A utility for creating palindrome ; checks if number of digits is odd or even if odd then neglect the last digit of input in finding reverse as in case of odd number of digits middle element occur once ; Creates palindrome by just appending reverse of number to itself ; Function to generate palindromes ; Run two times for odd and even length palindromes ; Creates palindrome numbers with first half as i . Value of j decides whether we need an odd length or even length palindrome . ; Function to find the minimum number of elements in a sorted array A [ i . . j ] such that their sum is N ; Function to find the minimum number of palindromes that N can be expressed as a sum of ; Getting the list of all palindromes upto N ; Sorting the list of palindromes ; Returning the required value ; Driver code
dp = [ [ 0 for i in range ( 1000 ) ] for i in range ( 1000 ) ] NEW_LINE def createPalindrome ( input , isOdd ) : NEW_LINE INDENT n = input NEW_LINE palin = input NEW_LINE if ( isOdd ) : NEW_LINE INDENT n //= 10 NEW_LINE DEDENT while ( n > 0 ) : NEW_LINE INDENT palin = palin * 10 + ( n % 10 ) NEW_LINE n //= 10 NEW_LINE DEDENT return palin NEW_LINE DEDENT def generatePalindromes ( N ) : NEW_LINE INDENT palindromes = [ ] NEW_LINE number = 0 NEW_LINE for j in range ( 2 ) : NEW_LINE INDENT i = 1 NEW_LINE number = createPalindrome ( i , j ) NEW_LINE while number <= N : NEW_LINE INDENT number = createPalindrome ( i , j ) NEW_LINE palindromes . append ( number ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT return palindromes NEW_LINE DEDENT def minimumSubsetSize ( A , i , j , N ) : NEW_LINE INDENT if ( not N ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( i > j or A [ i ] > N ) : NEW_LINE INDENT return 10 ** 9 NEW_LINE DEDENT if ( dp [ i ] [ N ] ) : NEW_LINE INDENT return dp [ i ] [ N ] NEW_LINE DEDENT dp [ i ] [ N ] = min ( 1 + minimumSubsetSize ( A , i + 1 , j , N - A [ i ] ) , minimumSubsetSize ( A , i + 1 , j , N ) ) NEW_LINE return dp [ i ] [ N ] NEW_LINE DEDENT def minimumNoOfPalindromes ( N ) : NEW_LINE INDENT palindromes = generatePalindromes ( N ) NEW_LINE palindromes = sorted ( palindromes ) NEW_LINE return minimumSubsetSize ( palindromes , 0 , len ( palindromes ) - 1 , N ) NEW_LINE DEDENT N = 65 NEW_LINE print ( minimumNoOfPalindromes ( N ) ) NEW_LINE
Number of ways a convex polygon of n + 2 sides can split into triangles by connecting vertices | Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver code
def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 ; NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k ; NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT res *= ( n - i ) ; NEW_LINE res /= ( i + 1 ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def catalan ( n ) : NEW_LINE INDENT c = binomialCoeff ( 2 * n , n ) ; NEW_LINE return int ( c / ( n + 1 ) ) ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( catalan ( n ) ) ; NEW_LINE
Alternate Fibonacci Numbers | Alternate Fibonacci Series using Dynamic Programming ; 0 th and 1 st number of the series are 0 and 1 ; Driver Code
def alternateFib ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT f1 = 0 ; NEW_LINE f2 = 1 ; NEW_LINE print ( f1 , end = " ▁ " ) ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT f3 = f2 + f1 ; NEW_LINE if ( i % 2 == 0 ) : NEW_LINE INDENT print ( f3 , end = " ▁ " ) ; NEW_LINE DEDENT f1 = f2 ; NEW_LINE f2 = f3 ; NEW_LINE DEDENT DEDENT N = 15 ; NEW_LINE alternateFib ( N ) ; NEW_LINE
Number of ways to form an array with distinct adjacent elements | Returns the total ways to form arrays such that every consecutive element is different and each element except the first and last can take values from 1 to M ; define the dp [ ] [ ] array ; if the first element is 1 ; there is only one way to place a 1 at the first index ; the value at first index needs to be 1 , thus there is no way to place a non - one integer ; if the first element was 1 then at index 1 , only non one integer can be placed thus there are M - 1 ways to place a non one integer at index 2 and 0 ways to place a 1 at the 2 nd index ; Else there is one way to place a one at index 2 and if a non one needs to be placed here , there are ( M - 2 ) options , i . e neither the element at this index should be 1 , neither should it be equal to the previous element ; Build the dp array in bottom up manner ; f ( i , one ) = f ( i - 1 , non - one ) ; f ( i , non - one ) = f ( i - 1 , one ) * ( M - 1 ) + f ( i - 1 , non - one ) * ( M - 2 ) ; last element needs to be one , so return dp [ n - 1 ] [ 0 ] ; Driver Code
def totalWays ( N , M , X ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for j in range ( N + 1 ) ] NEW_LINE if ( X == 1 ) : NEW_LINE INDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0 ] [ 1 ] = 0 NEW_LINE DEDENT if ( X == 1 ) : NEW_LINE INDENT dp [ 1 ] [ 0 ] = 0 NEW_LINE dp [ 1 ] [ 1 ] = M - 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 1 ] [ 0 ] = 1 NEW_LINE dp [ 1 ] [ 1 ] = ( M - 2 ) NEW_LINE DEDENT for i in range ( 2 , N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 1 ] NEW_LINE dp [ i ] [ 1 ] = dp [ i - 1 ] [ 0 ] * ( M - 1 ) + dp [ i - 1 ] [ 1 ] * ( M - 2 ) NEW_LINE DEDENT return dp [ N - 1 ] [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE M = 3 NEW_LINE X = 2 NEW_LINE print ( totalWays ( N , M , X ) ) NEW_LINE DEDENT
Memoization ( 1D , 2D and 3D ) | Fibonacci Series using Recursion ; Base case ; recursive calls ; Driver Code
def fib ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT return fib ( n - 1 ) + fib ( n - 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE print ( fib ( n ) ) NEW_LINE DEDENT
Memoization ( 1D , 2D and 3D ) | Python program to find the Nth term of Fibonacci series ; Fibonacci Series using memoized Recursion ; base case ; if fib ( n ) has already been computed we do not do further recursive calls and hence reduce the number of repeated work ; store the computed value of fib ( n ) in an array term at index n to so that it does not needs to be precomputed again ; Driver Code
term = [ 0 for i in range ( 1000 ) ] NEW_LINE def fib ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return n NEW_LINE DEDENT if term [ n ] != 0 : NEW_LINE INDENT return term [ n ] NEW_LINE DEDENT else : NEW_LINE INDENT term [ n ] = fib ( n - 1 ) + fib ( n - 2 ) NEW_LINE return term [ n ] NEW_LINE DEDENT DEDENT n = 6 NEW_LINE print ( fib ( n ) ) NEW_LINE
Memoization ( 1D , 2D and 3D ) | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Driver Code
def lcs ( X , Y , m , n ) : NEW_LINE INDENT if ( m == 0 or n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( X [ m - 1 ] == Y [ n - 1 ] ) : NEW_LINE INDENT return 1 + lcs ( X , Y , m - 1 , n - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return max ( lcs ( X , Y , m , n - 1 ) , lcs ( X , Y , m - 1 , n ) ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = " AGGTAB " ; NEW_LINE Y = " GXTXAYB " ; NEW_LINE m = len ( X ) ; NEW_LINE n = len ( Y ) ; NEW_LINE print ( " Length ▁ of ▁ LCS ▁ is ▁ { } n " . format ( lcs ( X , Y , m , n ) ) ) NEW_LINE DEDENT
Smallest number with given sum of digits and sum of square of digits | Python3 program to find the Smallest number with given sum of digits and sum of square of digits ; Top down dp to find minimum number of digits with given sum of dits a and sum of square of digits as b ; Invalid condition ; Number of digits satisfied ; Memoization ; Initialize ans as maximum as we have to find the minimum number of digits ; Check for all possible combinations of digits ; recurrence call ; If the combination of digits cannot give sum as a and sum of square of digits as b ; Returns the minimum number of digits ; Function to print the digits that gives sum as a and sum of square of digits as b ; initialize the dp array as ; base condition ; function call to get the minimum number of digits ; When there does not exists any number ; Printing the digits from the most significant digit ; Trying all combinations ; checking conditions for minimum digits ; Driver Code ; Function call to print the smallest number
dp = [ [ - 1 for i in range ( 8101 ) ] for i in range ( 901 ) ] NEW_LINE def minimumNumberOfDigits ( a , b ) : NEW_LINE INDENT if ( a > b or a < 0 or b < 0 or a > 900 or b > 8100 ) : NEW_LINE INDENT return - 1 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 ans = 101 NEW_LINE for i in range ( 9 , 0 , - 1 ) : NEW_LINE INDENT k = minimumNumberOfDigits ( a - i , b - ( i * i ) ) NEW_LINE if ( k != - 1 ) : NEW_LINE INDENT ans = min ( ans , k + 1 ) NEW_LINE DEDENT DEDENT dp [ a ] [ b ] = ans NEW_LINE return ans NEW_LINE DEDENT def printSmallestNumber ( a , b ) : NEW_LINE INDENT for i in range ( 901 ) : NEW_LINE INDENT for j in range ( 8101 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT dp [ 0 ] [ 0 ] = 0 NEW_LINE k = minimumNumberOfDigits ( a , b ) NEW_LINE if ( k == - 1 or k > 100 ) : NEW_LINE INDENT print ( - 1 , end = ' ' ) NEW_LINE DEDENT else : NEW_LINE INDENT while ( a > 0 and b > 0 ) : NEW_LINE INDENT for i in range ( 1 , 10 ) : NEW_LINE INDENT if ( a >= i and b >= i * i and 1 + dp [ a - i ] [ b - i * i ] == dp [ a ] [ b ] ) : NEW_LINE INDENT print ( i , end = ' ' ) NEW_LINE a -= i NEW_LINE b -= i * i NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 18 NEW_LINE b = 162 NEW_LINE printSmallestNumber ( a , b ) NEW_LINE DEDENT
Sum of product of consecutive Binomial Coefficients | Python3 Program to find sum of product of consecutive Binomial Coefficient . ; Find the binomial coefficient up to nth term ; C [ 0 ] = 1 ; nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Return the sum of the product of consecutive binomial coefficient . ; Driver Code
MAX = 100 ; NEW_LINE def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ 0 ] * ( k + 1 ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) , 0 , - 1 ) : NEW_LINE INDENT C [ j ] = C [ j ] + C [ j - 1 ] ; NEW_LINE DEDENT DEDENT return C [ k ] ; NEW_LINE DEDENT def sumOfproduct ( n ) : NEW_LINE INDENT return binomialCoeff ( 2 * n , n - 1 ) ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( sumOfproduct ( n ) ) ; NEW_LINE
Check if array sum can be made K by three operations on it | Python program to find if Array can have sum of K by applying three types of possible operations on it ; Check if it is possible to achieve a sum with three operation allowed ; if sum id negative . ; If going out of bound . ; If sum is achieved . ; If the current state is not evaluated yet . ; Replacing element with negative value of the element . ; Substracting index number from the element . ; Adding index number to the element . ; Wrapper Function ; Driver Code
MAX = 100 NEW_LINE def check ( i , add , n , k , a , dp ) : NEW_LINE INDENT if add <= 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if i >= n : NEW_LINE INDENT if add == k : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if dp [ i ] [ add ] != - 1 : NEW_LINE INDENT return dp [ i ] [ add ] NEW_LINE DEDENT dp [ i ] [ add ] = ( check ( i + 1 , add - 2 * a [ i ] , n , k , a , dp ) or check ( i + 1 , add , n , k , a , dp ) ) NEW_LINE dp [ i ] [ add ] = ( check ( i + 1 , add - ( i + 1 ) , n , k , a , dp ) or dp [ i ] [ add ] ) NEW_LINE dp [ i ] [ add ] = ( check ( i + 1 , add + i + 1 , n , k , a , dp ) or dp [ i ] [ add ] ) NEW_LINE return dp [ i ] [ add ] NEW_LINE DEDENT def wrapper ( n , k , a ) : NEW_LINE INDENT add = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT add += a [ i ] NEW_LINE DEDENT dp = [ - 1 ] * MAX NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT dp [ i ] = [ - 1 ] * MAX NEW_LINE DEDENT return check ( 0 , add , n , k , a , dp ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 3 , 4 ] NEW_LINE n = 4 NEW_LINE k = 5 NEW_LINE print ( " Yes " ) if wrapper ( n , k , a ) else print ( " No " ) NEW_LINE DEDENT
Print Fibonacci sequence using 2 variables | Simple Python3 Program to print Fibonacci sequence ; Driver code
def fib ( n ) : NEW_LINE INDENT a = 0 NEW_LINE b = 1 NEW_LINE if ( n >= 0 ) : NEW_LINE INDENT print ( a , end = ' ▁ ' ) NEW_LINE DEDENT if ( n >= 1 ) : NEW_LINE INDENT print ( b , end = ' ▁ ' ) NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT c = a + b NEW_LINE print ( c , end = ' ▁ ' ) NEW_LINE a = b NEW_LINE b = c NEW_LINE DEDENT DEDENT fib ( 9 ) NEW_LINE
Maximum sum increasing subsequence from a prefix and a given element after prefix is must | Python3 program to find maximum sum increasing subsequence till i - th index and including k - th index . ; Initializing the first row of the dp [ ] [ ] ; Creating the dp [ ] [ ] matrix . ; To calculate for i = 4 and k = 6. ; Driver code
def pre_compute ( a , n , index , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] > a [ 0 ] : NEW_LINE INDENT dp [ 0 ] [ i ] = a [ i ] + a [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0 ] [ i ] = a [ i ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if a [ j ] > a [ i ] and j > i : NEW_LINE INDENT if dp [ i - 1 ] [ i ] + a [ j ] > dp [ i - 1 ] [ j ] : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ i ] + a [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return dp [ index ] [ k ] NEW_LINE DEDENT a = [ 1 , 101 , 2 , 3 , 100 , 4 , 5 ] NEW_LINE n = len ( a ) NEW_LINE index = 4 NEW_LINE k = 6 NEW_LINE print ( pre_compute ( a , n , index , k ) ) NEW_LINE
Moser | Function to generate nth term of Moser - de Bruijn Sequence ; S ( 2 * n ) = 4 * S ( n ) ; S ( 2 * n + 1 ) = 4 * S ( n ) + 1 ; Generating the first ' n ' terms of Moser - de Bruijn Sequence ; Driver Code
def gen ( n ) : NEW_LINE INDENT S = [ 0 , 1 ] NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT S . append ( 4 * S [ int ( i / 2 ) ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT S . append ( 4 * S [ int ( i / 2 ) ] + 1 ) ; NEW_LINE DEDENT DEDENT z = S [ n ] ; NEW_LINE return z ; NEW_LINE DEDENT def moserDeBruijn ( n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( gen ( i ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT n = 15 NEW_LINE print ( " First " , n , " terms ▁ of ▁ " , " Moser - de ▁ Brujn ▁ Sequence : " ) NEW_LINE moserDeBruijn ( n ) NEW_LINE
Longest Common Substring ( Space optimized DP solution ) | Space optimized Python3 implementation of longest common substring . ; Function to find longest common substring . ; Find length of both the strings . ; Variable to store length of longest common substring . ; Matrix to store result of two consecutive rows at a time . ; Variable to represent which row of matrix is current row . ; For a particular value of i and j , len_mat [ currRow ] [ j ] stores length of longest common substring in string X [ 0. . i ] and Y [ 0. . j ] . ; Make current row as previous row and previous row as new current row . ; Driver Code
import numpy as np NEW_LINE def LCSubStr ( X , Y ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE result = 0 NEW_LINE len_mat = np . zeros ( ( 2 , n ) ) NEW_LINE currRow = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i == 0 j == 0 ) : NEW_LINE INDENT len_mat [ currRow ] [ j ] = 0 NEW_LINE DEDENT elif ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT len_mat [ currRow ] [ j ] = len_mat [ 1 - currRow ] [ j - 1 ] + 1 NEW_LINE result = max ( result , len_mat [ currRow ] [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT len_mat [ currRow ] [ j ] = 0 NEW_LINE DEDENT DEDENT currRow = 1 - currRow NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = " GeeksforGeeks " NEW_LINE Y = " GeeksQuiz " NEW_LINE print ( LCSubStr ( X , Y ) ) NEW_LINE DEDENT
Minimal moves to form a string by adding characters or appending string itself | Python program to print the Minimal moves to form a string by appending string and adding characters ; function to return the minimal number of moves ; initializing dp [ i ] to INT_MAX ; initialize both strings to null ; base case ; check if it can be appended ; addition of character takes one step ; appending takes 1 step , and we directly reach index i * 2 + 1 after appending so the number of steps is stord in i * 2 + 1 ; Driver Code ; function call to return minimal number of moves
INT_MAX = 100000000 NEW_LINE def minimalSteps ( s , n ) : NEW_LINE INDENT dp = [ INT_MAX for i in range ( n ) ] NEW_LINE s1 = " " NEW_LINE s2 = " " NEW_LINE dp [ 0 ] = 1 NEW_LINE s1 += s [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT s1 += s [ i ] NEW_LINE s2 = s [ i + 1 : i + 1 + i + 1 ] NEW_LINE dp [ i ] = min ( dp [ i ] , dp [ i - 1 ] + 1 ) NEW_LINE if ( s1 == s2 ) : NEW_LINE INDENT dp [ i * 2 + 1 ] = min ( dp [ i ] + 1 , dp [ i * 2 + 1 ] ) NEW_LINE DEDENT DEDENT return dp [ n - 1 ] NEW_LINE DEDENT s = " aaaaaaaa " NEW_LINE n = len ( s ) NEW_LINE print ( minimalSteps ( s , n ) ) NEW_LINE
Check if any valid sequence is divisible by M | Function to check if any valid sequence is divisible by M ; DEclare mod array ; Calculate the mod array ; Check if sum is divisible by M ; Check if sum is not divisible by 2 ; Remove the first element from the ModArray since it is not possible to place minus on the first element ; Decrease the size of array ; Sort the array ; Loop until the pointer cross each other ; Check if sum becomes equal ; Increase and decrease the pointer accordingly ; Driver code ; Function call
def func ( n , m , A ) : NEW_LINE INDENT ModArray = [ 0 ] * n NEW_LINE Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ModArray [ i ] = A [ i ] % m NEW_LINE Sum += ModArray [ i ] NEW_LINE DEDENT Sum = Sum % m NEW_LINE if ( Sum % m == 0 ) : NEW_LINE INDENT print ( " True " ) NEW_LINE return NEW_LINE DEDENT if ( Sum % 2 != 0 ) : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT else : NEW_LINE INDENT ModArray . pop ( 0 ) NEW_LINE i = 0 NEW_LINE j = len ( ModArray ) - 1 NEW_LINE ModArray . sort ( ) NEW_LINE Sum = Sum // 2 NEW_LINE while ( i <= j ) : NEW_LINE INDENT s = ModArray [ i ] + ModArray [ j ] NEW_LINE if ( s == Sum ) : NEW_LINE INDENT i1 = i NEW_LINE i2 = j NEW_LINE print ( " True " ) NEW_LINE break NEW_LINE DEDENT elif ( s > Sum ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT m = 2 NEW_LINE a = [ 1 , 3 , 9 ] NEW_LINE n = len ( a ) NEW_LINE func ( n , m , a ) NEW_LINE
Golomb sequence | Print the first n term of Golomb Sequence ; base cases ; Finding and pring first n terms of Golomb Sequence . ; Driver Code
def Golomb ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 1 ] = 1 NEW_LINE print ( dp [ 1 ] , end = " ▁ " ) NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] = 1 + dp [ i - dp [ dp [ i - 1 ] ] ] NEW_LINE print ( dp [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT n = 9 NEW_LINE Golomb ( n ) NEW_LINE
Balanced expressions such that given positions have opening brackets | Python 3 code to find number of ways of arranging bracket with proper expressions ; function to calculate the number of proper bracket sequence ; hash array to mark the positions of opening brackets ; dp 2d array ; mark positions in hash array ; first position marked as 1 ; iterate and formulate the recurrences ; if position has a opening bracket ; return answer ; Driver Code ; positions where opening braces will be placed
N = 1000 NEW_LINE def arrangeBraces ( n , pos , k ) : NEW_LINE INDENT h = [ False for i in range ( N ) ] NEW_LINE dp = [ [ 0 for i in range ( N ) ] for i in range ( N ) ] NEW_LINE for i in range ( k ) : NEW_LINE INDENT h [ pos [ i ] ] = 1 NEW_LINE DEDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , 2 * n + 1 ) : NEW_LINE INDENT for j in range ( 2 * n + 1 ) : NEW_LINE INDENT if ( h [ i ] ) : NEW_LINE INDENT if ( j != 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( j != 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j + 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j + 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return dp [ 2 * n ] [ 0 ] NEW_LINE DEDENT n = 3 NEW_LINE pos = [ 2 , ] ; NEW_LINE k = len ( pos ) NEW_LINE print ( arrangeBraces ( n , pos , k ) ) NEW_LINE
Maximum difference of zeros and ones in binary string | Set 2 ( O ( n ) time ) | Returns the length of substring with maximum difference of zeroes and ones in binary string ; traverse a binary string from left to right ; add current value to the current_sum according to the Character if it ' s ▁ ' 0 ' add 1 else -1 ; update maximum sum ; return - 1 if string does not contain any zero that means all ones otherwise max_sum ; Driven Program
def findLength ( string , n ) : NEW_LINE INDENT current_sum = 0 NEW_LINE max_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT current_sum += ( 1 if string [ i ] == '0' else - 1 ) NEW_LINE if current_sum < 0 : NEW_LINE INDENT current_sum = 0 NEW_LINE DEDENT max_sum = max ( current_sum , max_sum ) NEW_LINE DEDENT return max_sum if max_sum else 0 NEW_LINE DEDENT s = "11000010001" NEW_LINE n = 11 NEW_LINE print ( findLength ( s , n ) ) NEW_LINE
Number of decimal numbers of length k , that are strict monotone | Python3 program to count numbers of k digits that are strictly monotone . ; DP [ i ] [ j ] is going to store monotone numbers of length i + 1 considering j + 1 digits ( 1 , 2 , 3 , . .9 ) ; Unit length numbers ; Building dp [ ] in bottom up ; Driver code
DP_s = 9 NEW_LINE def getNumStrictMonotone ( ln ) : NEW_LINE INDENT DP = [ [ 0 ] * DP_s for _ in range ( ln ) ] NEW_LINE for i in range ( DP_s ) : NEW_LINE INDENT DP [ 0 ] [ i ] = i + 1 NEW_LINE DEDENT for i in range ( 1 , ln ) : NEW_LINE INDENT for j in range ( 1 , DP_s ) : NEW_LINE INDENT DP [ i ] [ j ] = DP [ i - 1 ] [ j - 1 ] + DP [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT return DP [ ln - 1 ] [ DP_s - 1 ] NEW_LINE DEDENT print ( getNumStrictMonotone ( 2 ) ) NEW_LINE
Count ways to divide circle using N non | python code to count ways to divide circle using N non - intersecting chords . ; n = no of points required ; dp array containing the sum ; returning the required number ; driver code
def chordCnt ( A ) : NEW_LINE INDENT n = 2 * A NEW_LINE dpArray = [ 0 ] * ( n + 1 ) NEW_LINE dpArray [ 0 ] = 1 NEW_LINE dpArray [ 2 ] = 1 NEW_LINE for i in range ( 4 , n + 1 , 2 ) : NEW_LINE INDENT for j in range ( 0 , i - 1 , 2 ) : NEW_LINE INDENT dpArray [ i ] += ( dpArray [ j ] * dpArray [ i - 2 - j ] ) NEW_LINE DEDENT DEDENT return int ( dpArray [ n ] ) NEW_LINE DEDENT N = 2 NEW_LINE print ( chordCnt ( N ) ) NEW_LINE N = 1 NEW_LINE print ( chordCnt ( N ) ) NEW_LINE N = 4 NEW_LINE print ( chordCnt ( N ) ) NEW_LINE
Check for possible path in 2D matrix | Python3 program to find if there is path from top left to right bottom ; to find the path from top left to bottom right ; set arr [ 0 ] [ 0 ] = 1 ; Mark reachable ( from top left ) nodes in first row and first column . ; Mark reachable nodes in remaining matrix . ; return yes if right bottom index is 1 ; Given array ; path from arr [ 0 ] [ 0 ] to arr [ row ] [ col ]
row = 5 NEW_LINE col = 5 NEW_LINE def isPath ( arr ) : NEW_LINE INDENT arr [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , row ) : NEW_LINE INDENT if ( arr [ i ] [ 0 ] != - 1 ) : NEW_LINE INDENT arr [ i ] [ 0 ] = arr [ i - 1 ] [ 0 ] NEW_LINE DEDENT DEDENT for j in range ( 1 , col ) : NEW_LINE INDENT if ( arr [ 0 ] [ j ] != - 1 ) : NEW_LINE INDENT arr [ 0 ] [ j ] = arr [ 0 ] [ j - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 1 , row ) : NEW_LINE INDENT for j in range ( 1 , col ) : NEW_LINE INDENT if ( arr [ i ] [ j ] != - 1 ) : NEW_LINE INDENT arr [ i ] [ j ] = max ( arr [ i ] [ j - 1 ] , arr [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return ( arr [ row - 1 ] [ col - 1 ] == 1 ) NEW_LINE DEDENT arr = [ [ 0 , 0 , 0 , - 1 , 0 ] , [ - 1 , 0 , 0 , - 1 , - 1 ] , [ 0 , 0 , 0 , - 1 , 0 ] , [ - 1 , 0 , - 1 , 0 , - 1 ] , [ 0 , 0 , - 1 , 0 , 0 ] ] NEW_LINE if ( isPath ( arr ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
NewmanΓ’ β‚¬β€œ ShanksΓ’ β‚¬β€œ Williams prime | return nth NewmanaShanksaWilliams prime ; Base case ; Recursive step ; Driven Program
def nswp ( n ) : NEW_LINE INDENT if n == 0 or n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 2 * nswp ( n - 1 ) + nswp ( n - 2 ) NEW_LINE DEDENT n = 3 NEW_LINE print ( nswp ( n ) ) NEW_LINE
Newman Shanks Williams prime | return nth Newman Shanks Williams prime ; Base case ; Finding nth Newman Shanks Williams prime ; Driver Code
def nswp ( n ) : NEW_LINE INDENT dp = [ 1 for x in range ( n + 1 ) ] ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] = ( 2 * dp [ i - 1 ] + dp [ i - 2 ] ) ; NEW_LINE DEDENT return dp [ n ] ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( nswp ( n ) ) ; NEW_LINE
Number of ways to insert a character to increase the LCS by one | Python Program to Number of ways to insert a character to increase LCS by one ; Return the Number of ways to insert a character to increase the Longest Common Subsequence by one ; Insert all positions of all characters in string B ; Longest Common Subsequence ; Longest Common Subsequence from reverse ; inserting character between position i and i + 1 ; Driver Code
MAX = 256 NEW_LINE def numberofways ( A , B , N , M ) : NEW_LINE INDENT pos = [ [ ] for _ in range ( MAX ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT pos [ ord ( B [ i ] ) ] . append ( i + 1 ) NEW_LINE DEDENT dpl = [ [ 0 ] * ( M + 2 ) for _ in range ( N + 2 ) ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , M + 1 ) : NEW_LINE INDENT if A [ i - 1 ] == B [ j - 1 ] : NEW_LINE INDENT dpl [ i ] [ j ] = dpl [ i - 1 ] [ j - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dpl [ i ] [ j ] = max ( dpl [ i - 1 ] [ j ] , dpl [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT LCS = dpl [ N ] [ M ] NEW_LINE dpr = [ [ 0 ] * ( M + 2 ) for _ in range ( N + 2 ) ] NEW_LINE for i in range ( N , 0 , - 1 ) : NEW_LINE INDENT for j in range ( M , 0 , - 1 ) : NEW_LINE INDENT if A [ i - 1 ] == B [ j - 1 ] : NEW_LINE INDENT dpr [ i ] [ j ] = dpr [ i + 1 ] [ j + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dpr [ i ] [ j ] = max ( dpr [ i + 1 ] [ j ] , dpr [ i ] [ j + 1 ] ) NEW_LINE DEDENT DEDENT DEDENT ans = 0 NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT for j in range ( MAX ) : NEW_LINE INDENT for x in pos [ j ] : NEW_LINE INDENT if dpl [ i ] [ x - 1 ] + dpr [ i + 1 ] [ x + 1 ] == LCS : NEW_LINE INDENT ans += 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = " aa " NEW_LINE B = " baaa " NEW_LINE N = len ( A ) NEW_LINE M = len ( B ) NEW_LINE print ( numberofways ( A , B , N , M ) ) NEW_LINE DEDENT
Minimum cost to make two strings identical by deleting the digits | Function to returns cost of removing the identical characters in LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains cost of removing identical characters in LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; If both characters are same , add both of them ; Otherwise find the maximum cost among them ; Returns cost of making X [ ] and Y [ ] identical ; Find LCS of X [ ] and Y [ ] ; Initialize the cost variable ; Find cost of all acters in both strings ; Driver program to test above function
def lcs ( X , Y , m , n ) : NEW_LINE INDENT L = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT L [ i ] [ j ] = 0 NEW_LINE DEDENT elif ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 2 * ( ord ( X [ i - 1 ] ) - 48 ) NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return L [ m ] [ n ] NEW_LINE DEDENT def findMinCost ( X , Y ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE cost = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT cost += ord ( X [ i ] ) - 48 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT cost += ord ( Y [ i ] ) - 48 NEW_LINE DEDENT ans = cost - lcs ( X , Y , m , n ) NEW_LINE return ans NEW_LINE DEDENT X = "3759" NEW_LINE Y = "9350" NEW_LINE print ( " Minimum ▁ Cost ▁ to ▁ make ▁ two ▁ strings ▁ " , " identical ▁ is ▁ = ▁ " , findMinCost ( X , Y ) ) NEW_LINE
Given a large number , check if a subsequence of digits is divisible by 8 | Function to calculate any permutation divisible by 8. If such permutation exists , the function will return that permutation else it will return - 1 ; Generating all possible permutations and checking if any such permutation is divisible by 8 ; Driver function
def isSubSeqDivisible ( st ) : NEW_LINE INDENT l = len ( st ) NEW_LINE arr = [ int ( ch ) for ch in st ] NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT for j in range ( i , l ) : NEW_LINE INDENT for k in range ( j , l ) : NEW_LINE INDENT if ( arr [ i ] % 8 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( ( arr [ i ] * 10 + arr [ j ] ) % 8 == 0 and i != j ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( ( arr [ i ] * 100 + arr [ j ] * 10 + arr [ k ] ) % 8 == 0 and i != j and j != k and i != k ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT DEDENT return False NEW_LINE DEDENT st = "3144" NEW_LINE if ( isSubSeqDivisible ( st ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Given a large number , check if a subsequence of digits is divisible by 8 | Python3 program to check if given string has a subsequence divisible by 8 ; map key will be tens place digit of number that is divisible by 8 and value will be units place digit ; For filling the map let start with initial value 8 ; key is digit at tens place and value is digit at units place mp . insert ( { key , value } ) ; Create a hash to check if we visited a number ; Iterate from last index to 0 th index ; If 8 is present in string then 8 divided 8 hence print yes ; considering present character as the second digit of two digits no we check if the value of this key is marked in hash or not If marked then we a have a number divisible by 8 ; If no subsequence divisible by 8
Str = "129365" NEW_LINE mp = { } NEW_LINE no = 8 NEW_LINE while ( no < 100 ) : NEW_LINE INDENT no = no + 8 NEW_LINE mp [ ( no // 10 ) % 10 ] = no % 10 NEW_LINE DEDENT visited = [ False ] * 10 NEW_LINE for i in range ( len ( Str ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( Str [ i ] == '8' ) : NEW_LINE INDENT print ( " Yes " , end = " " ) NEW_LINE break NEW_LINE DEDENT if visited [ mp [ ord ( Str [ i ] ) - ord ( '0' ) ] ] : NEW_LINE INDENT print ( " Yes " , end = " " ) NEW_LINE break NEW_LINE DEDENT visited [ ord ( Str [ i ] ) - ord ( '0' ) ] = True NEW_LINE DEDENT if ( i == - 1 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT