text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Maximum possible sum of non | Function to find the maximum sum not exceeding K possible by selecting a subset of non - adjacent elements ; Base Case ; Not selecting current element ; If selecting current element is possible ; Return answer ; Driver Code ; Given array arr [ ] ; Given K ; Function Call
def maxSum ( a , n , k ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT option = maxSum ( a , n - 1 , k ) NEW_LINE if ( k >= a [ n - 1 ] ) : NEW_LINE INDENT option = max ( option , a [ n - 1 ] + maxSum ( a , n - 2 , k - a [ n - 1 ] ) ) NEW_LINE DEDENT return option NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 50 , 10 , 20 , 30 , 40 ] NEW_LINE N = len ( arr ) NEW_LINE K = 100 NEW_LINE print ( maxSum ( arr , N , K ) ) NEW_LINE DEDENT
Count possible binary strings of length N without P consecutive 0 s and Q consecutive 1 s | Function to check if a satisfy the given condition or not ; Stores the length of string ; Stores the previous character of the string ; Stores the count of consecutive equal characters ; Traverse the string ; If current character is equal to the previous character ; If count of consecutive 1 s is more than Q ; If count of consecutive 0 s is more than P ; Reset value of cnt ; If count of consecutive 1 s is more than Q ; If count of consecutive 0 s is more than P ; Function to count all distinct binary strings that satisfy the given condition ; Stores the length of str ; If length of str is N ; If str satisfy the given condition ; If str does not satisfy the given condition ; Append a character '0' at end of str ; Append a character '1' at end of str ; Return total count of binary strings ; Driver Code
def checkStr ( str , P , Q ) : NEW_LINE INDENT N = len ( str ) NEW_LINE prev = str [ 0 ] NEW_LINE cnt = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( str [ i ] == prev ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( prev == '1' and cnt >= Q ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( prev == '0' and cnt >= P ) : NEW_LINE INDENT return False NEW_LINE DEDENT cnt = 1 NEW_LINE DEDENT prev = str [ i ] NEW_LINE DEDENT if ( prev == '1' and cnt >= Q ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( prev == '0' and cnt >= P ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def cntBinStr ( str , N , P , Q ) : NEW_LINE INDENT lenn = len ( str ) NEW_LINE if ( lenn == N ) : NEW_LINE INDENT if ( checkStr ( str , P , Q ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT X = cntBinStr ( str + '0' , N , P , Q ) NEW_LINE Y = cntBinStr ( str + '1' , N , P , Q ) NEW_LINE return X + Y NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE P = 2 NEW_LINE Q = 3 NEW_LINE print ( cntBinStr ( " " , N , P , Q ) ) NEW_LINE DEDENT
Count possible permutations of given array satisfying the given conditions | Function to get the value of binomial coefficient ; Stores the value of binomial coefficient ; Since C ( N , R ) = C ( N , N - R ) ; Calculate the value of C ( N , R ) ; Function to get the count of permutations of the array that satisfy the condition ; Stores the value of C ( 2 N , N ) ; Stores the value of catalan number ; Return answer ; Driver Code
def binCoff ( N , R ) : NEW_LINE INDENT res = 1 NEW_LINE if ( R > ( N - R ) ) : NEW_LINE INDENT R = ( N - R ) NEW_LINE DEDENT for i in range ( R ) : NEW_LINE INDENT res *= ( N - i ) NEW_LINE res //= ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def cntPermutation ( N ) : NEW_LINE INDENT C_2N_N = binCoff ( 2 * N , N ) NEW_LINE cntPerm = C_2N_N // ( N + 1 ) NEW_LINE return cntPerm NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( cntPermutation ( N // 2 ) ) NEW_LINE DEDENT
Smallest submatrix with Kth maximum XOR | Function to print smallest index of Kth maximum Xor value of submatrices ; Dimensions of matrix ; Stores XOR values for every index ; Min heap to find the kth maximum XOR value ; Stores indices for corresponding XOR values ; Traversing matrix to calculate XOR values ; Insert calculated value in Min Heap ; If size exceeds k ; Remove the minimum ; Store smallest index containing xor [ i , j ] ; Stores the kth maximum element ; Print the required index ; Driver code ; Function call
def smallestPosition ( m , k ) : NEW_LINE INDENT n = len ( m ) NEW_LINE mm = len ( m [ 1 ] ) NEW_LINE xor = [ [ 0 for i in range ( mm ) ] for j in range ( n ) ] NEW_LINE minHeap = [ ] NEW_LINE Map = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( mm ) : NEW_LINE INDENT if i - 1 >= 0 : NEW_LINE INDENT a = xor [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT a = 0 NEW_LINE DEDENT if j - 1 >= 0 : NEW_LINE INDENT b = xor [ i ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT b = 0 NEW_LINE DEDENT if i - 1 >= 0 and j - 1 >= 0 : NEW_LINE INDENT c = xor [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT c = 0 NEW_LINE DEDENT xor [ i ] [ j ] = m [ i ] [ j ] ^ a ^ b ^ c NEW_LINE minHeap . append ( xor [ i ] [ j ] ) NEW_LINE minHeap . sort ( ) NEW_LINE if ( len ( minHeap ) > k ) : NEW_LINE INDENT del minHeap [ 0 ] NEW_LINE DEDENT if xor [ i ] [ j ] not in Map : NEW_LINE INDENT Map [ xor [ i ] [ j ] ] = [ i , j ] NEW_LINE DEDENT DEDENT DEDENT minHeap . sort ( ) NEW_LINE kth_max_e = minHeap [ 0 ] NEW_LINE print ( ( Map [ kth_max_e ] [ 0 ] + 1 ) , ( Map [ kth_max_e ] [ 1 ] + 1 ) ) NEW_LINE DEDENT m = [ [ 1 , 2 , 3 ] , [ 2 , 2 , 1 ] , [ 2 , 4 , 2 ] ] NEW_LINE k = 1 NEW_LINE smallestPosition ( m , k ) NEW_LINE
Length of Longest Palindrome Substring | Function to obtain the length of the longest palindromic substring ; Length of given string ; Stores the maximum length ; Iterate over the string ; Iterate over the string ; Check for palindrome ; If string [ i , j - i + 1 ] is palindromic ; Return length of LPS ; Given string ; Function call
def longestPalSubstr ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE maxLength = 1 NEW_LINE start = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT for j in range ( i , len ( str ) , 1 ) : NEW_LINE INDENT flag = 1 NEW_LINE for k in range ( ( j - i + 1 ) // 2 ) : NEW_LINE INDENT if ( str [ i + k ] != str [ j - k ] ) : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT DEDENT if ( flag != 0 and ( j - i + 1 ) > maxLength ) : NEW_LINE INDENT start = i NEW_LINE maxLength = j - i + 1 NEW_LINE DEDENT DEDENT DEDENT return maxLength NEW_LINE DEDENT str = " forgeeksskeegfor " NEW_LINE print ( longestPalSubstr ( str ) ) NEW_LINE
Maximize cost to empty an array by removing contiguous subarrays of equal elements | Initialize dp array ; Function that removes elements from array to maximize the cost ; Base case ; Check if an answer is stored ; Deleting count + 1 i . e . including the first element and starting a new sequence ; Removing [ left + 1 , i - 1 ] elements to continue with previous sequence ; Store the result ; Return answer ; Function to remove the elements ; Function Call ; Driver Code ; Given array ; Function Call
dp = [ [ [ - 1 for x in range ( 101 ) ] for y in range ( 101 ) ] for z in range ( 101 ) ] NEW_LINE def helper ( arr , left , right , count , m ) : NEW_LINE INDENT if ( left > right ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ left ] [ right ] [ count ] != - 1 ) : NEW_LINE INDENT return dp [ left ] [ right ] [ count ] NEW_LINE DEDENT ans = ( ( count + 1 ) * m + helper ( arr , left + 1 , right , 0 , m ) ) NEW_LINE for i in range ( left + 1 , right + 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ left ] ) : NEW_LINE ans = ( max ( ans , helper ( arr , left + 1 , i - 1 , 0 , m ) + helper ( arr , i , right , count + 1 , m ) ) ) NEW_LINE dp [ left ] [ right ] [ count ] = ans NEW_LINE return ans NEW_LINE DEDENT DEDENT def maxPoints ( arr , n , m ) : NEW_LINE INDENT length = n NEW_LINE global dp NEW_LINE return helper ( arr , 0 , length - 1 , 0 , m ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 2 , 2 , 3 , 4 , 3 , 1 ] NEW_LINE M = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( maxPoints ( arr , N , M ) ) NEW_LINE DEDENT
Minimum cost to convert M to N by repeated addition of its even divisors | Python3 program for the above approach ; Function to find the value of minimum steps to convert m to n ; Base Case ; If n exceeds m ; Iterate through all possible even divisors of m ; If m is divisible by i , then find the minimum cost ; Add the cost to convert m to m + i and recursively call next state ; Return min_cost ; Driver Code ; Function call ; If conversion is not possible ; Print the cost
inf = 1000000008 NEW_LINE def minSteps ( m , n ) : NEW_LINE INDENT if ( n == m ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( m > n ) : NEW_LINE INDENT return inf NEW_LINE DEDENT min_cost = inf NEW_LINE for i in range ( 2 , m , 2 ) : NEW_LINE INDENT if ( m % i == 0 ) : NEW_LINE INDENT min_cost = min ( min_cost , m / i + minSteps ( m + i , n ) ) NEW_LINE DEDENT DEDENT return min_cost NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = 6 NEW_LINE N = 24 NEW_LINE minimum_cost = minSteps ( M , N ) NEW_LINE if minimum_cost == inf : NEW_LINE INDENT minimum_cost = - 1 NEW_LINE DEDENT print ( minimum_cost ) NEW_LINE DEDENT
Represent a number as the sum of positive numbers ending with 9 | Function to find the minimum count of numbers ending with 9 to form N ; Extract last digit of N ; Calculate the last digit ; If the last digit satisfies the condition ; Driver Code
def minCountOfNumbers ( N ) : NEW_LINE INDENT k = N % 10 NEW_LINE z = N - ( 9 * ( 9 - k ) ) NEW_LINE if ( z >= 9 and z % 10 == 9 ) : NEW_LINE INDENT return 10 - k NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 156 NEW_LINE print ( minCountOfNumbers ( N ) ) NEW_LINE DEDENT
Binary Matrix after flipping submatrices in given range for Q queries | Function to flip a submatrices ; Boundaries of the submatrix ; Iterate over the submatrix ; Check for 1 or 0 and flip accordingly ; Function to perform the queries ; Driver Code ; Function call
def manipulation ( matrix , q ) : NEW_LINE INDENT x1 , y1 , x2 , y2 = q NEW_LINE for i in range ( x1 - 1 , x2 ) : NEW_LINE INDENT for j in range ( y1 - 1 , y2 ) : NEW_LINE INDENT if matrix [ i ] [ j ] : NEW_LINE INDENT matrix [ i ] [ j ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT matrix [ i ] [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def queries_fxn ( matrix , queries ) : NEW_LINE INDENT for q in queries : NEW_LINE INDENT manipulation ( matrix , q ) NEW_LINE DEDENT DEDENT matrix = [ [ 0 , 1 , 0 ] , [ 1 , 1 , 0 ] ] NEW_LINE queries = [ [ 1 , 1 , 2 , 3 ] , [ 1 , 1 , 1 , 1 ] , [ 1 , 2 , 2 , 3 ] ] NEW_LINE queries_fxn ( matrix , queries ) NEW_LINE print ( matrix ) NEW_LINE
Minimum repeated addition of even divisors of N required to convert N to M | INF is the maximum value which indicates Impossible state ; Recursive Function that considers all possible even divisors of cur ; Indicates impossible state ; Return 0 if cur == M ; Initially it is set to INF that means we can 't transform cur to M ; Loop to find even divisors of cur ; If i is divisor of cur ; If i is even ; Finding divisors recursively for cur + i ; Check another divisor ; Find recursively for cur + ( cur / i ) ; Return the answer ; Function that finds the minimum operation to reduce N to M ; INF indicates impossible state ; Driver Code ; Given N and M ; Function call
INF = int ( 1e7 ) ; NEW_LINE def min_op ( cur , M ) : NEW_LINE INDENT if ( cur > M ) : NEW_LINE INDENT return INF ; NEW_LINE DEDENT if ( cur == M ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT op = int ( INF ) ; NEW_LINE for i in range ( 2 , int ( cur ** 1 / 2 ) + 1 ) : NEW_LINE INDENT if ( cur % i == 0 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT op = min ( op , 1 + min_op ( cur + i , M ) ) ; NEW_LINE DEDENT if ( ( cur / i ) != i and ( cur / i ) % 2 == 0 ) : NEW_LINE INDENT op = min ( op , 1 + min_op ( cur + ( cur // i ) , M ) ) ; NEW_LINE DEDENT DEDENT DEDENT return op ; NEW_LINE DEDENT def min_operations ( N , M ) : NEW_LINE INDENT op = min_op ( N , M ) ; NEW_LINE if ( op >= INF ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( op ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 ; NEW_LINE M = 24 ; NEW_LINE min_operations ( N , M ) ; NEW_LINE DEDENT
Minimum length of subsequence having unit GCD | Function that finds the prime factors of a number ; To store the prime factor ; 2 s that divide n ; N must be odd at this point Skip one element ; Update the prime factor ; If n is a prime number greater than 2 ; Function that finds the shortest subsequence ; Check if the prime factor of first number , is also the prime factor of the rest numbers in array ; Set corresponding bit of prime factor to 1 , it means both these numbers have the same prime factor ; If no states encountered so far continue for this combination of bits ; Update this state with minimum ways to reach this state ; Function that print the minimum length of subsequence ; Find the prime factors of the first number ; Initialize the array with maximum steps , size of the array + 1 for instance ; Total number of set bits is equal to the total number of prime factors ; Indicates there is one way to reach the number under consideration ; State 0 corresponds to gcd of 1 ; If not found such subsequence then print " - 1" ; Else print the length ; Driver Code ; Given array arr [ ] ; Function Call
def findPrimeFactors ( n ) : NEW_LINE INDENT primeFactors = [ 0 for i in range ( 9 ) ] NEW_LINE j = 0 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT primeFactors [ j ] = 2 NEW_LINE j += 1 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n >>= 1 NEW_LINE DEDENT DEDENT i = 3 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT primeFactors [ j ] = i NEW_LINE j += 1 NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n //= i NEW_LINE DEDENT DEDENT i += 2 NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT primeFactors [ j ] = n NEW_LINE j += 1 NEW_LINE DEDENT for i in range ( 0 , j + 1 ) : NEW_LINE INDENT primeFactors [ i ] = 0 NEW_LINE DEDENT return primeFactors NEW_LINE DEDENT def findShortestSubsequence ( dp , a , index , primeFactors ) : NEW_LINE INDENT n = len ( a ) NEW_LINE for j in range ( index , n ) : NEW_LINE INDENT bitmask = 0 NEW_LINE for p in range ( len ( primeFactors ) ) : NEW_LINE INDENT if ( primeFactors [ p ] != 0 and a [ j ] % primeFactors [ p ] == 0 ) : NEW_LINE INDENT bitmask ^= ( 1 << p ) NEW_LINE DEDENT DEDENT for i in range ( len ( dp ) ) : NEW_LINE INDENT if ( dp [ i ] == n + 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT dp [ bitmask & i ] = min ( dp [ bitmask & i ] , dp [ i ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT def printMinimumLength ( a ) : NEW_LINE INDENT mn = len ( a ) + 1 NEW_LINE for i in range ( len ( a ) - 1 ) : NEW_LINE INDENT primeFactors = findPrimeFactors ( a [ i ] ) NEW_LINE n = len ( primeFactors ) NEW_LINE dp = [ 0 for i in range ( 1 << n ) ] NEW_LINE dp = [ len ( a ) + 1 for i in range ( len ( dp ) ) ] NEW_LINE setBits = ( 1 << n ) - 1 NEW_LINE dp [ setBits ] = 1 NEW_LINE findShortestSubsequence ( dp , a , i + 1 , primeFactors ) NEW_LINE mn = min ( dp [ 0 ] , mn ) NEW_LINE DEDENT if ( mn == len ( a ) + 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( mn ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 6 , 12 , 3 ] NEW_LINE printMinimumLength ( arr ) NEW_LINE DEDENT
Maximum sum of Bitwise XOR of all elements of two equal length subsets | Function that finds the maximum Bitwise XOR sum of the two subset ; Check if the current state is already computed ; Initialize answer to minimum value ; Iterate through all possible pairs ; Check whether ith bit and jth bit of mask is not set then pick the pair ; For all possible pairs find maximum value pick current a [ i ] , a [ j ] and set i , j th bits in mask ; Store the maximum value and return the answer ; Driver Code ; Given array arr [ ] ; Declare Initialize the dp states ; Function call
def xorSum ( a , n , mask , dp ) : NEW_LINE INDENT if ( dp [ mask ] != - 1 ) : NEW_LINE INDENT return dp [ mask ] NEW_LINE DEDENT max_value = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( i != j and ( mask & ( 1 << i ) ) == 0 and ( mask & ( 1 << j ) ) == 0 ) : NEW_LINE INDENT max_value = max ( max_value , ( a [ i ] ^ a [ j ] ) + xorSum ( a , n , ( mask | ( 1 << i ) | ( 1 << j ) ) , dp ) ) NEW_LINE DEDENT DEDENT DEDENT dp [ mask ] = max_value NEW_LINE return dp [ mask ] NEW_LINE DEDENT n = 4 NEW_LINE arr = [ 1 , 2 , 3 , 4 ] NEW_LINE dp = [ - 1 ] * ( ( 1 << n ) + 5 ) NEW_LINE print ( xorSum ( arr , n , 0 , dp ) ) NEW_LINE
Count of ways in which N can be represented as sum of Fibonacci numbers without repetition | Python3 program for the above approach ; Function to generate the fibonacci number ; First two number of fibonacci sqequence ; Function to find maximum ways to represent num as the sum of fibonacci number ; Generate the Canonical form of given number ; Reverse the number ; Base condition of dp1 and dp2 ; Iterate from 1 to cnt ; Calculate dp1 [ ] ; Calculate dp2 [ ] ; Return final ans ; Function call to generate the fibonacci numbers ; Given number ; Function call
fib = [ 0 ] * 101 NEW_LINE dp1 = [ 0 ] * 101 NEW_LINE dp2 = [ 0 ] * 101 NEW_LINE v = [ 0 ] * 101 NEW_LINE def fibonacci ( ) : NEW_LINE INDENT fib [ 1 ] = 1 NEW_LINE fib [ 2 ] = 2 NEW_LINE for i in range ( 3 , 87 + 1 ) : NEW_LINE INDENT fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] NEW_LINE DEDENT DEDENT def find ( num ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( 87 , 0 , - 1 ) : NEW_LINE INDENT if ( num >= fib [ i ] ) : NEW_LINE INDENT v [ cnt ] = i NEW_LINE cnt += 1 NEW_LINE num -= fib [ i ] NEW_LINE DEDENT DEDENT v [ : : - 1 ] NEW_LINE dp1 [ 0 ] = 1 NEW_LINE dp2 [ 0 ] = ( v [ 0 ] - 1 ) // 2 NEW_LINE for i in range ( 1 , cnt ) : NEW_LINE INDENT dp1 [ i ] = dp1 [ i - 1 ] + dp2 [ i - 1 ] NEW_LINE dp2 [ i ] = ( ( ( v [ i ] - v [ i - 1 ] ) // 2 ) * dp2 [ i - 1 ] + ( ( v [ i ] - v [ i - 1 ] - 1 ) // 2 ) * dp1 [ i - 1 ] ) NEW_LINE DEDENT return dp1 [ cnt - 1 ] + dp2 [ cnt - 1 ] NEW_LINE DEDENT fibonacci ( ) NEW_LINE num = 13 NEW_LINE print ( find ( num ) ) NEW_LINE
Count of N | Function to find count of N - digit numbers with single digit XOR ; Range of numbers ; Calculate XOR of digits ; If XOR <= 9 , then increment count ; Print the count ; Given number ; Function call
def countNums ( N ) : NEW_LINE INDENT l = pow ( 10 , N - 1 ) NEW_LINE r = pow ( 10 , N ) - 1 NEW_LINE count = 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT xorr = 0 NEW_LINE temp = i NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT xorr = xorr ^ ( temp % 10 ) NEW_LINE temp //= 10 NEW_LINE DEDENT if ( xorr <= 9 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT N = 2 NEW_LINE countNums ( N ) NEW_LINE
Maximize length of Non | Python3 program to implement the above approach ; Function to find the maximum length non decreasing subarray by reversing at most one subarray ; dp [ i ] [ j ] be the longest subsequence of a [ 0. . . i ] with first j parts ; Maximum length sub - sequence of ( 0. . ) ; Maximum length sub - sequence of ( 0. . 1. . ) ; Maximum length sub - sequence of ( 0. . 1. .0 . . ) ; Maximum length sub - sequence of ( 0. . 1. .0 . .1 . . ) ; Find the max length subsequence ; Print the answer ; Driver Code
import sys NEW_LINE def main ( arr , n ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( n ) ] for y in range ( 4 ) ] NEW_LINE if arr [ 0 ] == 0 : NEW_LINE INDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 1 ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW_LINE INDENT dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] == 1 : NEW_LINE INDENT dp [ 1 ] [ i ] = max ( dp [ 1 ] [ i - 1 ] + 1 , dp [ 0 ] [ i - 1 ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 1 ] [ i ] = dp [ 1 ] [ i - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW_LINE INDENT dp [ 2 ] [ i ] = max ( [ dp [ 2 ] [ i - 1 ] + 1 , dp [ 1 ] [ i - 1 ] + 1 , dp [ 0 ] [ i - 1 ] + 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 2 ] [ i ] = dp [ 2 ] [ i - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] == 1 : NEW_LINE INDENT dp [ 3 ] [ i ] = max ( [ dp [ 3 ] [ i - 1 ] + 1 , dp [ 2 ] [ i - 1 ] + 1 , dp [ 1 ] [ i - 1 ] + 1 , dp [ 0 ] [ i - 1 ] + 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 3 ] [ i ] = dp [ 3 ] [ i - 1 ] NEW_LINE DEDENT DEDENT ans = max ( [ dp [ 2 ] [ n - 1 ] , dp [ 1 ] [ n - 1 ] , dp [ 0 ] [ n - 1 ] , dp [ 3 ] [ n - 1 ] ] ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE arr = [ 0 , 1 , 0 , 1 ] NEW_LINE main ( arr , n ) NEW_LINE DEDENT
Print the Maximum Subarray Sum | Function to print the elements of Subarray with maximum sum ; Initialize currMax and globalMax with first value of nums ; Iterate for all the elemensts of the array ; Update currMax ; Check if currMax is greater than globalMax ; Traverse in left direction to find start Index of subarray ; Decrement the start index ; Printing the elements of subarray with max sum ; Given array arr [ ] ; Function call
def SubarrayWithMaxSum ( nums ) : NEW_LINE INDENT currMax = nums [ 0 ] NEW_LINE globalMax = nums [ 0 ] NEW_LINE for i in range ( 1 , len ( nums ) ) : NEW_LINE INDENT currMax = max ( nums [ i ] , nums [ i ] + currMax ) NEW_LINE if ( currMax > globalMax ) : NEW_LINE INDENT globalMax = currMax NEW_LINE endIndex = i NEW_LINE DEDENT DEDENT startIndex = endIndex NEW_LINE while ( startIndex >= 0 ) : NEW_LINE INDENT globalMax -= nums [ startIndex ] NEW_LINE if ( globalMax == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT startIndex -= 1 NEW_LINE DEDENT for i in range ( startIndex , endIndex + 1 ) : NEW_LINE INDENT print ( nums [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ - 2 , - 5 , 6 , - 2 , - 3 , 1 , 5 , - 6 ] NEW_LINE SubarrayWithMaxSum ( arr ) NEW_LINE
Count of distinct Primonacci Numbers in a given range [ L , R ] | Python3 implementation of the above approach ; Stores list of all primes ; Function to find all primes ; To mark the prime ones ; Initially all indices as prime ; If i is prime ; Set all multiples of i as non - prime ; Adding all primes to a list ; Function to return the count of Primonacci Numbers in the range [ l , r ] ; dp [ i ] contains ith Primonacci Number ; Stores the Primonacci Numbers ; Iterate over all smaller primes ; If Primonacci number lies within the range [ L , R ] ; Count of Primonacci Numbers ; Driver Code
M = 100005 NEW_LINE primes = [ ] NEW_LINE def sieve ( ) : NEW_LINE INDENT mark = [ False ] * M NEW_LINE for i in range ( 2 , M ) : NEW_LINE INDENT mark [ i ] = True NEW_LINE DEDENT i = 2 NEW_LINE while i * i < M : NEW_LINE INDENT if ( mark [ i ] ) : NEW_LINE INDENT j = i * i NEW_LINE while j < M : NEW_LINE INDENT mark [ j ] = False NEW_LINE j += i NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT for i in range ( 2 , M ) : NEW_LINE INDENT if ( mark [ i ] ) : NEW_LINE INDENT primes . append ( i ) NEW_LINE DEDENT DEDENT DEDENT def countPrimonacci ( l , r ) : NEW_LINE INDENT dp = [ ] NEW_LINE dp . append ( 1 ) NEW_LINE dp . append ( 1 ) NEW_LINE i = 2 NEW_LINE s = set ( ) NEW_LINE while ( True ) : NEW_LINE INDENT x = 0 NEW_LINE for j in range ( len ( primes ) ) : NEW_LINE INDENT p = primes [ j ] NEW_LINE if ( p >= i ) : NEW_LINE INDENT break NEW_LINE DEDENT x += dp [ i - p ] NEW_LINE DEDENT if ( x >= l and x <= r ) : NEW_LINE INDENT s . add ( x ) NEW_LINE DEDENT if ( x > r ) : NEW_LINE INDENT break NEW_LINE DEDENT dp . append ( x ) NEW_LINE i += 1 NEW_LINE DEDENT print ( len ( s ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT sieve ( ) NEW_LINE L , R = 1 , 10 NEW_LINE countPrimonacci ( L , R ) NEW_LINE DEDENT
Queries to count distinct Binary Strings of all lengths from N to M satisfying given properties | Python3 program to implement the above approach ; Function to calculate the count of possible strings ; Initialize dp [ 0 ] ; dp [ i ] represents count of strings of length i ; Add dp [ i - k ] if i >= k ; Update Prefix Sum Array ; Driver Code
N = int ( 1e5 + 5 ) NEW_LINE MOD = 1000000007 NEW_LINE dp = [ 0 ] * N NEW_LINE def countStrings ( K , Q ) : NEW_LINE INDENT dp [ 0 ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] NEW_LINE if ( i >= K ) : NEW_LINE INDENT dp [ i ] = ( dp [ i ] + dp [ i - K ] ) % MOD NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] = ( dp [ i ] + dp [ i - 1 ] ) % MOD NEW_LINE DEDENT for i in range ( len ( Q ) ) : NEW_LINE INDENT ans = dp [ Q [ i ] [ 1 ] ] - dp [ Q [ i ] [ 0 ] - 1 ] NEW_LINE if ( ans < 0 ) : NEW_LINE INDENT ans += MOD NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT DEDENT K = 3 NEW_LINE Q = [ [ 1 , 4 ] , [ 3 , 7 ] ] NEW_LINE countStrings ( K , Q ) NEW_LINE
Minimum possible sum of prices of a Triplet from the given Array | Python3 program to implement the above approach ; Function to minimize the sum of price by taking a triplet ; Initialize a dp [ ] list ; Stores the final result ; Iterate for all values till N ; Check if num [ j ] > num [ i ] ; Update dp [ j ] if it is greater than stored value ; Update the minimum sum as ans ; If there is no minimum sum exist then print - 1 else print the ans ; Driver code
import sys ; NEW_LINE def minSum ( n , num , price ) : NEW_LINE INDENT dp = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] = sys . maxsize NEW_LINE DEDENT ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( num [ j ] > num [ i ] ) : NEW_LINE INDENT dp [ j ] = min ( dp [ j ] , price [ i ] + price [ j ] ) NEW_LINE ans = min ( ans , dp [ i ] + price [ j ] ) NEW_LINE DEDENT DEDENT DEDENT if ans is not sys . maxsize : NEW_LINE INDENT return ans NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num = [ 2 , 4 , 6 , 7 , 8 ] NEW_LINE price = [ 10 , 20 , 100 , 20 , 40 ] NEW_LINE n = len ( price ) NEW_LINE print ( minSum ( n , num , price ) ) NEW_LINE DEDENT
Count of binary strings of length N having equal count of 0 ' s ▁ and ▁ 1' s and count of 1 ' s ▁ Γ’ ‰ Β₯ ▁ count ▁ of ▁ 0' s in each prefix substring | Function to calculate and returns the value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate the value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Function to return the count of all binary strings having equal count of 0 ' s ▁ and ▁ 1' s and each prefix substring having frequency of 1 ' s ▁ > = ▁ frequencies ▁ of ▁ 0' s ; If N is odd ; No such strings possible ; Otherwise ; 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 countStrings ( N ) : NEW_LINE INDENT if ( N % 2 == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT N //= 2 NEW_LINE c = binomialCoeff ( 2 * N , N ) NEW_LINE return c // ( N + 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE print ( countStrings ( N ) ) NEW_LINE DEDENT
Number of ways to cut a stick of length N into in even length at most K units long pieces | Recursive function to count the total number of ways ; Base case if no - solution exist ; Condition if a solution exist ; Check if already calculated ; Initialize counter ; Recursive call ; Store the answer ; Return the answer ; Driver code
def solve ( n , k , mod , dp ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ n ] != - 1 ) : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( 2 , k + 1 , 2 ) : NEW_LINE INDENT cnt = ( ( cnt % mod + solve ( n - i , k , mod , dp ) % mod ) % mod ) NEW_LINE DEDENT dp [ n ] = cnt NEW_LINE return int ( cnt ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mod = 1e9 + 7 NEW_LINE n = 4 NEW_LINE k = 2 NEW_LINE dp = [ - 1 ] * ( n + 1 ) NEW_LINE ans = solve ( n , k , mod , dp ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Number of ways to select exactly K even numbers from given Array | Python3 program for the above approach ; Function for calculating factorial ; Factorial of n defined as : n ! = n * ( n - 1 ) * ... * 1 ; Function to find the number of ways to select exactly K even numbers from the given array ; Count even numbers ; Check if the current number is even ; Check if the even numbers to be chosen is greater than n . Then , there is no way to pick it . ; The number of ways will be nCk ; Given array arr [ ] ; Given count of even elements ; Function call
f = [ 0 ] * 12 NEW_LINE def fact ( ) : NEW_LINE INDENT f [ 0 ] = f [ 1 ] = 1 NEW_LINE for i in range ( 2 , 11 ) : NEW_LINE INDENT f [ i ] = i * 1 * f [ i - 1 ] NEW_LINE DEDENT DEDENT def solve ( arr , n , k ) : NEW_LINE INDENT fact ( ) NEW_LINE even = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT even += 1 NEW_LINE DEDENT DEDENT if ( k > even ) : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( f [ even ] // ( f [ k ] * f [ even - k ] ) ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 1 NEW_LINE solve ( arr , n , k ) NEW_LINE
Count of binary strings of length N having equal count of 0 ' s ▁ and ▁ 1' s | Python3 program to implement the above approach ; Function to calculate C ( n , r ) % MOD DP based approach ; Corner case ; Stores the last row of Pascal 's Triangle ; Initialize top row of pascal triangle ; Construct Pascal 's Triangle from top to bottom ; Fill current row with the help of previous row ; C ( n , j ) = C ( n - 1 , j ) + C ( n - 1 , j - 1 ) ; Driver Code
MOD = 1000000007 NEW_LINE def nCrModp ( n , r ) : NEW_LINE INDENT if ( n % 2 == 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT C = [ 0 ] * ( r + 1 ) NEW_LINE C [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , r ) , 0 , - 1 ) : NEW_LINE INDENT C [ j ] = ( C [ j ] + C [ j - 1 ] ) % MOD NEW_LINE DEDENT DEDENT return C [ r ] NEW_LINE DEDENT N = 6 NEW_LINE print ( nCrModp ( N , N // 2 ) ) NEW_LINE
Convert 1 into X in min steps by multiplying with 2 or 3 or by adding 1 | Function to print the Minimum number of operations required to convert 1 into X by using three given operations ; Initialize a DP array to store min operations for sub - problems ; Base Condition : No operation required when N is 1 ; Multiply the number by 2 ; Multiply the number by 3 ; Add 1 to the number . ; Print the minimum operations ; Initialize a list to store the sequence ; Backtrack to find the sequence ; If add by 1 ; If multiply by 2 ; If multiply by 3 ; Print the sequence of operation ; Given number X ; Function Call
def printMinOperations ( N ) : NEW_LINE INDENT dp = [ N ] * ( N + 1 ) NEW_LINE dp [ 1 ] = 0 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 and dp [ i ] > dp [ i // 2 ] + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i // 2 ] + 1 NEW_LINE DEDENT if ( i % 3 == 0 and dp [ i ] > dp [ i // 3 ] + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i // 3 ] + 1 NEW_LINE DEDENT if ( dp [ i ] > dp [ i - 1 ] + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + 1 NEW_LINE DEDENT DEDENT print ( dp [ N ] , end = " " ) NEW_LINE seq = [ ] NEW_LINE while ( N > 1 ) : NEW_LINE INDENT seq . append ( N ) NEW_LINE if dp [ N - 1 ] == dp [ N ] - 1 : NEW_LINE INDENT N = N - 1 NEW_LINE DEDENT elif N % 2 == 0 and dp [ N // 2 ] == dp [ N ] - 1 : NEW_LINE INDENT N = N // 2 NEW_LINE DEDENT else : NEW_LINE INDENT N = N // 3 NEW_LINE DEDENT DEDENT seq . append ( 1 ) NEW_LINE for i in reversed ( seq ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT X = 96234 NEW_LINE printMinOperations ( X ) NEW_LINE
Largest subsequence such that all indices and all values are multiples individually | Python3 program for the above approach ; Function that print maximum length of array ; dp [ ] array to store the maximum length ; Find all divisors of i ; If the current value is greater than the divisor 's value ; If current value is greater than the divisor 's value and s is not equal to current index ; Condition if current value is greater than the divisor 's value ; Computing the greatest value ; Printing maximum length of array ; Driver Code ; Given array arr [ ] ; Function call
from math import * NEW_LINE def maxLength ( arr , n ) : NEW_LINE INDENT dp = [ 1 ] * n NEW_LINE for i in range ( n - 1 , 1 , - 1 ) : NEW_LINE INDENT for j in range ( 1 , int ( sqrt ( i ) ) + 1 ) : NEW_LINE INDENT if ( i % j == 0 ) : NEW_LINE INDENT s = i // j NEW_LINE if ( s == j ) : NEW_LINE INDENT if ( arr [ i ] > arr [ s ] ) : NEW_LINE INDENT dp [ s ] = max ( dp [ i ] + 1 , dp [ s ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( s != i and arr [ i ] > arr [ s ] ) : NEW_LINE INDENT dp [ s ] = max ( dp [ i ] + 1 , dp [ s ] ) NEW_LINE DEDENT if ( arr [ i ] > arr [ j ] ) : NEW_LINE INDENT dp [ j ] = max ( dp [ i ] + 1 , dp [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT Max = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( dp [ i ] > Max ) : NEW_LINE INDENT Max = dp [ i ] NEW_LINE DEDENT DEDENT print ( Max ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 1 , 4 , 2 , 3 , 6 , 4 , 9 ] NEW_LINE size = len ( arr ) NEW_LINE maxLength ( arr , size ) NEW_LINE DEDENT
Maximum profit by buying and selling a stock at most twice | Set 2 | Python3 implmenetation to find maximum possible profit with at most two transactions ; Function to find the maximum profit with two transactions on a given list of stock prices ; Set initial buying values to INT_MAX as we want to minimize it ; Set initial selling values to zero as we want to maximize it ; Money lent to buy the stock should be minimum as possible . buy1 tracks the minimum possible stock to buy from 0 to i - 1. ; Profit after selling a stock should be maximum as possible . profit1 tracks maximum possible profit we can make from 0 to i - 1. ; Now for buying the 2 nd stock , we will integrate profit made from selling the 1 st stock ; Profit after selling a 2 stocks should be maximum as possible . profit2 tracks maximum possible profit we can make from 0 to i - 1. ; Driver code
import sys NEW_LINE def maxProfit ( price , n ) : NEW_LINE INDENT buy1 , buy2 = sys . maxsize , sys . maxsize NEW_LINE profit1 , profit2 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT buy1 = min ( buy1 , price [ i ] ) NEW_LINE profit1 = max ( profit1 , price [ i ] - buy1 ) NEW_LINE buy2 = min ( buy2 , price [ i ] - profit1 ) NEW_LINE profit2 = max ( profit2 , price [ i ] - buy2 ) NEW_LINE DEDENT return profit2 NEW_LINE DEDENT price = [ 2 , 30 , 15 , 10 , 8 , 25 , 80 ] NEW_LINE n = len ( price ) NEW_LINE print ( " Maximum ▁ Profit ▁ = ▁ " , maxProfit ( price , n ) ) NEW_LINE
Maximum score of deleting an element from an Array based on given condition | Python3 implementation to find the maximum score of the deleting a element from an array ; Function to find the maximum score of the deleting an element from an array ; Creating a map to keep the frequency of numbers ; Loop to iterate over the elements of the array ; Creating a DP array to keep count of max score at ith element and it will be filled in the bottom Up manner ; Loop to choose the elements of the array to delete from the array ; Driver Code ; Function Call
from collections import defaultdict NEW_LINE def findMaximumScore ( a , n ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ a [ i ] ] += 1 NEW_LINE DEDENT dp = [ 0 ] * ( max ( a ) + 1 ) NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = freq [ 1 ] NEW_LINE for i in range ( 2 , len ( dp ) ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i - 1 ] , dp [ i - 2 ] + freq [ i ] * i ) NEW_LINE DEDENT return dp [ - 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE a = [ 1 , 2 , 3 ] NEW_LINE print ( findMaximumScore ( a , n ) ) NEW_LINE DEDENT
Reverse a subarray to maximize sum of even | Function to return maximized sum at even indices ; Stores difference with element on the left ; Stores difference with element on the right ; Compute and store left difference ; For first index ; If previous difference is positive ; Otherwise ; For the last index ; Otherwise ; For first index ; If the previous difference is positive ; Driver Code
def maximizeSum ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE sum = 0 NEW_LINE for i in range ( 0 , n , 2 ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT leftDP = [ 0 ] * ( n ) NEW_LINE rightDP = [ 0 ] * ( n ) NEW_LINE c = 0 NEW_LINE for i in range ( 1 , n , 2 ) : NEW_LINE INDENT leftDiff = arr [ i ] - arr [ i - 1 ] NEW_LINE if ( c - 1 < 0 ) : NEW_LINE INDENT leftDP [ i ] = leftDiff NEW_LINE DEDENT else : NEW_LINE INDENT if ( leftDP [ i ] > 0 ) : NEW_LINE INDENT leftDP [ i ] = ( leftDiff + leftDP [ i - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT leftDP [ i ] = leftDiff NEW_LINE DEDENT DEDENT rightDiff = 0 NEW_LINE if ( i + 1 >= len ( arr ) ) : NEW_LINE INDENT rightDiff = 0 NEW_LINE DEDENT else : NEW_LINE INDENT rightDiff = arr [ i ] - arr [ i + 1 ] NEW_LINE DEDENT if ( c - 1 < 0 ) : NEW_LINE INDENT rightDP [ i ] = rightDiff NEW_LINE DEDENT else : NEW_LINE INDENT if ( rightDP [ i ] > 0 ) : NEW_LINE INDENT rightDP [ i ] = ( rightDiff + rightDP [ i - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT rightDP [ i ] = rightDiff NEW_LINE DEDENT DEDENT c += 1 NEW_LINE DEDENT maxm = 0 NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT maxm = max ( maxm , max ( leftDP [ i ] , rightDP [ i ] ) ) NEW_LINE DEDENT return maxm + sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 8 , 4 , 5 , 7 , 6 , 8 , 9 , 7 , 3 ] NEW_LINE ans = maximizeSum ( arr ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Count of all subsequences having adjacent elements with different parity | Function to find required subsequences ; Initialise the dp [ ] [ ] with 0. ; If odd element is encountered ; Considering i - th element will be present in the subsequence ; Appending i - th element to all non - empty subsequences ending with even element till ( i - 1 ) th indexes ; Considering ith element will not be present in the subsequence ; Considering i - th element will be present in the subsequence ; Appending i - th element to all non - empty subsequences ending with odd element till ( i - 1 ) th indexes ; Considering ith element will not be present in the subsequence ; Count of all valid subsequences ; Driver code
def validsubsequences ( arr , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] % 2 ) : NEW_LINE INDENT dp [ i ] [ 1 ] += 1 NEW_LINE dp [ i ] [ 1 ] += dp [ i - 1 ] [ 0 ] NEW_LINE dp [ i ] [ 1 ] += dp [ i - 1 ] [ 1 ] NEW_LINE dp [ i ] [ 0 ] += dp [ i - 1 ] [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ 0 ] += 1 NEW_LINE dp [ i ] [ 0 ] += dp [ i - 1 ] [ 1 ] NEW_LINE dp [ i ] [ 0 ] += dp [ i - 1 ] [ 0 ] NEW_LINE dp [ i ] [ 1 ] += dp [ i - 1 ] [ 1 ] NEW_LINE DEDENT DEDENT return dp [ n ] [ 0 ] + dp [ n ] [ 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 6 , 9 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( validsubsequences ( arr , n ) ) NEW_LINE DEDENT
Count of N | Function to return count of N - digit numbers with absolute difference of adjacent digits not exceeding K ; For 1 - digit numbers , the count is 10 ; dp [ i ] [ j ] stores the count of i - digit numbers ending with j ; Initialize count for 1 - digit numbers ; Compute values for count of digits greater than 1 ; Find the range of allowed numbers if last digit is j ; Perform Range update ; Prefix sum to find count of of i - digit numbers ending with j ; Stores the final answer ; Driver Code
def getCount ( n , k ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 10 NEW_LINE DEDENT dp = [ [ 0 for x in range ( 11 ) ] for y in range ( n + 1 ) ] ; NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = 1 NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 0 , 10 ) : NEW_LINE INDENT l = max ( 0 , j - k ) NEW_LINE r = min ( 9 , j + k ) NEW_LINE dp [ i ] [ l ] = dp [ i ] [ l ] + dp [ i - 1 ] [ j ] NEW_LINE dp [ i ] [ r + 1 ] = dp [ i ] [ r + 1 ] - dp [ i - 1 ] [ j ] NEW_LINE DEDENT for j in range ( 1 , 10 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i ] [ j ] + dp [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for i in range ( 0 , 10 ) : NEW_LINE INDENT count = count + dp [ n ] [ i ] NEW_LINE DEDENT return count NEW_LINE DEDENT n , k = 2 , 1 NEW_LINE print ( getCount ( n , k ) ) NEW_LINE
Find if there is a path between two vertices in a directed graph | Set 2 | Python3 program to find if there is a path between two vertices in a directed graph using Dynamic Programming ; Function to find if there is a path between two vertices in a directed graph ; dp matrix ; Set dp [ i ] [ j ] = true if there is edge between i to j ; Check for all intermediate vertex ; If vertex is invalid ; If there is a path ; Driver code
X = 6 NEW_LINE Z = 2 NEW_LINE def existPath ( V , edges , u , v ) : NEW_LINE INDENT mat = [ [ False for i in range ( V ) ] for j in range ( V ) ] NEW_LINE for i in range ( X ) : NEW_LINE INDENT mat [ edges [ i ] [ 0 ] ] [ edges [ i ] [ 1 ] ] = True NEW_LINE DEDENT for k in range ( V ) : NEW_LINE INDENT for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT mat [ i ] [ j ] = ( mat [ i ] [ j ] or mat [ i ] [ k ] and mat [ k ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT if ( u >= V or v >= V ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( mat [ u ] [ v ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT V = 4 NEW_LINE edges = [ [ 0 , 2 ] , [ 0 , 1 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 2 , 0 ] , [ 3 , 3 ] ] NEW_LINE u , v = 1 , 3 NEW_LINE if ( existPath ( V , edges , u , v ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Maximize the numbers of splits in an Array having sum divisible by 3 | Python3 program for above approach ; prefix array storing right most index with prefix sums 0 , 1 , 2 ; dp array ; current prefix sum ; Calculating the prefix sum modulo 3 ; We dont have a left pointer with prefix sum C ; We cannot consider i as a right pointer of any segment ; We have a left pointer pre [ C ] with prefix sum C ; i is the rightmost index of prefix sum C ; Driver code
def calculate_maximum_splits ( arr , N ) : NEW_LINE INDENT pre = [ 0 , - 1 , - 1 ] NEW_LINE dp = [ 0 for i in range ( N ) ] NEW_LINE C = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT C = C + arr [ i ] NEW_LINE C = C % 3 NEW_LINE if pre [ C ] == - 1 : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = max ( dp [ i - 1 ] , dp [ pre [ C ] ] + 1 ) NEW_LINE DEDENT pre [ C ] = i NEW_LINE DEDENT return dp [ N - 1 ] NEW_LINE DEDENT arr = [ 2 , 36 , 1 , 9 , 2 , 0 , 1 , 8 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( calculate_maximum_splits ( arr , N ) ) NEW_LINE
Count of elements having Euler 's Totient value one less than itself | Python3 program for the above approach ; Seiev of Erotosthenes method to compute all primes ; If current number is marked prime then mark its multiple as non - prime ; Function to count the number of element satisfying the condition ; Compute the number of primes in count prime array ; Print the number of elements satisfying the condition ; Given array ; Size of the array ; Function call
prime = [ 0 ] * ( 1000001 ) NEW_LINE def seiveOfEratosthenes ( ) : NEW_LINE INDENT for i in range ( 2 , 1000001 ) : NEW_LINE INDENT prime [ i ] = 1 NEW_LINE DEDENT i = 2 NEW_LINE while ( i * i < 1000001 ) : NEW_LINE INDENT if ( prime [ i ] == 1 ) : NEW_LINE INDENT for j in range ( i * i , 1000001 , i ) : NEW_LINE INDENT prime [ j ] = 0 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def CountElements ( arr , n , L , R ) : NEW_LINE INDENT seiveOfEratosthenes ( ) NEW_LINE countPrime = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT countPrime [ i ] = ( countPrime [ i - 1 ] + prime [ arr [ i - 1 ] ] ) NEW_LINE DEDENT print ( countPrime [ R ] - countPrime [ L - 1 ] ) NEW_LINE return NEW_LINE DEDENT arr = [ 2 , 4 , 5 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE L = 1 NEW_LINE R = 3 NEW_LINE CountElements ( arr , N , L , R ) NEW_LINE
Count of elements having odd number of divisors in index range [ L , R ] for Q queries | Python3 program for the above approach ; Function count the number of elements having odd number of divisors ; Initialise dp [ ] array ; Precomputation ; Find the Prefix Sum ; Iterate for each query ; Find the answer for each query ; Driver code ; Given array arr [ ] ; Given Query ; Function call
import math NEW_LINE def OddDivisorsCount ( n , q , a , Query ) : NEW_LINE INDENT DP = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = int ( math . sqrt ( a [ i ] ) ) ; NEW_LINE if ( x * x == a [ i ] ) : NEW_LINE INDENT DP [ i ] = 1 ; NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT DP [ i ] = DP [ i - 1 ] + DP [ i ] ; NEW_LINE DEDENT l = 0 NEW_LINE r = 0 NEW_LINE for i in range ( q ) : NEW_LINE INDENT l = Query [ i ] [ 0 ] ; NEW_LINE r = Query [ i ] [ 1 ] ; NEW_LINE if ( l == 0 ) : NEW_LINE INDENT print ( DP [ r ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( DP [ r ] - DP [ l - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 ; NEW_LINE Q = 3 ; NEW_LINE arr = [ 2 , 4 , 5 , 6 , 9 ] NEW_LINE Query = [ [ 0 , 2 ] , [ 1 , 3 ] , [ 1 , 4 ] ] NEW_LINE OddDivisorsCount ( N , Q , arr , Query ) ; NEW_LINE DEDENT
Find all possible ways to Split the given string into Primes | Python 3 program to Find all the ways to split the given string into Primes . ; Sieve of Eratosthenes ; Function Convert integer to binary string ; Function print all the all the ways to split the given string into Primes . ; To store all possible strings ; Exponetnital complexity n * ( 2 ^ ( n - 1 ) ) for bit ; Pruning step ; Driver code
primes = [ True ] * 1000001 NEW_LINE maxn = 1000000 NEW_LINE def sieve ( ) : NEW_LINE INDENT primes [ 0 ] = primes [ 1 ] = 0 NEW_LINE i = 2 NEW_LINE while i * i <= maxn : NEW_LINE INDENT if ( primes [ i ] ) : NEW_LINE INDENT for j in range ( i * i , maxn + 1 , i ) : NEW_LINE INDENT primes [ j ] = False NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def toBinary ( n ) : NEW_LINE INDENT r = " " NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE r = "0" + r NEW_LINE else : NEW_LINE r = "1" + r NEW_LINE n //= 2 NEW_LINE DEDENT if ( r == " " ) : NEW_LINE return "0" NEW_LINE return r NEW_LINE DEDENT def PrimeSplit ( st ) : NEW_LINE INDENT cnt = 0 NEW_LINE ans = [ ] NEW_LINE bt = 1 << ( len ( st ) - 1 ) NEW_LINE n = len ( st ) NEW_LINE for i in range ( bt ) : NEW_LINE INDENT temp = toBinary ( i ) + "0" NEW_LINE j = 0 NEW_LINE x = n - len ( temp ) NEW_LINE while ( j < x ) : NEW_LINE INDENT temp = "0" + temp NEW_LINE j += 1 NEW_LINE DEDENT j = 0 NEW_LINE x = 0 NEW_LINE y = - 1 NEW_LINE sp = " " NEW_LINE tp = " " NEW_LINE flag = 0 NEW_LINE while ( j < n ) : NEW_LINE INDENT sp += st [ j ] NEW_LINE if ( temp [ j ] == '1' ) : NEW_LINE INDENT tp += sp + ' , ' NEW_LINE y = int ( sp ) NEW_LINE if ( not primes [ y ] ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT sp = " " NEW_LINE DEDENT j += 1 NEW_LINE DEDENT tp += sp NEW_LINE if ( sp != " " ) : NEW_LINE INDENT y = int ( sp ) NEW_LINE if ( not primes [ y ] ) : NEW_LINE flag = 1 NEW_LINE DEDENT if ( not flag ) : NEW_LINE ans . append ( tp ) NEW_LINE DEDENT if ( len ( ans ) == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT for i in ans : NEW_LINE INDENT print ( i ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "11373" NEW_LINE sieve ( ) NEW_LINE PrimeSplit ( st ) NEW_LINE DEDENT
Count of subsequences of length 4 in form ( x , x , x + 1 , x + 1 ) | Set 2 | Function to count the numbers ; Array that stores the digits from left to right ; Array that stores the digits from right to left ; Initially both array store zero ; Fill the table for count1 array ; Update the count of current character ; Fill the table for count2 array ; Update the count of cuuent character ; Variable that stores the count of the numbers ; Traverse Input string and get the count of digits from count1 and count2 array such that difference b / w digit is 1 & store it int c1 & c2 . And store it in variable c1 and c2 ; Update the ans ; Return the final count ; Given String ; Function call
def countStableNum ( Str , N ) : NEW_LINE INDENT count1 = [ [ 0 for j in range ( 10 ) ] for i in range ( N ) ] NEW_LINE count2 = [ [ 0 for j in range ( 10 ) ] for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT count1 [ i ] [ j ] , count2 [ i ] [ j ] = 0 , 0 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( i != 0 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT count1 [ i ] [ j ] = ( count1 [ i ] [ j ] + count1 [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT count1 [ i ] [ ord ( Str [ i ] ) - ord ( '0' ) ] += 1 NEW_LINE DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( i != N - 1 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT count2 [ i ] [ j ] += count2 [ i + 1 ] [ j ] NEW_LINE DEDENT DEDENT count2 [ i ] [ ord ( Str [ i ] ) - ord ( '0' ) ] = count2 [ i ] [ ord ( Str [ i ] ) - ord ( '0' ) ] + 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 1 , N - 1 ) : NEW_LINE INDENT if ( Str [ i ] == '9' ) : NEW_LINE INDENT continue NEW_LINE DEDENT c1 = count1 [ i - 1 ] [ ord ( Str [ i ] ) - ord ( '0' ) ] NEW_LINE c2 = count2 [ i + 1 ] [ ord ( Str [ i ] ) - ord ( '0' ) + 1 ] NEW_LINE if ( c2 == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT ans = ( ans + ( c1 * ( ( c2 * ( c2 - 1 ) // 2 ) ) ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT Str = "224353" NEW_LINE N = len ( Str ) NEW_LINE print ( countStableNum ( Str , N ) ) NEW_LINE
Maximize occurrences of values between L and R on sequential addition of Array elements with modulo H | Function that prints the number of times X gets a value between L and R ; Base condition ; Condition if X can be made equal to j after i additions ; Compute value of X after adding arr [ i ] ; Compute value of X after adding arr [ i ] - 1 ; Update dp as the maximum value ; Compute maximum answer from all possible cases ; Printing maximum good occurrence of X ; Driver Code
def goodInteger ( arr , n , h , l , r ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( h ) ] for j in range ( n + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( h ) : NEW_LINE INDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT h1 = ( j + arr [ i ] ) % h NEW_LINE h2 = ( j + arr [ i ] - 1 ) % h NEW_LINE dp [ i + 1 ] [ h1 ] = max ( dp [ i + 1 ] [ h1 ] , dp [ i ] [ j ] + ( h1 >= l and h1 <= r ) ) NEW_LINE dp [ i + 1 ] [ h2 ] = max ( dp [ i + 1 ] [ h2 ] , dp [ i ] [ j ] + ( h2 >= l and h2 <= r ) ) NEW_LINE DEDENT DEDENT DEDENT ans = 0 NEW_LINE for i in range ( h ) : NEW_LINE INDENT if ( dp [ n ] [ i ] != - 1 ) : NEW_LINE INDENT ans = max ( ans , dp [ n ] [ i ] ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 16 , 17 , 14 , 20 , 20 , 11 , 22 ] NEW_LINE H = 24 NEW_LINE L = 21 NEW_LINE R = 23 NEW_LINE size = len ( A ) NEW_LINE goodInteger ( A , size , H , L , R ) NEW_LINE DEDENT
Longest subarray whose elements can be made equal by maximum K increments | Function to find maximum possible length of subarray ; Stores the sum of elements that needs to be added to the sub array ; Stores the index of the current position of subarray ; Stores the maximum length of subarray . ; Maximum element from each subarray length ; Previous index of the current subarray of maximum length ; Deque to store the indices of maximum element of each sub array ; For each array element , find the maximum length of required subarray ; Traverse the deque and update the index of maximum element . ; If it is first element then update maximum and dp [ ] ; Else check if current element exceeds max ; Update max and dp [ ] ; Update the index of the current maximum length subarray ; While current element being added to dp [ ] array exceeds K ; Update index of current position and the previous position ; Remove elements from deque and update the maximum element ; Update the maximum length of the required subarray . ; Driver code
def validSubArrLength ( arr , N , K ) : NEW_LINE INDENT dp = [ 0 for i in range ( N + 1 ) ] NEW_LINE pos = 0 NEW_LINE ans = 0 NEW_LINE mx = 0 NEW_LINE pre = 0 NEW_LINE q = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT while ( len ( q ) and arr [ len ( q ) - 1 ] < arr [ i ] ) : NEW_LINE INDENT q . remove ( q [ len ( q ) - 1 ] ) NEW_LINE DEDENT q . append ( i ) NEW_LINE if ( i == 0 ) : NEW_LINE INDENT mx = arr [ i ] NEW_LINE dp [ i ] = arr [ i ] NEW_LINE DEDENT elif ( mx <= arr [ i ] ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + arr [ i ] NEW_LINE mx = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + arr [ i ] NEW_LINE DEDENT if ( pre == 0 ) : NEW_LINE INDENT pos = 0 NEW_LINE DEDENT else : NEW_LINE INDENT pos = pre - 1 NEW_LINE DEDENT while ( ( i - pre + 1 ) * mx - ( dp [ i ] - dp [ pos ] ) > K and pre < i ) : NEW_LINE INDENT pos = pre NEW_LINE pre += 1 NEW_LINE while ( len ( q ) and q [ 0 ] < pre and pre < i ) : NEW_LINE INDENT q . remove ( q [ 0 ] ) NEW_LINE mx = arr [ q [ 0 ] ] NEW_LINE DEDENT DEDENT ans = max ( ans , i - pre + 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE K = 8 NEW_LINE arr = [ 2 , 7 , 1 , 3 , 4 , 5 ] NEW_LINE print ( validSubArrLength ( arr , N , K ) ) NEW_LINE DEDENT
Partition of a set into K subsets with equal sum using BitMask and DP | Function to check whether K required partitions are possible or not ; Return true as the entire array is the answer ; If total number of partitions exceeds size of the array ; If the array sum is not divisible by K ; No such partitions are possible ; Required sum of each subset ; Initialize dp array with - 1 ; Sum of empty subset is zero ; Iterate over all subsets / masks ; If current mask is invalid , continue ; Iterate over all array elements ; Check if the current element can be added to the current subset / mask ; Transition ; Driver Code
def isKPartitionPossible ( arr , N , K ) : NEW_LINE INDENT if ( K == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( N < K ) : NEW_LINE INDENT return False NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum % K != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT target = sum / K NEW_LINE dp = [ 0 for i in range ( 1 << 15 ) ] NEW_LINE for i in range ( ( 1 << N ) ) : NEW_LINE INDENT dp [ i ] = - 1 NEW_LINE DEDENT dp [ 0 ] = 0 NEW_LINE for mask in range ( ( 1 << N ) ) : NEW_LINE INDENT if ( dp [ mask ] == - 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( ( mask & ( 1 << i ) == 0 ) and dp [ mask ] + arr [ i ] <= target ) : NEW_LINE INDENT dp [ mask ( 1 << i ) ] = ( ( dp [ mask ] + arr [ i ] ) % target ) NEW_LINE DEDENT DEDENT DEDENT if ( dp [ ( 1 << N ) - 1 ] == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 4 , 5 , 3 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE if ( isKPartitionPossible ( arr , N , K ) ) : NEW_LINE INDENT print ( " Partitions ▁ into ▁ equal ▁ " \ " sum ▁ is ▁ possible . " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Partitions ▁ into ▁ equal ▁ sum ▁ " \ " is ▁ not ▁ possible . " ) NEW_LINE DEDENT DEDENT
Minimum cost path in a Matrix by moving only on value difference of X | Python3 implementation to find the minimum number of operations required to move from ( 1 , 1 ) to ( N , M ) ; Function to find the minimum operations required to move to bottom - right cell of matrix ; Condition to check if the current cell is the bottom - right cell of the matrix ; Condition to check if the current cell is out of matrix ; Condition to check if the current indices is already computed ; Condition to check that the movement with the current value is not possible ; Recursive call to compute the number of operation required to compute the value ; Function to find the minimum number of operations required to reach the bottom - right cell ; Loop to iterate over every possible cell of the matrix ; Driver Code ; Function Call
MAX = 1e18 NEW_LINE v = [ [ 0 , 0 ] ] * ( 151 ) NEW_LINE dp = [ [ - 1 for i in range ( 151 ) ] for i in range ( 151 ) ] NEW_LINE def min_operation ( i , j , val , x ) : NEW_LINE INDENT if ( i == n - 1 and j == m - 1 ) : NEW_LINE INDENT if ( val > v [ i ] [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = MAX NEW_LINE return MAX NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = v [ i ] [ j ] - val NEW_LINE return dp [ i ] [ j ] NEW_LINE DEDENT DEDENT if ( i == n or j == m ) : NEW_LINE INDENT dp [ i ] [ j ] = MAX NEW_LINE return MAX NEW_LINE DEDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT if ( val > v [ i ] [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = MAX NEW_LINE return MAX NEW_LINE DEDENT tmp = v [ i ] [ j ] - val NEW_LINE tmp += min ( min_operation ( i + 1 , j , val + x , x ) , min_operation ( i , j + 1 , val + x , x ) ) NEW_LINE dp [ i ] [ j ] = tmp NEW_LINE return tmp NEW_LINE DEDENT def solve ( x ) : NEW_LINE INDENT ans = 10 ** 19 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT val = v [ i ] [ j ] - x * ( i + j ) NEW_LINE for ii in range ( 151 ) : NEW_LINE INDENT for jj in range ( 151 ) : NEW_LINE INDENT dp [ ii ] [ jj ] = - 1 NEW_LINE DEDENT DEDENT val = min_operation ( 0 , 0 , val , x ) NEW_LINE ans = min ( ans , val ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 NEW_LINE m = 2 NEW_LINE x = 3 NEW_LINE v [ 0 ] = [ 15 , 153 ] NEW_LINE v [ 1 ] = [ 135 , 17 ] NEW_LINE print ( solve ( x ) ) NEW_LINE DEDENT
Minimum count of numbers required from given array to represent S | Python3 implementation to find the minimum number of sequence required from array such that their sum is equal to given S ; Function to find the minimum elements required to get the sum of given value S ; Condition if the sequence is found ; Condition when no such sequence found ; Calling for without choosing the current index value ; Calling for after choosing the current index value ; Function for every array ; Driver code
import sys NEW_LINE def printAllSubsetsRec ( arr , n , v , Sum ) : NEW_LINE INDENT if ( Sum == 0 ) : NEW_LINE INDENT return len ( v ) NEW_LINE DEDENT if ( Sum < 0 ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT x = printAllSubsetsRec ( arr , n - 1 , v , Sum ) NEW_LINE v . append ( arr [ n - 1 ] ) NEW_LINE y = printAllSubsetsRec ( arr , n , v , Sum - arr [ n - 1 ] ) NEW_LINE v . pop ( len ( v ) - 1 ) NEW_LINE return min ( x , y ) NEW_LINE DEDENT def printAllSubsets ( arr , n , Sum ) : NEW_LINE INDENT v = [ ] NEW_LINE return printAllSubsetsRec ( arr , n , v , Sum ) NEW_LINE DEDENT arr = [ 2 , 1 , 4 , 3 , 5 , 6 ] NEW_LINE Sum = 6 NEW_LINE n = len ( arr ) NEW_LINE print ( printAllSubsets ( arr , n , Sum ) ) NEW_LINE
Minimum count of numbers required from given array to represent S | Function to find the count of minimum length of the sequence ; Loop to initialize the array as infinite in the row 0 ; Loop to find the solution by pre - computation for the sequence ; Minimum possible for the previous minimum value of the sequence ; Driver Code
def Count ( S , m , n ) : NEW_LINE INDENT table = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT table [ 0 ] [ i ] = 10 ** 9 - 1 NEW_LINE DEDENT for i in range ( 1 , m + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( S [ i - 1 ] > j ) : NEW_LINE INDENT table [ i ] [ j ] = table [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT table [ i ] [ j ] = min ( table [ i - 1 ] [ j ] , table [ i ] [ j - S [ i - 1 ] ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT return table [ m ] [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 6 , 5 , 1 ] NEW_LINE m = len ( arr ) NEW_LINE print ( Count ( arr , m , 11 ) ) NEW_LINE DEDENT
Maximize product of same | Python3 implementation to maximize product of same - indexed elements of same size subsequences ; Utility function to find the maximum ; Utility function to find the maximum scalar product from the equal length sub - sequences taken from the two given array ; Return a very small number if index is invalid ; If the sub - problem is already evaluated , then return it ; Take the maximum of all the recursive cases ; Function to find maximum scalar product from same size sub - sequences taken from the two given array ; Initialize a 2 - D array for memoization ; Driver Code
INF = 10000000 NEW_LINE def maximum ( A , B , C , D ) : NEW_LINE INDENT return max ( max ( A , B ) , max ( C , D ) ) NEW_LINE DEDENT def maxProductUtil ( X , Y , A , B , dp ) : NEW_LINE INDENT if ( X < 0 or Y < 0 ) : NEW_LINE INDENT return - INF NEW_LINE DEDENT if ( dp [ X ] [ Y ] != - 1 ) : NEW_LINE INDENT return dp [ X ] [ Y ] NEW_LINE DEDENT dp [ X ] [ Y ] = maximum ( A [ X ] * B [ Y ] + maxProductUtil ( X - 1 , Y - 1 , A , B , dp ) , A [ X ] * B [ Y ] , maxProductUtil ( X - 1 , Y , A , B , dp ) , maxProductUtil ( X , Y - 1 , A , B , dp ) ) NEW_LINE return dp [ X ] [ Y ] NEW_LINE DEDENT def maxProduct ( A , N , B , M ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( m ) ] for i in range ( n ) ] NEW_LINE return maxProductUtil ( N - 1 , M - 1 , A , B , dp ) NEW_LINE DEDENT a = [ - 2 , 6 , - 2 , - 5 ] NEW_LINE b = [ - 3 , 4 , - 2 , 8 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE print ( maxProduct ( a , n , b , m ) ) NEW_LINE
Check if one string can be converted to other using given operation | Function that prints whether is it possible to make a equal to T by performing given operations ; Base case , if we put the last character at front of A ; Base case , if we put the last character at back of A ; Condition if current sequence is matchable ; Condition for front move to ( i - 1 ) th character ; Condition for back move to ( i - 1 ) th character ; Condition if it is possible to make A equal to T ; Print final answer ; Driver Code
def twoStringsEquality ( s , t ) : NEW_LINE INDENT n = len ( s ) NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for i in range ( n ) ] NEW_LINE if ( s [ n - 1 ] == t [ 0 ] ) : NEW_LINE INDENT dp [ n - 1 ] [ 1 ] = 1 NEW_LINE DEDENT if ( s [ n - 1 ] == t [ n - 1 ] ) : NEW_LINE INDENT dp [ n - 1 ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( n - i + 1 ) : NEW_LINE INDENT if ( dp [ i ] [ j ] ) : NEW_LINE INDENT if ( s [ i - 1 ] == t [ j ] ) : NEW_LINE INDENT dp [ i - 1 ] [ j + 1 ] = 1 NEW_LINE DEDENT if ( s [ i - 1 ] == t [ i + j - 1 ] ) : NEW_LINE INDENT dp [ i - 1 ] [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT ans = False NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( dp [ 0 ] [ i ] == 1 ) : NEW_LINE INDENT ans = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( ans == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abab " NEW_LINE T = " baab " NEW_LINE twoStringsEquality ( S , T ) NEW_LINE DEDENT
Maximize sum of all elements which are not a part of the Longest Increasing Subsequence | Function to find maximum sum ; Find total sum of array ; Maintain a 2D array ; Update the dp array along with sum in the second row ; In case of greater length update the length along with sum ; In case of equal length find length update length with minimum sum ; Find the sum that need to be subtracted from total sum ; Return the sum ; Driver code
def findSum ( arr , n ) : NEW_LINE INDENT totalSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT totalSum += arr [ i ] NEW_LINE DEDENT dp = [ [ 0 ] * n for i in range ( 2 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 NEW_LINE dp [ 1 ] [ i ] = arr [ i ] NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] ) : NEW_LINE INDENT if ( dp [ 0 ] [ i ] < dp [ 0 ] [ j ] + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = dp [ 0 ] [ j ] + 1 NEW_LINE dp [ 1 ] [ i ] = dp [ 1 ] [ j ] + arr [ i ] NEW_LINE DEDENT elif ( dp [ 0 ] [ i ] == dp [ 0 ] [ j ] + 1 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = min ( dp [ 1 ] [ i ] , dp [ 1 ] [ j ] + arr [ i ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT maxm = 0 NEW_LINE subtractSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( dp [ 0 ] [ i ] > maxm ) : NEW_LINE INDENT maxm = dp [ 0 ] [ i ] NEW_LINE subtractSum = dp [ 1 ] [ i ] NEW_LINE DEDENT elif ( dp [ 0 ] [ i ] == maxm ) : NEW_LINE INDENT subtractSum = min ( subtractSum , dp [ 1 ] [ i ] ) NEW_LINE DEDENT DEDENT return totalSum - subtractSum NEW_LINE DEDENT arr = [ 4 , 6 , 1 , 2 , 3 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findSum ( arr , n ) ) NEW_LINE
Count of possible permutations of a number represented as a sum of 2 ' s , ▁ 4' s and 6 's only | Returns number of ways to reach score n ; table [ i ] will store count of solutions for value i . ; Initialize all table values as 0 ; Base case ( If given value is 0 , 1 , 2 , or 4 ) ; Driver Code
def count ( n ) : NEW_LINE INDENT if ( n == 2 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( n == 4 ) : NEW_LINE INDENT return 2 ; NEW_LINE DEDENT elif ( n == 6 ) : NEW_LINE INDENT return 4 ; NEW_LINE DEDENT table = [ 0 ] * ( n + 1 ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT table [ i ] = 0 ; NEW_LINE DEDENT table [ 0 ] = 0 ; NEW_LINE table [ 2 ] = 1 ; NEW_LINE table [ 4 ] = 2 ; NEW_LINE table [ 6 ] = 4 ; NEW_LINE for i in range ( 8 , n + 1 , 2 ) : NEW_LINE INDENT table [ i ] = table [ i - 2 ] + table [ i - 4 ] + table [ i - 6 ] ; NEW_LINE DEDENT return table [ n ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 8 ; NEW_LINE print ( count ( n ) ) ; NEW_LINE DEDENT
Count of ways to split a given number into prime segments | Python3 implementation to count total number of ways to split a string to get prime numbers ; Function to check whether a number is a prime number or not ; Function to find the count of ways to split string into prime numbers ; 1 based indexing ; Consider every suffix up to 6 digits ; Number should not have a leading zero and it should be a prime number ; Return the final result ; Driver code
MOD = 1000000007 NEW_LINE def isPrime ( number ) : NEW_LINE INDENT num = int ( number ) NEW_LINE i = 2 NEW_LINE while i * i <= num : NEW_LINE INDENT if ( ( num % i ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if num > 1 : NEW_LINE return True NEW_LINE else : NEW_LINE return False NEW_LINE DEDENT def countPrimeStrings ( number , i ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for j in range ( 1 , 7 ) : NEW_LINE INDENT if ( i - j >= 0 and number [ i - j ] != '0' and isPrime ( number [ i - j : i ] ) ) : NEW_LINE INDENT cnt += countPrimeStrings ( number , i - j ) NEW_LINE cnt %= MOD NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = "3175" NEW_LINE l = len ( s1 ) NEW_LINE print ( countPrimeStrings ( s1 , l ) ) NEW_LINE DEDENT
Count of ways to split a given number into prime segments | Python3 implementation to count total number of ways to split a String to get prime numbers ; Function to build sieve ; If p is a prime ; Update all multiples of p as non prime ; Function to check whether a number is a prime number or not ; Function to find the count of ways to split String into prime numbers ; Number should not have a leading zero and it should be a prime number ; Function to count the number of prime Strings ; Driver code
MOD = 1000000007 NEW_LINE sieve = [ 0 ] * ( 1000000 ) NEW_LINE def buildSieve ( ) : NEW_LINE INDENT for i in range ( len ( sieve ) ) : NEW_LINE INDENT sieve [ i ] = True NEW_LINE DEDENT sieve [ 0 ] = False NEW_LINE sieve [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= 1000000 : NEW_LINE INDENT if sieve [ p ] == True : NEW_LINE INDENT for i in range ( p * p , 1000000 , p ) : NEW_LINE INDENT sieve [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def isPrime ( number ) : NEW_LINE INDENT num = int ( number ) NEW_LINE return sieve [ num ] NEW_LINE DEDENT def rec ( number , i , dp ) : NEW_LINE INDENT if dp [ i ] != - 1 : NEW_LINE INDENT return dp [ i ] NEW_LINE DEDENT cnt = 0 NEW_LINE for j in range ( 1 , 7 ) : NEW_LINE if ( i - j ) >= 0 and number [ i - j ] != '0' and isPrime ( number [ i - j : i ] ) : NEW_LINE INDENT cnt += rec ( number , i - j , dp ) NEW_LINE cnt %= MOD NEW_LINE DEDENT dp [ i ] = cnt NEW_LINE return dp [ i ] NEW_LINE DEDENT def countPrimeStrings ( number ) : NEW_LINE INDENT n = len ( number ) NEW_LINE dp = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] = - 1 NEW_LINE DEDENT dp [ 0 ] = 1 NEW_LINE return rec ( number , n , dp ) NEW_LINE DEDENT buildSieve ( ) NEW_LINE s1 = "3175" NEW_LINE print ( countPrimeStrings ( s1 ) ) NEW_LINE
Check if a matrix contains a square submatrix with 0 as boundary element | Function checks if square with all 0 's in boundary exists in the matrix ; r1 is the top row , c1 is the left col r2 is the bottom row , c2 is the right ; Function checks if the boundary of the square consists of 0 's ; Driver Code
def squareOfZeroes ( ) : NEW_LINE INDENT global matrix , cache NEW_LINE lastIdx = len ( matrix ) - 1 NEW_LINE return hasSquareOfZeroes ( 0 , 0 , lastIdx , lastIdx ) NEW_LINE DEDENT def hasSquareOfZeroes ( r1 , c1 , r2 , c2 ) : NEW_LINE INDENT global matrix , cache NEW_LINE if ( r1 >= r2 or c1 >= c2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT key = ( str ( r1 ) + ' - ' + str ( c1 ) + ' - ' + str ( r2 ) + ' - ' + str ( c2 ) ) NEW_LINE if ( key in cache ) : NEW_LINE INDENT return cache [ key ] NEW_LINE DEDENT cache [ key ] = ( isSquareOfZeroes ( r1 , c1 , r2 , c2 ) or hasSquareOfZeroes ( r1 + 1 , c1 + 1 , r2 - 1 , c2 - 1 ) ) NEW_LINE cache [ key ] = ( cache [ key ] or hasSquareOfZeroes ( r1 , c1 + 1 , r2 - 1 , c2 ) or hasSquareOfZeroes ( r1 + 1 , c1 , r2 , c2 - 1 ) ) NEW_LINE cache [ key ] = ( cache [ key ] or hasSquareOfZeroes ( r1 + 1 , c1 + 1 , r2 , c2 ) or hasSquareOfZeroes ( r1 , c1 , r2 - 1 , c2 - 1 ) ) NEW_LINE return cache [ key ] NEW_LINE DEDENT def isSquareOfZeroes ( r1 , c1 , r2 , c2 ) : NEW_LINE INDENT global matrix NEW_LINE for row in range ( r1 , r2 + 1 ) : NEW_LINE INDENT if ( matrix [ row ] [ c1 ] != 0 or matrix [ row ] [ c2 ] != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for col in range ( c1 , c2 + 1 ) : NEW_LINE INDENT if ( matrix [ r1 ] [ col ] != 0 or matrix [ r2 ] [ col ] != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT cache = { } NEW_LINE matrix = [ [ 1 , 1 , 1 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 1 ] , [ 0 , 1 , 1 , 1 , 0 , 1 ] , [ 0 , 0 , 0 , 1 , 0 , 1 ] , [ 0 , 1 , 1 , 1 , 0 , 1 ] , [ 0 , 0 , 0 , 0 , 0 , 1 ] ] NEW_LINE ans = squareOfZeroes ( ) NEW_LINE if ( ans == 1 ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT DEDENT
Number of ways to obtain each numbers in range [ 1 , b + c ] by adding any two numbers in range [ a , b ] and [ b , c ] | Python3 program to calculate the number of ways ; Initialising the array with zeros . You can do using memset too . ; Printing the array ; Driver code
def CountWays ( a , b , c ) : NEW_LINE INDENT x = b + c + 1 ; NEW_LINE arr = [ 0 ] * x ; NEW_LINE for i in range ( a , b + 1 ) : NEW_LINE INDENT for j in range ( b , c + 1 ) : NEW_LINE INDENT arr [ i + j ] += 1 ; NEW_LINE DEDENT DEDENT for i in range ( 1 , x ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 1 ; NEW_LINE b = 2 ; NEW_LINE c = 2 ; NEW_LINE CountWays ( a , b , c ) ; NEW_LINE DEDENT
Number of ways to obtain each numbers in range [ 1 , b + c ] by adding any two numbers in range [ a , b ] and [ b , c ] | Python3 program to calculate the number of ways ; 2 is added because sometimes we will decrease the value out of bounds . ; Initialising the array with zeros . ; Printing the array ; Driver code
def CountWays ( a , b , c ) : NEW_LINE INDENT x = b + c + 2 ; NEW_LINE arr = [ 0 ] * x ; NEW_LINE for i in range ( 1 , b + 1 ) : NEW_LINE arr [ i + b ] = arr [ i + b ] + 1 ; NEW_LINE arr [ i + c + 1 ] = arr [ i + c + 1 ] - 1 ; NEW_LINE for i in range ( 1 , x - 1 ) : NEW_LINE arr [ i ] += arr [ i - 1 ] ; NEW_LINE print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 1 ; NEW_LINE b = 2 ; NEW_LINE c = 2 ; NEW_LINE CountWays ( a , b , c ) ; NEW_LINE DEDENT
Count of distinct possible strings after performing given operations | Function that prints the number of different strings that can be formed ; Computing the length of the given string ; Base case ; Traverse the given string ; If two consecutive 1 ' s ▁ ▁ or ▁ 2' s are present ; Otherwise take the previous value ; Driver Code
def differentStrings ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = dp [ 1 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] == s [ i - 1 ] and ( s [ i ] == '1' or s [ i ] == '2' ) ) : NEW_LINE INDENT dp [ i + 1 ] = dp [ i ] + dp [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i + 1 ] = dp [ i ] NEW_LINE DEDENT DEDENT print ( dp [ n ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "0111022110" NEW_LINE differentStrings ( S ) NEW_LINE DEDENT
Sum of cost of all paths to reach a given cell in a Matrix | Python3 implementation to find the sum of cost of all paths to reach ( M , N ) ; Function for computing combination ; Function to find the factorial of N ; Loop to find the factorial of a given number ; Function for coumputing the sum of all path cost ; Loop to find the contribution of each ( i , j ) in the all possible ways ; Count number of times ( i , j ) visited ; Add the contribution of grid [ i ] [ j ] in the result ; Driver code ; Function Call
Col = 3 ; NEW_LINE def nCr ( n , r ) : NEW_LINE INDENT return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; NEW_LINE DEDENT def fact ( n ) : NEW_LINE INDENT res = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def sumPathCost ( grid , m , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( 0 , m + 1 ) : NEW_LINE INDENT for j in range ( 0 , n + 1 ) : NEW_LINE INDENT count = ( nCr ( i + j , i ) * nCr ( m + n - i - j , m - i ) ) ; NEW_LINE sum += count * grid [ i ] [ j ] ; NEW_LINE DEDENT DEDENT return sum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 2 ; NEW_LINE n = 2 ; NEW_LINE grid = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; NEW_LINE print ( int ( sumPathCost ( grid , m , n ) ) ) ; NEW_LINE DEDENT
Count numbers in a range with digit sum divisible by K having first and last digit different | Python3 program to count numbers in a range with digit sum divisible by K having first and last digit different ; For calculating the upper bound of the sequence . ; Checking whether the sum of digits = 0 or not and the corner case as number equal to 1 ; If the state is visited then return the answer of this state directly . ; For checking whether digit to be placed is up to upper bound at the position pos or upto 9 ; Calculating new digit sum modulo k ; Check if there is a prefix of 0 s and current digit != 0 ; Then current digit will be the starting digit ; Update the boolean flag that the starting digit has been found ; At n - 1 , check if current digit and starting digit are the same then no need to calculate this answer ; Else find the answer ; Function to find the required count ; Setting up the upper bound ; calculating F ( R ) ; Setting up the upper bound ; Calculating F ( L - 1 ) ; Driver code
K = 0 NEW_LINE N = 0 NEW_LINE v = [ ] NEW_LINE dp = [ [ [ [ [ - 1 for i in range ( 2 ) ] for j in range ( 2 ) ] for k in range ( 10 ) ] for l in range ( 1000 ) ] for m in range ( 20 ) ] NEW_LINE def init ( x ) : NEW_LINE INDENT global K NEW_LINE global N NEW_LINE global v NEW_LINE v = [ ] NEW_LINE while ( x > 0 ) : NEW_LINE INDENT v . append ( x % 10 ) NEW_LINE x //= 10 NEW_LINE DEDENT v = v [ : : - 1 ] NEW_LINE N = len ( v ) NEW_LINE DEDENT def fun ( pos , sum , st , check , f ) : NEW_LINE INDENT global N NEW_LINE global v NEW_LINE if ( pos == N ) : NEW_LINE INDENT return ( sum == 0 and check == 1 ) NEW_LINE DEDENT if ( dp [ pos ] [ sum ] [ st ] [ check ] [ f ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ sum ] [ st ] [ check ] [ f ] NEW_LINE DEDENT lmt = 9 NEW_LINE if ( f == False ) : NEW_LINE INDENT lmt = v [ pos ] NEW_LINE DEDENT ans = 0 NEW_LINE for digit in range ( lmt + 1 ) : NEW_LINE INDENT nf = f NEW_LINE new_sum = ( sum + digit ) % K NEW_LINE new_check = check NEW_LINE new_st = st NEW_LINE if ( f == 0 and digit < lmt ) : NEW_LINE INDENT nf = 1 NEW_LINE DEDENT if ( check == 0 and digit != 0 ) : NEW_LINE INDENT new_st = digit NEW_LINE new_check = 1 NEW_LINE DEDENT if ( pos == N - 1 and new_st == digit ) : NEW_LINE INDENT continue NEW_LINE DEDENT ans += fun ( pos + 1 , new_sum , new_st , new_check , nf ) NEW_LINE dp [ pos ] [ sum ] [ st ] [ check ] [ f ] = ans NEW_LINE DEDENT return ans NEW_LINE DEDENT def findCount ( L , R , K ) : NEW_LINE INDENT init ( R ) NEW_LINE r_ans = fun ( 0 , 0 , 0 , 0 , 0 ) NEW_LINE init ( L - 1 ) NEW_LINE r_ans = 0 NEW_LINE l_ans = fun ( 0 , 0 , 0 , 0 , 0 ) NEW_LINE print ( l_ans - r_ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 10 NEW_LINE R = 20 NEW_LINE K = 2 NEW_LINE findCount ( L , R , K ) NEW_LINE DEDENT
Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1 | Python3 program to split a given String into K segments such that the sum of product of occurence of characters in them is minimized ; Function to return the minimum sum of products of occurences of 0 and 1 in each segments ; Store the length of the String ; Not possible to generate subsets greater than the length of String ; If the number of subsets equals the length ; Precompute the sum of products for all index ; Calculate the minimum sum of products for K subsets ; Driver code
import sys NEW_LINE def minSumProd ( S , K ) : NEW_LINE INDENT Len = len ( S ) ; NEW_LINE if ( K > Len ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( K == Len ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT dp = [ 0 ] * Len ; NEW_LINE count_zero = 0 ; NEW_LINE count_one = 0 ; NEW_LINE for j in range ( 0 , Len , 1 ) : NEW_LINE INDENT if ( S [ j ] == '0' ) : NEW_LINE INDENT count_zero += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT count_one += 1 ; NEW_LINE DEDENT dp [ j ] = count_zero * count_one ; NEW_LINE DEDENT for i in range ( 1 , K ) : NEW_LINE INDENT for j in range ( Len - 1 , i - 1 , - 1 ) : NEW_LINE INDENT count_zero = 0 ; NEW_LINE count_one = 0 ; NEW_LINE dp [ j ] = sys . maxsize ; NEW_LINE for k in range ( j , i - 1 , - 1 ) : NEW_LINE INDENT if ( S [ k ] == '0' ) : NEW_LINE INDENT count_zero += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT count_one += 1 ; NEW_LINE DEDENT dp [ j ] = min ( dp [ j ] , count_zero * count_one + dp [ k - 1 ] ) ; NEW_LINE DEDENT DEDENT DEDENT return dp [ Len - 1 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "1011000110110100" ; NEW_LINE K = 5 ; NEW_LINE print ( minSumProd ( S , K ) ) ; NEW_LINE DEDENT
Minimize prize count required such that smaller value gets less prize in an adjacent pair | Function to find the minimum number of required such that adjacent smaller elements gets less number of prizes ; Loop to compute the smaller elements at the left ; Loop to find the smaller elements at the right ; Loop to find the minimum prizes required ; Driver code
def minPrizes ( arr , n ) : NEW_LINE INDENT dpLeft = [ 0 ] * n NEW_LINE dpLeft [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] > arr [ i - 1 ] : NEW_LINE INDENT dpLeft [ i ] = dpLeft [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dpLeft [ i ] = 1 NEW_LINE DEDENT DEDENT dpRight = [ 0 ] * n NEW_LINE dpRight [ - 1 ] = 1 NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if arr [ i ] > arr [ i + 1 ] : NEW_LINE INDENT dpRight [ i ] = dpRight [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dpRight [ i ] = 1 NEW_LINE DEDENT DEDENT totalPrizes = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT totalPrizes += max ( dpLeft [ i ] , dpRight [ i ] ) NEW_LINE DEDENT print ( totalPrizes ) NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE minPrizes ( arr , n ) NEW_LINE
Maximum sum subsequence with values differing by at least 2 | Python3 program to find maximum sum subsequence with values differing by at least 2 ; Function to find maximum sum subsequence such that two adjacent values elements are not selected ; Map to store the frequency of array elements ; Make a dp array to store answer upto i th value ; Base cases ; Iterate for all possible values of arr [ i ] ; Return the last value ; Driver code
from collections import defaultdict NEW_LINE def get_max_sum ( arr , n ) : NEW_LINE INDENT freq = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT dp = [ 0 ] * 100001 NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = freq [ 0 ] NEW_LINE for i in range ( 2 , 100000 + 1 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i - 1 ] , dp [ i - 2 ] + i * freq [ i ] ) NEW_LINE DEDENT return dp [ 100000 ] NEW_LINE DEDENT N = 3 NEW_LINE arr = [ 2 , 2 , 3 ] NEW_LINE print ( get_max_sum ( arr , N ) ) NEW_LINE
Minimum flips required to keep all 1 s together in a Binary string | Python implementation for Minimum number of flips required in a binary string such that all the 1 aTMs are together ; Length of the binary string ; Initial state of the dp dp [ 0 ] [ 0 ] will be 1 if the current bit is 1 and we have to flip it ; Initial state of the dp dp [ 0 ] [ 1 ] will be 1 if the current bit is 0 and we have to flip it ; dp [ i ] [ 0 ] = Flips required to make all previous bits zero + Flip required to make current bit zero ; dp [ i ] [ 1 ] = minimum flips required to make all previous states 0 or make previous states 1 satisfying the condition ; Minimum of answer and flips required to make all bits 0 ; Driver code
def minFlip ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE dp = [ [ 0 , 0 ] for i in range ( n ) ] NEW_LINE dp [ 0 ] [ 0 ] = int ( a [ 0 ] == '1' ) NEW_LINE dp [ 0 ] [ 1 ] = int ( a [ 0 ] == '0' ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + int ( a [ i ] == '1' ) NEW_LINE dp [ i ] [ 1 ] = min ( dp [ i - 1 ] ) + int ( a [ i ] == '0' ) NEW_LINE DEDENT answer = 10 ** 18 NEW_LINE for i in range ( n ) : NEW_LINE INDENT answer = min ( answer , dp [ i ] [ 1 ] + dp [ n - 1 ] [ 0 ] - dp [ i ] [ 0 ] ) NEW_LINE DEDENT return min ( answer , dp [ n - 1 ] [ 0 ] ) NEW_LINE DEDENT s = "1100111000101" NEW_LINE print ( minFlip ( s ) ) NEW_LINE
Length of longest increasing index dividing subsequence | Function to find the length of the longest increasing sub - sequence such that the index of the element is divisible by index of previous element ; Initialize the dp [ ] array with 1 as a single element will be of 1 length ; Traverse the given array ; If the index is divisible by the previous index ; If increasing subsequence identified ; Longest length is stored ; Driver code
def LIIDS ( arr , N ) : NEW_LINE INDENT dp = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT dp . append ( 1 ) NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT j = i + i NEW_LINE while j <= N : NEW_LINE INDENT if j < N and i < N and arr [ j ] > arr [ i ] : NEW_LINE INDENT dp [ j ] = max ( dp [ j ] , dp [ i ] + 1 ) NEW_LINE DEDENT j += i NEW_LINE DEDENT if i < N : NEW_LINE INDENT ans = max ( ans , dp [ i ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 7 , 9 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE print ( LIIDS ( arr , N ) ) NEW_LINE
Count of subarrays having exactly K perfect square numbers | Python3 program to count of subarrays having exactly K perfect square numbers . ; A utility function to check if the number n is perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; Function to find number of subarrays with sum exactly equal to k ; STL map to store number of subarrays starting from index zero having particular value of sum . ; To store the sum of element traverse so far ; Add current element to currsum ; If currsum = K , then a new subarray is found ; If currsum > K then find the no . of subarrays with sum currsum - K and exclude those subarrays ; Add currsum to count of different values of sum ; Return the final result ; Function to count the subarray with K perfect square numbers ; Update the array element ; If current element is perfect square then update the arr [ i ] to 1 ; Else change arr [ i ] to 0 ; Function Call ; Driver Code ; Function Call
from collections import defaultdict NEW_LINE import math NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sr = math . sqrt ( x ) NEW_LINE return ( ( sr - math . floor ( sr ) ) == 0 ) NEW_LINE DEDENT def findSubarraySum ( arr , n , K ) : NEW_LINE INDENT prevSum = defaultdict ( int ) NEW_LINE res = 0 NEW_LINE currsum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT currsum += arr [ i ] NEW_LINE if ( currsum == K ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT if ( ( currsum - K ) in prevSum ) : NEW_LINE INDENT res += ( prevSum [ currsum - K ] ) NEW_LINE DEDENT prevSum [ currsum ] += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def countSubarray ( arr , n , K ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( isPerfectSquare ( arr [ i ] ) ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT DEDENT print ( findSubarraySum ( arr , n , K ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 9 , 2 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE countSubarray ( arr , N , K ) NEW_LINE DEDENT
Number of ways to split N as sum of K numbers from the given range | Python3 implementation to count the number of ways to divide N in K groups such that each group has elements in range [ L , R ] ; Function to count the number of ways to divide the number N in K groups such that each group has number of elements in range [ L , R ] ; Base Case ; If N is divides completely into less than k groups ; Put all possible values greater equal to prev ; Function to count the number of ways to divide the number N ; Driver Code
mod = 1000000007 NEW_LINE def calculate ( pos , left , k , L , R ) : NEW_LINE INDENT if ( pos == k ) : NEW_LINE INDENT if ( left == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( left == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT answer = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( i > left ) : NEW_LINE INDENT break NEW_LINE DEDENT answer = ( answer + calculate ( pos + 1 , left - i , k , L , R ) ) % mod NEW_LINE DEDENT return answer NEW_LINE DEDENT def countWaystoDivide ( n , k , L , R ) : NEW_LINE INDENT return calculate ( 0 , n , k , L , R ) NEW_LINE DEDENT N = 12 NEW_LINE K = 3 NEW_LINE L = 1 NEW_LINE R = 5 NEW_LINE print ( countWaystoDivide ( N , K , L , R ) ) NEW_LINE
Check if it is possible to get given sum by taking one element from each row | Function that prints whether is it possible to make sum equal to K ; Base case ; Condition if we can make sum equal to current column by using above rows ; Iterate through current column and check whether we can make sum less than or equal to k ; Printing whether is it possible or not ; Driver Code
def PossibleSum ( n , m , v , k ) : NEW_LINE INDENT dp = [ [ 0 ] * ( k + 1 ) for i in range ( n + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( k + 1 ) : NEW_LINE INDENT if dp [ i ] [ j ] == 1 : NEW_LINE INDENT for d in range ( m ) : NEW_LINE INDENT if ( j + v [ i ] [ d ] ) <= k : NEW_LINE INDENT dp [ i + 1 ] [ j + v [ i ] [ d ] ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT if dp [ n ] [ k ] == 1 : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT N = 2 NEW_LINE M = 10 NEW_LINE K = 5 NEW_LINE arr = [ [ 4 , 0 , 15 , 3 , 2 , 20 , 10 , 1 , 5 , 4 ] , [ 4 , 0 , 10 , 3 , 2 , 25 , 4 , 1 , 5 , 4 ] ] NEW_LINE PossibleSum ( N , M , arr , K ) NEW_LINE
Modify array by merging elements with addition such that it consists of only Primes . | DP array to store the ans for max 20 elements ; To check whether the number is prime or not ; Function to check whether the array can be modify so that there are only primes ; If curr is prime and all elements are visited , return true ; If all elements are not visited , set curr = 0 , to search for new prime sum ; If all elements are visited ; If the current sum is not prime return false ; If this state is already calculated , return the answer directly ; Try all state of mask ; If ith index is not set ; Add the current element and set ith index and recur ; If subset can be formed then return true ; After every possibility of mask , if the subset is not formed , return false by memoizing . ; Driver code
dp = [ 0 ] * ( 1 << 20 ) NEW_LINE def isprime ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def solve ( arr , curr , mask , n ) : NEW_LINE INDENT if ( isprime ( curr ) ) : NEW_LINE INDENT if ( mask == ( 1 << n ) - 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT curr = 0 NEW_LINE DEDENT if ( mask == ( 1 << n ) - 1 ) : NEW_LINE INDENT if ( isprime ( curr ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if ( dp [ mask ] != False ) : NEW_LINE INDENT return dp [ mask ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( ( mask & 1 << i ) == False ) : NEW_LINE INDENT if ( solve ( arr , curr + arr [ i ] , mask 1 << i , n ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return ( dp [ mask ] == False ) NEW_LINE DEDENT arr = [ 3 , 6 , 7 , 13 ] NEW_LINE n = len ( arr ) NEW_LINE if ( solve ( arr , 0 , 0 , n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
Maximum sum in circular array such that no two elements are adjacent | Set 2 | Store the maximum possible at each index ; When i exceeds the index of the last element simply return 0 ; If the value has already been calculated , directly return it from the dp array ; The next states are don 't take this element and go to (i + 1)th state else take this element and go to (i + 2)th state ; function to find the max value ; subarr contains elements from 0 to arr . size ( ) - 2 ; Initializing all the values with - 1 ; Calculating maximum possible sum for first case ; subarr contains elements from 1 to arr . size ( ) - 1 ; Re - initializing all values with - 1 ; Calculating maximum possible sum for second case ; Printing the maximum between them ; Driver code
dp = [ ] NEW_LINE def maxSum ( i , subarr ) : NEW_LINE INDENT if ( i >= len ( subarr ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] != - 1 ) : NEW_LINE INDENT return dp [ i ] NEW_LINE DEDENT dp [ i ] = max ( maxSum ( i + 1 , subarr ) , subarr [ i ] + maxSum ( i + 2 , subarr ) ) NEW_LINE return dp [ i ] NEW_LINE DEDENT def Func ( arr ) : NEW_LINE INDENT subarr = arr NEW_LINE subarr . pop ( ) NEW_LINE global dp NEW_LINE dp = [ - 1 ] * ( len ( subarr ) ) NEW_LINE max1 = maxSum ( 0 , subarr ) NEW_LINE subarr = arr NEW_LINE subarr = subarr [ : ] NEW_LINE del dp NEW_LINE dp = [ - 1 ] * ( len ( subarr ) ) NEW_LINE max2 = maxSum ( 0 , subarr ) NEW_LINE print ( max ( max1 , max2 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 1 ] NEW_LINE Func ( arr ) NEW_LINE DEDENT
Count all square sub | Python3 program to count total number of k x k sub matrix whose sum is greater than the given number S ; Function to create prefix sum matrix from the given matrix ; Store first value in table ; Initialize first row of matrix ; Initialize first column of matrix ; Initialize rest table with sum ; Utility function to count the submatrix whose sum is greater than the S ; Loop to iterate over all the possible positions of the given matrix mat [ ] [ ] ; Condition to check , if K x K is first sub matrix ; Condition to check sub - matrix has no margin at top ; Condition when sub matrix has no margin at left ; Condition when submatrix has margin at top and left ; Increment count , If sub matrix sum is greater than S ; Function to count submatrix of size k x k such that sum if greater than or equal to S ; For loop to initialize prefix sum matrix with zero , initially ; Function to create the prefix sum matrix ; Driver Code ; Print total number of sub matrix
dim = 5 NEW_LINE def createTable ( mtrx , k , p , dp ) : NEW_LINE INDENT dp [ 0 ] [ 0 ] = mtrx [ 0 ] [ 0 ] NEW_LINE for j in range ( 1 , dim ) : NEW_LINE INDENT dp [ 0 ] [ j ] = mtrx [ 0 ] [ j ] + dp [ 0 ] [ j - 1 ] NEW_LINE DEDENT for i in range ( 1 , dim ) : NEW_LINE INDENT dp [ i ] [ 0 ] = mtrx [ i ] [ 0 ] + dp [ i - 1 ] [ 0 ] NEW_LINE DEDENT for i in range ( 1 , dim ) : NEW_LINE INDENT for j in range ( 1 , dim ) : NEW_LINE INDENT dp [ i ] [ j ] = ( mtrx [ i ] [ j ] + dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] - dp [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT def countSubMatrixUtil ( dp , k , p ) : NEW_LINE INDENT count = 0 NEW_LINE subMatSum = 0 NEW_LINE for i in range ( k - 1 , dim ) : NEW_LINE INDENT for j in range ( k - 1 , dim , 1 ) : NEW_LINE INDENT if ( i == ( k - 1 ) or j == ( k - 1 ) ) : NEW_LINE INDENT if ( i == ( k - 1 ) and j == ( k - 1 ) ) : NEW_LINE INDENT subMatSum = dp [ i ] [ j ] NEW_LINE DEDENT elif ( i == ( k - 1 ) ) : NEW_LINE INDENT subMatSum = dp [ i ] [ j ] - dp [ i ] [ j - k ] NEW_LINE DEDENT else : NEW_LINE INDENT subMatSum = dp [ i ] [ j ] - dp [ i - k ] [ j ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT subMatSum = ( dp [ i ] [ j ] - dp [ i - k ] [ j ] - dp [ i ] [ j - k ] + dp [ i - k ] [ j - k ] ) NEW_LINE DEDENT if ( subMatSum >= p ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT def countSubMatrix ( mtrx , k , p ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( dim ) ] for j in range ( dim ) ] NEW_LINE for i in range ( dim ) : NEW_LINE INDENT for j in range ( dim ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT createTable ( mtrx , k , p , dp ) NEW_LINE return countSubMatrixUtil ( dp , k , p ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mtrx = [ [ 1 , 7 , 1 , 1 , 1 ] , [ 2 , 2 , 2 , 2 , 2 ] , [ 3 , 9 , 6 , 7 , 3 ] , [ 4 , 3 , 2 , 4 , 5 ] , [ 5 , 1 , 5 , 3 , 1 ] ] NEW_LINE k = 3 NEW_LINE p = 35 NEW_LINE print ( countSubMatrix ( mtrx , k , p ) ) NEW_LINE DEDENT
Word Break Problem | DP | Unordered_map used for storing the sentences the key string can be broken into ; Unordered_set used to store the dictionary . ; Utility function used for printing the obtained result ; Utility function for appending new words to already existing strings ; Loop to find the append string which can be broken into ; Utility function for word Break ; Condition to check if the subproblem is already computed ; If the whole word is a dictionary word then directly append into the result array for the string ; Loop to iterate over the substring ; If the substring is present into the dictionary then recurse for other substring of the string ; Store the subproblem into the map res is an reference so we need to assign an reference to something if its keep on changing res values changes after it start going through combine method you can check if you had a doubt so here we just clone res ; Master wordBreak function converts the string vector to unordered_set ; Clear the previous stored data ; Driver Code
mp = dict ( ) NEW_LINE dict_t = set ( ) NEW_LINE def printResult ( A ) : NEW_LINE INDENT for i in range ( len ( A ) ) : NEW_LINE INDENT print ( A [ i ] ) NEW_LINE DEDENT DEDENT def combine ( prev , word ) : NEW_LINE INDENT for i in range ( len ( prev ) ) : NEW_LINE INDENT prev [ i ] += " ▁ " + word ; NEW_LINE DEDENT return prev ; NEW_LINE DEDENT def wordBreakUtil ( s ) : NEW_LINE INDENT if ( s in mp ) : NEW_LINE INDENT return mp [ s ] ; NEW_LINE DEDENT res = [ ] NEW_LINE if ( s in dict_t ) : NEW_LINE INDENT res . append ( s ) ; NEW_LINE DEDENT for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT word = s [ i : ] ; NEW_LINE if ( word in dict_t ) : NEW_LINE INDENT rem = s [ : i ] NEW_LINE prev = combine ( wordBreakUtil ( rem ) , word ) ; NEW_LINE for i in prev : NEW_LINE INDENT res . append ( i ) NEW_LINE DEDENT DEDENT DEDENT x = [ ] NEW_LINE for i in res : NEW_LINE x . append ( i ) NEW_LINE mp [ s ] = x ; NEW_LINE return res ; NEW_LINE DEDENT def wordBreak ( s , wordDict ) : NEW_LINE INDENT mp . clear ( ) ; NEW_LINE dict_t . clear ( ) ; NEW_LINE for i in wordDict : NEW_LINE INDENT dict_t . add ( i ) NEW_LINE DEDENT return wordBreakUtil ( s ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT wordDict1 = [ " cat " , " cats " , " and " , " sand " , " dog " ] NEW_LINE printResult ( wordBreak ( " catsanddog " , wordDict1 ) ) ; NEW_LINE DEDENT
Maximize product of digit sum of consecutive pairs in a subsequence of length K | Python3 implementation to find the maximum product of the digit sum of the consecutive pairs of the subsequence of the length K ; Function to find the product of two numbers digit sum in the pair ; Loop to find the digits of the number ; Loop to find the digits of other number ; Function to find the subsequence of the length K ; Base case ; Condition when we didn 't reach the length K, but ran out of elements of the array ; Condition if already calculated ; If length upto this point is odd ; If length is odd , it means we need second element of this current pair , calculate the product of digit sum of current and previous element and recur by moving towards next index ; If length upto this point is even ; Exclude this current element and recur for next elements . ; Return by memoizing it , by selecting the maximum among two choices . ; Driver code
import sys NEW_LINE MAX = 100 NEW_LINE dp = [ ] NEW_LINE for i in range ( 1000 ) : NEW_LINE INDENT temp1 = [ ] NEW_LINE for j in range ( MAX ) : NEW_LINE INDENT temp2 = [ ] NEW_LINE for k in range ( MAX ) : NEW_LINE INDENT temp2 . append ( 0 ) NEW_LINE DEDENT temp1 . append ( temp2 ) NEW_LINE DEDENT dp . append ( temp1 ) NEW_LINE DEDENT def productDigitSum ( x , y ) : NEW_LINE INDENT sumx = 0 NEW_LINE while x : NEW_LINE INDENT sumx += x % 10 NEW_LINE x = x // 10 NEW_LINE DEDENT sumy = 0 NEW_LINE while y : NEW_LINE INDENT sumy += y % 10 NEW_LINE y = y // 10 NEW_LINE DEDENT return sumx * sumy NEW_LINE DEDENT def solve ( arr , i , len , prev , n , k ) : NEW_LINE INDENT if len == k : NEW_LINE INDENT return 0 NEW_LINE DEDENT if i == n : NEW_LINE INDENT return - sys . maxsize - 1 NEW_LINE DEDENT if dp [ i ] [ len ] [ prev ] : NEW_LINE INDENT return dp [ i ] [ len ] [ prev ] NEW_LINE DEDENT if len & 1 : NEW_LINE INDENT inc = ( productDigitSum ( arr [ prev ] , arr [ i ] ) + solve ( arr , i + 1 , len + 1 , i , n , k ) ) NEW_LINE DEDENT else : NEW_LINE INDENT inc = solve ( arr , i + 1 , len + 1 , i , n , k ) NEW_LINE DEDENT exc = solve ( arr , i + 1 , len , prev , n , k ) NEW_LINE dp [ i ] [ len ] [ prev ] = max ( inc , exc ) NEW_LINE return dp [ i ] [ len ] [ prev ] NEW_LINE DEDENT arr = [ 10 , 5 , 9 , 101 , 24 , 2 , 20 , 14 ] NEW_LINE n = len ( arr ) NEW_LINE k = 6 NEW_LINE print ( solve ( arr , 0 , 0 , 0 , n , k ) ) NEW_LINE
Count minimum factor jumps required to reach the end of an Array | vector to store factors of each integer ; dp array ; Precomputing all factors of integers from 1 to 100000 ; Function to count the minimum jumps ; If we reach the end of array , no more jumps are required ; If the jump results in out of index , return INT_MAX ; If the answer has been already computed , return it directly ; Else compute the answer using the recurrence relation ; Iterating over all choices of jumps ; Considering current factor as a jump ; Jump leads to the destination ; Return ans and memorize it ; Driver code ; pre - calculating the factors
factors = [ [ ] for i in range ( 100005 ) ] ; NEW_LINE dp = [ 0 for i in range ( 100005 ) ] ; NEW_LINE def precompute ( ) : NEW_LINE INDENT for i in range ( 1 , 100001 ) : NEW_LINE INDENT for j in range ( i , 100001 , i ) : NEW_LINE INDENT factors [ j ] . append ( i ) ; NEW_LINE DEDENT DEDENT DEDENT def solve ( arr , k , n ) : NEW_LINE INDENT if ( k == n - 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( k >= n ) : NEW_LINE INDENT return 1000000000 NEW_LINE DEDENT if ( dp [ k ] ) : NEW_LINE INDENT return dp [ k ] ; NEW_LINE DEDENT ans = 1000000000 NEW_LINE for j in factors [ arr [ k ] ] : NEW_LINE INDENT res = solve ( arr , k + j , n ) ; NEW_LINE if ( res != 1000000000 ) : NEW_LINE INDENT ans = min ( ans , res + 1 ) ; NEW_LINE DEDENT DEDENT dp [ k ] = ans ; NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT precompute ( ) NEW_LINE arr = [ 2 , 8 , 16 , 55 , 99 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE print ( solve ( arr , 0 , n ) ) NEW_LINE DEDENT
Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | Python3 program to find the maximum distance from a 0 - cell to a 1 - cell ; If the matrix consists of only 0 ' s ▁ ▁ or ▁ only ▁ 1' s ; If it 's a 0-cell ; Calculate its distance with every 1 - cell ; Compare and store the minimum ; Compare ans store the maximum ; Driver code
def maxDistance ( grid ) : NEW_LINE INDENT one = [ ] NEW_LINE M = len ( grid ) NEW_LINE N = len ( grid [ 0 ] ) NEW_LINE ans = - 1 NEW_LINE for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE if ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT one . append ( [ i , j ] ) NEW_LINE DEDENT DEDENT if ( one == [ ] or M * N == len ( one ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE if ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT dist = float ( ' inf ' ) NEW_LINE for p in one : NEW_LINE INDENT d = abs ( p [ 0 ] - i ) + abs ( p [ 1 ] - j ) NEW_LINE dist = min ( dist , d ) NEW_LINE if ( dist <= ans ) : NEW_LINE break NEW_LINE ans = max ( ans , dist ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ [ 0 , 0 , 1 ] , [ 0 , 0 , 0 ] , [ 0 , 0 , 0 ] ] NEW_LINE print ( maxDistance ( arr ) ) NEW_LINE
Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | Function to find the maximum distance ; Queue to store all 1 - cells ; Grid dimensions ; Directions traversable from a given a particular cell ; If the grid contains only 0 s or only 1 s ; Access every 1 - cell ; Traverse all possible directions from the cells ; Check if the cell is within the boundaries or contains a 1 ; Driver code
def maxDistance ( grid ) : NEW_LINE INDENT q = [ ] NEW_LINE M = len ( grid ) NEW_LINE N = len ( grid [ 0 ] ) NEW_LINE ans = - 1 NEW_LINE dirs = [ [ 0 , 1 ] , [ 1 , 0 ] , [ 0 , - 1 ] , [ - 1 , 0 ] ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT q . append ( [ i , j ] ) NEW_LINE DEDENT DEDENT DEDENT if ( len ( q ) == 0 or M * N == len ( q ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT while ( len ( q ) > 0 ) : NEW_LINE INDENT cnt = len ( q ) NEW_LINE while ( cnt > 0 ) : NEW_LINE INDENT p = q [ 0 ] NEW_LINE q . pop ( ) NEW_LINE for Dir in dirs : NEW_LINE INDENT x = p [ 0 ] + Dir [ 0 ] NEW_LINE y = p [ 1 ] + Dir [ 1 ] NEW_LINE if ( x < 0 or x >= M or y < 0 or y >= N or grid [ x ] [ y ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT q . append ( [ x , y ] ) NEW_LINE grid [ x ] [ y ] = 1 NEW_LINE DEDENT cnt -= 1 NEW_LINE DEDENT ans += 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ [ 0 , 0 , 1 ] , [ 0 , 0 , 0 ] , [ 0 , 0 , 1 ] ] NEW_LINE print ( maxDistance ( arr ) ) NEW_LINE
Count the number of ways to give ranks for N students such that same ranks are possible | Python3 program to calculate the number of ways to give ranks for N students such that same ranks are possible ; Initializing a table in order to store the bell triangle ; Function to calculate the K - th bell number ; If we have already calculated the bell numbers until the required N ; Base case ; First Bell Number ; If the value of the bell triangle has already been calculated ; Fill the defined dp table ; Function to return the number of ways to give ranks for N students such that same ranks are possible ; Resizing the dp table for the given value of n ; Variables to store the answer and the factorial value ; Iterating till N ; Simultaneously calculate the k ! ; Computing the K - th bell number and multiplying it with K ! ; Driver code
mod = 1e9 + 7 NEW_LINE dp = [ [ - 1 for x in range ( 6 ) ] for y in range ( 6 ) ] NEW_LINE def f ( n , k ) : NEW_LINE INDENT if ( n < k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( k == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ n ] [ k ] != - 1 ) : NEW_LINE INDENT return dp [ n ] [ k ] NEW_LINE DEDENT dp [ n ] [ k ] = ( ( ( ( k * f ( n - 1 , k ) ) % mod + ( f ( n - 1 , k - 1 ) ) % mod ) % mod ) ) NEW_LINE return dp [ n ] [ k ] NEW_LINE DEDENT def operation ( n ) : NEW_LINE INDENT global dp NEW_LINE ans = 0 NEW_LINE fac = 1 NEW_LINE for k in range ( 1 , n + 1 ) : NEW_LINE INDENT fac *= k NEW_LINE ans = ( ans + ( fac * f ( n , k ) ) % mod ) % mod NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE print ( int ( operation ( n ) ) ) NEW_LINE DEDENT
Print all Longest dividing subsequence in an Array | Function to print LDS [ i ] element ; Traverse the Max [ ] ; Function to construct and print Longest Dividing Subsequence ; 2D vector for storing sequences ; Push the first element to LDS [ ] [ ] ; Interate over all element ; Loop for every index till i ; If current elements divides arr [ i ] and length is greater than the previous index , then insert the current element to the sequences LDS [ i ] ; L [ i ] ends with arr [ i ] ; LDS stores the sequences till each element of arr [ ] Traverse the LDS [ ] [ ] to find the maximum length ; Print all LDS with maximum length ; Find size ; If size = maxLength ; Print LDS ; Driver Code ; Function call
def printLDS ( Max ) : NEW_LINE INDENT for it in Max : NEW_LINE INDENT print ( it , end = " ▁ " ) NEW_LINE DEDENT DEDENT def LongestDividingSeq ( arr , N ) : NEW_LINE INDENT LDS = [ [ ] for i in range ( N ) ] NEW_LINE LDS [ 0 ] . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( ( arr [ i ] % arr [ j ] == 0 ) and ( len ( LDS [ i ] ) < len ( LDS [ j ] ) + 1 ) ) : NEW_LINE INDENT LDS [ i ] = LDS [ j ] . copy ( ) NEW_LINE DEDENT DEDENT LDS [ i ] . append ( arr [ i ] ) NEW_LINE DEDENT maxLength = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = len ( LDS [ i ] ) NEW_LINE maxLength = max ( maxLength , x ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT size = len ( LDS [ i ] ) NEW_LINE if ( size == maxLength ) : NEW_LINE INDENT printLDS ( LDS [ i ] ) NEW_LINE print ( ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 2 , 11 , 16 , 12 , 36 , 60 , 71 ] NEW_LINE N = len ( arr ) NEW_LINE LongestDividingSeq ( arr , N ) ; NEW_LINE
Count the number of ordered sets not containing consecutive numbers | Function to calculate the count of ordered set for a given size ; Base cases ; 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
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 answer = ( CountSets ( x - 1 , pos ) + CountSets ( x - 2 , pos - 1 ) ) NEW_LINE return answer NEW_LINE DEDENT def CountOrderedSets ( n ) : NEW_LINE INDENT factorial = [ 1 for i in range ( 10000 ) ] NEW_LINE factorial [ 0 ] = 1 NEW_LINE for i in range ( 1 , 10000 , 1 ) : NEW_LINE INDENT factorial [ i ] = factorial [ i - 1 ] * i NEW_LINE DEDENT answer = 0 NEW_LINE for i in range ( 1 , n + 1 , 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
Maximum sum such that exactly half of the elements are selected and no two adjacent | Python3 program to find maximum sum possible such that exactly floor ( N / 2 ) elements are selected and no two selected elements are adjacent to each other ; Function return the maximum sum possible under given condition ; Intitialising the dp table ; Base case ; Condition to select the current element ; Condition to not select the current element if possible ; Driver code
import sys NEW_LINE def MaximumSum ( a , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = - sys . maxsize - 1 NEW_LINE DEDENT DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 0 NEW_LINE DEDENT for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT for j in range ( 1 , i + 1 , 1 ) : NEW_LINE INDENT val = - sys . maxsize - 1 NEW_LINE if ( ( i - 2 >= 0 and dp [ i - 2 ] [ j - 1 ] != - sys . maxsize - 1 ) or i - 2 < 0 ) : NEW_LINE INDENT if ( i - 2 >= 0 ) : NEW_LINE INDENT val = a [ i - 1 ] + dp [ i - 2 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT val = a [ i - 1 ] NEW_LINE DEDENT DEDENT if ( i - 1 >= j ) : NEW_LINE INDENT val = max ( val , dp [ i - 1 ] [ j ] ) NEW_LINE DEDENT dp [ i ] [ j ] = val NEW_LINE DEDENT DEDENT return dp [ n ] [ n // 2 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE N = len ( A ) NEW_LINE print ( MaximumSum ( A , N ) ) NEW_LINE DEDENT
Check if N can be converted to the form K power K by the given operation | Python3 implementation to Check whether a given number N can be converted to the form K power K by the given operation ; Function to check if N can be converted to K power K ; Check if n is of the form k ^ k ; Iterate through each digit of n ; Check if it is possible to obtain number of given form ; Reduce the number each time ; Return the result ; Function to check the above method ; Check if conversion if possible ; Driver code ; Pre store K power K form of numbers Loop till 8 , because 8 ^ 8 > 10 ^ 7
kPowKform = dict ( ) NEW_LINE def func ( n ) : NEW_LINE INDENT global kPowKform NEW_LINE if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n in kPowKform ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT answer = 0 NEW_LINE x = n NEW_LINE while ( x > 0 ) : NEW_LINE INDENT d = x % 10 NEW_LINE if ( d != 0 ) : NEW_LINE INDENT if ( func ( n - d * d ) ) : NEW_LINE INDENT answer = 1 NEW_LINE break NEW_LINE DEDENT DEDENT x //= 10 NEW_LINE DEDENT return answer NEW_LINE DEDENT def canBeConverted ( n ) : NEW_LINE INDENT if ( func ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 90 NEW_LINE for i in range ( 1 , 9 ) : NEW_LINE INDENT val = 1 NEW_LINE for j in range ( 1 , i + 1 ) : NEW_LINE INDENT val *= i NEW_LINE DEDENT kPowKform [ val ] = 1 NEW_LINE DEDENT canBeConverted ( N ) NEW_LINE DEDENT
Count of subarrays of an Array having all unique digits | Function to check whether the subarray has all unique digits ; Storing all digits occurred ; Traversing all the numbers of v ; Storing all digits of v [ i ] ; Checking whether digits of v [ i ] have already occurred ; Inserting digits of v [ i ] in the set ; Function to count the number subarray with all digits unique ; Traverse through all the subarrays ; To store elements of this subarray ; Generate all subarray and store it in vector ; Check whether this subarray has all digits unique ; Increase the count ; Return the count ; Driver code
def check ( v ) : NEW_LINE INDENT digits = set ( ) NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT d = set ( ) NEW_LINE while ( v [ i ] != 0 ) : NEW_LINE INDENT d . add ( v [ i ] % 10 ) NEW_LINE v [ i ] //= 10 NEW_LINE DEDENT for it in d : NEW_LINE INDENT if it in digits : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for it in d : NEW_LINE INDENT digits . add ( it ) NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def numberOfSubarrays ( a , n ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( 1 , 1 << n ) : NEW_LINE INDENT temp = [ ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( i & ( 1 << j ) ) : NEW_LINE INDENT temp . append ( a [ j ] ) NEW_LINE DEDENT DEDENT if ( check ( temp ) ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE A = [ 1 , 12 , 23 , 34 ] NEW_LINE print ( numberOfSubarrays ( A , N ) ) NEW_LINE DEDENT
Minimum labelled node to be removed from undirected Graph such that there is no cycle | Python3 implementation to find the minimum labelled node to be removed such that there is no cycle in the undirected graph ; Variables to store if a node V has at - most one back edge and store the depth of the node for the edge ; Function to swap the pairs of the graph ; If the second value is greater than x ; Put the pair in the ascending order internally ; Function to perform the DFS ; Initialise with the large value ; Storing the depth of this vertex ; Mark the vertex as visited ; Iterating through the graph ; If the node is a child node ; If the child node is unvisited ; Move to the child and increase the depth ; increase according to algorithm ; If the node is not having exactly K backedges ; If the child is already visited and in current dfs ( because colour is 1 ) then this is a back edge ; Increase the countAdj values ; Colour this vertex 2 as we are exiting out of dfs for this node ; Function to find the minimum labelled node to be removed such that there is no cycle in the undirected graph ; Construct the graph ; Mark visited as false for each node ; Apply dfs on all unmarked nodes ; If no backedges in the initial graph this means that there is no cycle So , return - 1 ; Iterate through the vertices and return the first node that satisfies the condition ; Check whether the count sum of small [ v ] and count is the same as the total back edges and if the vertex v can be removed ; Driver code
MAX = 100005 ; NEW_LINE totBackEdges = 0 NEW_LINE countAdj = [ 0 for i in range ( MAX ) ] NEW_LINE small = [ 0 for i in range ( MAX ) ] NEW_LINE isPossible = [ 0 for i in range ( MAX ) ] NEW_LINE depth = [ 0 for i in range ( MAX ) ] NEW_LINE adj = [ [ ] for i in range ( MAX ) ] NEW_LINE vis = [ 0 for i in range ( MAX ) ] NEW_LINE def change ( p , x ) : NEW_LINE INDENT if ( p [ 1 ] > x ) : NEW_LINE INDENT p [ 1 ] = x ; NEW_LINE DEDENT if ( p [ 0 ] > p [ 1 ] ) : NEW_LINE tmp = p [ 0 ] ; NEW_LINE p [ 0 ] = p [ 1 ] ; NEW_LINE p [ 1 ] = tmp ; NEW_LINE DEDENT def dfs ( v , p = - 1 , de = 0 ) : NEW_LINE INDENT global vis , totBackEdges NEW_LINE answer = [ 100000000 , 100000000 ] NEW_LINE depth [ v ] = de ; NEW_LINE vis [ v ] = 1 ; NEW_LINE isPossible [ v ] = 1 ; NEW_LINE for u in adj [ v ] : NEW_LINE INDENT if ( ( u ^ p ) != 0 ) : NEW_LINE INDENT if ( vis [ u ] == 0 ) : NEW_LINE INDENT x = dfs ( u , v , de + 1 ) ; NEW_LINE small [ v ] += small [ u ] ; NEW_LINE change ( answer , x [ 1 ] ) ; NEW_LINE change ( answer , x [ 0 ] ) ; NEW_LINE if ( x [ 1 ] < de ) : NEW_LINE INDENT isPossible [ v ] = 0 ; NEW_LINE DEDENT DEDENT elif ( vis [ u ] == 1 ) : NEW_LINE INDENT totBackEdges += 1 NEW_LINE countAdj [ v ] += 1 NEW_LINE countAdj [ u ] += 1 NEW_LINE small [ p ] += 1 NEW_LINE small [ u ] -= 1 NEW_LINE change ( answer , depth [ u ] ) ; NEW_LINE DEDENT DEDENT DEDENT vis [ v ] = 2 ; NEW_LINE return answer ; NEW_LINE DEDENT def minNodetoRemove ( n , edges ) : NEW_LINE INDENT for i in range ( len ( edges ) ) : NEW_LINE INDENT adj [ edges [ i ] [ 0 ] ] . append ( edges [ i ] [ 1 ] ) ; NEW_LINE adj [ edges [ i ] [ 1 ] ] . append ( edges [ i ] [ 0 ] ) ; NEW_LINE DEDENT global vis , totBackEdges NEW_LINE vis = [ 0 for i in range ( len ( vis ) ) ] NEW_LINE totBackEdges = 0 ; NEW_LINE for v in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( vis [ v ] == 0 ) : NEW_LINE INDENT dfs ( v ) ; NEW_LINE DEDENT DEDENT if ( totBackEdges == 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT node = - 1 ; NEW_LINE for v in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( ( countAdj [ v ] + small [ v ] == totBackEdges ) and isPossible [ v ] != 0 ) : NEW_LINE INDENT node = v ; NEW_LINE DEDENT if ( node != - 1 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT return node ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE edges = [ ] NEW_LINE edges . append ( [ 5 , 1 ] ) ; NEW_LINE edges . append ( [ 5 , 2 ] ) ; NEW_LINE edges . append ( [ 1 , 2 ] ) ; NEW_LINE edges . append ( [ 2 , 3 ] ) ; NEW_LINE edges . append ( [ 2 , 4 ] ) ; NEW_LINE print ( minNodetoRemove ( N , edges ) ) ; NEW_LINE DEDENT
Find the row whose product has maximum count of prime factors | Python3 implementation to find the row whose product has maximum number of prime factors ; function for SieveOfEratosthenes ; Create a boolean array " isPrime [ 0 . . N ] " and initialize all entries it as true . A value in isPrime [ i ] will finally be false if i is not a prime , else true . ; check if isPrime [ p ] is not changed ; Update all multiples of p ; Print all isPrime numbers ; function to display the answer ; function to Count the row number of divisors in particular row multiplication ; Find count of occurrences of each prime factor ; Compute count of all divisors ; Update row number if factors of this row is max ; Clearing map to store prime factors for next row ; Driver code
N = 3 NEW_LINE M = 5 NEW_LINE Large = int ( 1e6 ) ; NEW_LINE prime = [ ] ; NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT isPrime = [ True ] * ( Large + 1 ) ; NEW_LINE for p in range ( 2 , int ( Large ** ( 1 / 2 ) ) ) : NEW_LINE INDENT if ( isPrime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , Large + 1 , p ) : NEW_LINE INDENT isPrime [ i ] = False ; NEW_LINE DEDENT DEDENT DEDENT for p in range ( 2 , Large + 1 ) : NEW_LINE INDENT if ( isPrime [ p ] ) : NEW_LINE INDENT prime . append ( p ) ; NEW_LINE DEDENT DEDENT DEDENT def Display ( arr , row ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT print ( arr [ row ] [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT def countDivisorsMult ( arr ) : NEW_LINE INDENT mp = { } ; NEW_LINE row_no = 0 ; max_factor = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT no = arr [ i ] [ j ] NEW_LINE for k in range ( len ( prime ) ) : NEW_LINE INDENT while ( no > 1 and no % prime [ k ] == 0 ) : NEW_LINE INDENT no //= prime [ k ] ; NEW_LINE if prime [ k ] not in mp : NEW_LINE INDENT mp [ prime [ k ] ] = 0 NEW_LINE DEDENT mp [ prime [ k ] ] += 1 ; NEW_LINE DEDENT if ( no == 1 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT res = 1 ; NEW_LINE for it in mp : NEW_LINE INDENT res *= mp [ it ] ; NEW_LINE DEDENT if ( max_factor < res ) : NEW_LINE INDENT row_no = i ; NEW_LINE max_factor = res ; NEW_LINE DEDENT mp . clear ( ) ; NEW_LINE DEDENT Display ( arr , row_no ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 2 , 3 , 10 , 23 ] , [ 4 , 5 , 6 , 7 , 8 ] , [ 7 , 8 , 9 , 15 , 45 ] ] ; NEW_LINE SieveOfEratosthenes ( ) ; NEW_LINE countDivisorsMult ( arr ) ; NEW_LINE DEDENT
Smallest N digit number whose sum of square of digits is a Perfect Square | Python3 implementation to find Smallest N digit number whose sum of square of digits is a Perfect Square ; function to check if number is a perfect square ; function to calculate the smallest N digit number ; place digits greater than equal to prev ; check if placing this digit leads to a solution then return it ; else backtrack ; create a representing the N digit number ; Driver code ; initialise N
from math import sqrt NEW_LINE def isSquare ( n ) : NEW_LINE INDENT k = int ( sqrt ( n ) ) NEW_LINE return ( k * k == n ) NEW_LINE DEDENT def calculate ( pos , prev , sum , v ) : NEW_LINE INDENT if ( pos == len ( v ) ) : NEW_LINE INDENT return isSquare ( sum ) NEW_LINE DEDENT for i in range ( prev , 9 + 1 ) : NEW_LINE INDENT v [ pos ] = i NEW_LINE sum += i * i NEW_LINE if ( calculate ( pos + 1 , i , sum , v ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT sum -= i * i NEW_LINE DEDENT return 0 NEW_LINE DEDENT def minValue ( n ) : NEW_LINE INDENT v = [ 0 ] * ( n ) NEW_LINE if ( calculate ( 0 , 1 , 0 , v ) ) : NEW_LINE INDENT answer = " " NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT answer += chr ( v [ i ] + ord ( '0' ) ) NEW_LINE DEDENT return answer NEW_LINE DEDENT else : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE print ( minValue ( N ) ) NEW_LINE DEDENT
Sum of GCD of all possible sequences | Pyhton3 implementation of the above approach ; A recursive function that generates all the sequence and find GCD ; If we reach the sequence of length N g is the GCD of the sequence ; Initialise answer to 0 ; Placing all possible values at this position and recursively find the GCD of the sequence ; Take GCD of GCD calculated uptill now i . e . g with current element ; Take modulo to avoid overflow ; Return the final answer ; Function that finds the sum of GCD of all the subsequence of N length ; Recursive function that generates the sequence and return the GCD ; Driver code ; Function Call
MOD = 1e9 + 7 NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( b , a % b ) NEW_LINE DEDENT DEDENT def calculate ( pos , g , n , k ) : NEW_LINE INDENT if ( pos == n ) : NEW_LINE INDENT return g NEW_LINE DEDENT answer = 0 NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT answer = ( answer % MOD + calculate ( pos + 1 , gcd ( g , i ) , n , k ) % MOD ) NEW_LINE answer %= MOD NEW_LINE DEDENT return answer NEW_LINE DEDENT def sumofGCD ( n , k ) : NEW_LINE INDENT return calculate ( 0 , 0 , n , k ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE K = 2 NEW_LINE print ( sumofGCD ( N , K ) ) NEW_LINE DEDENT
Sum of GCD of all possible sequences | Python3 implementation of the above approach ; Function to find a ^ b in log ( b ) ; Function that finds the sum of GCD of all the subsequence of N length ; To stores the number of sequences with gcd i ; Find contribution of each gcd to happen ; To count multiples ; possible sequences with overcounting ; to avoid overflow ; Find extra element which will not form gcd = i ; Find overcounting ; Remove the overcounting ; To store the final answer ; Return Final answer ; Driver code ; Function call
MOD = ( int ) ( 1e9 + 7 ) NEW_LINE def fastexpo ( a , b ) : NEW_LINE INDENT res = 1 NEW_LINE a = a % MOD NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( ( b & 1 ) != 0 ) : NEW_LINE INDENT res = ( res * a ) % MOD NEW_LINE DEDENT a = a * a NEW_LINE a = a % MOD NEW_LINE b = b >> 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def sumofGCD ( n , k ) : NEW_LINE INDENT count = [ 0 ] * ( k + 1 ) NEW_LINE for g in range ( k , 0 , - 1 ) : NEW_LINE INDENT count_multiples = k // g NEW_LINE temp = fastexpo ( count_multiples , n ) NEW_LINE temp = temp % MOD NEW_LINE extra = 0 NEW_LINE for j in range ( g * 2 , k + 1 , g ) : NEW_LINE INDENT extra = extra + count [ j ] NEW_LINE extra = extra % MOD NEW_LINE DEDENT count [ g ] = temp - extra + MOD NEW_LINE count [ g ] = count [ g ] % MOD NEW_LINE DEDENT Sum = 0 NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT add = count [ i ] % MOD * i % MOD NEW_LINE add = add % MOD NEW_LINE Sum = Sum + add NEW_LINE Sum = Sum % MOD NEW_LINE DEDENT return Sum NEW_LINE DEDENT N , K = 3 , 2 NEW_LINE print ( sumofGCD ( N , K ) ) NEW_LINE
Split the given string into Odds : Digit DP | Function to check whether a string is an odd number or not ; A function to find the minimum number of segments the given string can be divided such that every segment is a odd number ; Declare a splitdp [ ] array and initialize to - 1 ; Build the DP table in a bottom - up manner ; Initially Check if the entire prefix is odd ; If the Given Prefix can be split into Odds then for the remaining string from i to j Check if Odd . If yes calculate the minimum split till j ; To check if the substring from i to j is a odd number or not ; If it is an odd number , then update the dp array ; Return the minimum number of splits for the entire string ; Driver code
def checkOdd ( number ) : NEW_LINE INDENT n = len ( number ) NEW_LINE num = ord ( number [ n - 1 ] ) - 48 NEW_LINE return ( num & 1 ) NEW_LINE DEDENT def splitIntoOdds ( number ) : NEW_LINE INDENT numLen = len ( number ) NEW_LINE splitDP = [ - 1 for i in range ( numLen + 1 ) ] NEW_LINE for i in range ( 1 , numLen + 1 ) : NEW_LINE INDENT if ( i <= 9 and checkOdd ( number [ 0 : i ] ) > 0 ) : NEW_LINE INDENT splitDP [ i ] = 1 NEW_LINE DEDENT if ( splitDP [ i ] != - 1 ) : NEW_LINE INDENT for j in range ( 1 , 10 ) : NEW_LINE INDENT if ( i + j > numLen ) : NEW_LINE INDENT break ; NEW_LINE DEDENT if ( checkOdd ( number [ i : i + j ] ) ) : NEW_LINE INDENT if ( splitDP [ i + j ] == - 1 ) : NEW_LINE INDENT splitDP [ i + j ] = 1 + splitDP [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT splitDP [ i + j ] = min ( splitDP [ i + j ] , 1 + splitDP [ i ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return splitDP [ numLen ] NEW_LINE DEDENT print ( splitIntoOdds ( "123456789123456789123" ) ) NEW_LINE
Split the given string into Primes : Digit DP | Function to check whether a string is a prime number or not ; A recursive function to find the minimum number of segments the given string can be divided such that every segment is a prime ; If the number is null ; checkPrime function is called to check if the number is a prime or not . ; A very large number denoting maximum ; Consider a minimum of 6 and length since the primes are less than 10 ^ 6 ; Recursively call the function to check for the remaining string ; Evaluating minimum splits into Primes for the suffix ; Checks if no combination found ; Driver code
def checkPrime ( number ) : NEW_LINE INDENT num = int ( number ) NEW_LINE for i in range ( 2 , int ( num ** 0.5 ) ) : NEW_LINE INDENT if ( ( num % i ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def splitIntoPrimes ( number ) : NEW_LINE INDENT if ( number == ' ' ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( len ( number ) <= 6 and checkPrime ( number ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT numLen = len ( number ) NEW_LINE ans = 1000000 NEW_LINE for i in range ( 1 , ( min ( 6 , numLen ) + 1 ) ) : NEW_LINE INDENT if ( checkPrime ( number [ : i ] ) ) : NEW_LINE INDENT val = splitIntoPrimes ( number [ i : ] ) NEW_LINE if ( val != - 1 ) : NEW_LINE INDENT ans = min ( ans , 1 + val ) NEW_LINE DEDENT DEDENT DEDENT if ( ans == 1000000 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT DEDENT print ( splitIntoPrimes ( "13499315" ) ) NEW_LINE print ( splitIntoPrimes ( "43" ) ) NEW_LINE
Find the numbers from 1 to N that contains exactly k non | Function to find number less than N having k non - zero digits ; Store the memorised values ; Initialise ; Base ; Calculate all states For every state , from numbers 1 to N , the count of numbers which contain exactly j non zero digits is being computed and updated in the dp array . ; Return the required answer ; Driver code ; Function call
def k_nonzero_numbers ( s , n , k ) : NEW_LINE INDENT dp = [ [ [ 0 for i in range ( k + 2 ) ] for i in range ( 2 ) ] for i in range ( n + 2 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT for x in range ( k + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] [ x ] = 0 NEW_LINE DEDENT DEDENT DEDENT dp [ 0 ] [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sm = 0 NEW_LINE while ( sm < 2 ) : NEW_LINE INDENT for j in range ( k + 1 ) : NEW_LINE INDENT x = 0 NEW_LINE y = 0 NEW_LINE if sm : NEW_LINE INDENT y = 9 NEW_LINE DEDENT else : NEW_LINE INDENT y = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE DEDENT while ( x <= y ) : NEW_LINE INDENT dp [ i + 1 ] [ ( sm or x < ( ord ( s [ i ] ) - ord ( '0' ) ) ) ] [ j + ( x > 0 ) ] += dp [ i ] [ sm ] [ j ] NEW_LINE x += 1 NEW_LINE DEDENT DEDENT sm += 1 NEW_LINE DEDENT DEDENT return dp [ n ] [ 0 ] [ k ] + dp [ n ] [ 1 ] [ k ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "25" NEW_LINE k = 2 NEW_LINE n = len ( s ) NEW_LINE print ( k_nonzero_numbers ( s , n , k ) ) NEW_LINE DEDENT
Count maximum occurrence of subsequence in string such that indices in subsequence is in A . P . | Function to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Frequencies of subsequence ; Loop to find the frequencies of subsequence of length 1 ; Loop to find the frequencies subsequence of length 2 ; Finding maximum frequency ; Driver Code
def maximumOccurrence ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE freq = { } NEW_LINE for i in s : NEW_LINE INDENT temp = " " NEW_LINE temp += i NEW_LINE freq [ temp ] = freq . get ( temp , 0 ) + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT temp = " " NEW_LINE temp += s [ i ] NEW_LINE temp += s [ j ] NEW_LINE freq [ temp ] = freq . get ( temp , 0 ) + 1 NEW_LINE DEDENT DEDENT answer = - 10 ** 9 NEW_LINE for it in freq : NEW_LINE INDENT answer = max ( answer , freq [ it ] ) NEW_LINE DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " xxxyy " NEW_LINE print ( maximumOccurrence ( s ) ) NEW_LINE DEDENT
Count ways to partition a string such that both parts have equal distinct characters | Function to count the distinct characters in the string ; Frequency of each character ; Loop to count the frequency of each character of the string ; If frequency is greater than 0 then the character occured ; Function to count the number of ways to partition the string such that each partition have same number of distinct character ; Loop to choose the partition index for the string ; Divide in two parts ; Check whether number of distinct characters are equal ; Driver Code
def distinctChars ( s ) : NEW_LINE INDENT freq = [ 0 ] * 26 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT def waysToSplit ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE answer = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT left = s [ 0 : i ] ; NEW_LINE right = s [ i : n ] ; NEW_LINE if ( distinctChars ( left ) == distinctChars ( right ) ) : NEW_LINE INDENT answer += 1 ; NEW_LINE DEDENT DEDENT return answer ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " ababa " ; NEW_LINE print ( waysToSplit ( s ) ) ; NEW_LINE DEDENT
Count ways to partition a string such that both parts have equal distinct characters | Function to count the number of ways to partition the string such that each partition have same number of distinct character ; Prefix and suffix array for distinct character from start and end ; To check whether a character has appeared till ith index ; Calculating prefix array ; Character appears for the first time in string ; Character is visited ; Resetting seen for suffix calculation ; Calculating the suffix array ; Character appears for the first time ; This character has now appeared ; Loop to calculate the number partition points in the string ; Check whether number of distinct characters are equal ; Driver Code
def waysToSplit ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE answer = 0 ; NEW_LINE prefix = [ 0 ] * n ; NEW_LINE suffix = [ 0 ] * n ; NEW_LINE seen = [ 0 ] * 26 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT prev = prefix [ i - 1 ] if ( i - 1 >= 0 ) else 0 ; NEW_LINE if ( seen [ ord ( s [ i ] ) - ord ( ' a ' ) ] == 0 ) : NEW_LINE INDENT prefix [ i ] += ( prev + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT prefix [ i ] = prev ; NEW_LINE DEDENT seen [ ord ( s [ i ] ) - ord ( ' a ' ) ] = 1 ; NEW_LINE DEDENT seen = [ 0 ] * len ( seen ) ; NEW_LINE suffix [ n - 1 ] = 0 ; NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT prev = suffix [ i ] ; NEW_LINE if ( seen [ ord ( s [ i ] ) - ord ( ' a ' ) ] == 0 ) : NEW_LINE INDENT suffix [ i - 1 ] += ( prev + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT suffix [ i - 1 ] = prev ; NEW_LINE DEDENT seen [ ord ( s [ i ] ) - ord ( ' a ' ) ] = 1 ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( prefix [ i ] == suffix [ i ] ) : NEW_LINE INDENT answer += 1 ; NEW_LINE DEDENT DEDENT return answer ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " ababa " ; NEW_LINE print ( waysToSplit ( s ) ) ; NEW_LINE DEDENT
Counts paths from a point to reach Origin : Memory Optimized | Function to count the paths from a point to the origin ; Base Case when the point is already at origin ; Base Case when the point is on the x or y - axis ; Loop to fill all the position as 1 in the array ; Loop to count the number of paths from a point to origin in bottom - up manner ; Driver Code ; Function call
def Count_Paths ( x , y ) : NEW_LINE INDENT if ( x == 0 and y == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( x == 0 and y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT dp = [ 0 ] * ( max ( x , y ) + 1 ) NEW_LINE p = max ( x , y ) NEW_LINE q = min ( x , y ) NEW_LINE for i in range ( p + 1 ) : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , q + 1 ) : NEW_LINE INDENT for j in range ( 1 , p + 1 ) : NEW_LINE INDENT dp [ j ] += dp [ j - 1 ] NEW_LINE DEDENT DEDENT return dp [ p ] NEW_LINE DEDENT x = 3 NEW_LINE y = 3 NEW_LINE print ( " Number ▁ of ▁ Paths ▁ " , Count_Paths ( x , y ) ) NEW_LINE
Find the numbers present at Kth level of a Fibonacci Binary Tree | Initializing the max value ; Array to store all the fibonacci numbers ; Function to generate fibonacci numbers using Dynamic Programming ; 0 th and 1 st number of the series are 0 and 1 ; Add the previous two numbers in the series and store it ; Function to print the Fibonacci numbers present at Kth level of a Binary Tree ; Finding the left and right index ; Iterating and printing the numbers ; Precomputing Fibonacci numbers
MAX_SIZE = 100005 NEW_LINE fib = [ 0 ] * ( MAX_SIZE + 1 ) NEW_LINE def fibonacci ( ) : NEW_LINE INDENT fib [ 0 ] = 0 NEW_LINE fib [ 1 ] = 1 NEW_LINE for i in range ( 2 , MAX_SIZE + 1 ) : NEW_LINE INDENT fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] NEW_LINE DEDENT DEDENT def printLevel ( level ) : NEW_LINE INDENT left_index = pow ( 2 , level - 1 ) NEW_LINE right_index = pow ( 2 , level ) - 1 NEW_LINE for i in range ( left_index , right_index + 1 ) : NEW_LINE INDENT print ( fib [ i - 1 ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT fibonacci ( ) NEW_LINE K = 4 NEW_LINE printLevel ( K ) NEW_LINE
Count the number of ways to divide N in k groups incrementally | Function to count the number of ways to divide the number N in groups such that each group has K number of elements ; Base Case ; If N is divides completely into less than k groups ; Put all possible values greater equal to prev ; Function to count the number of ways to divide the number N ; Driver Code
def calculate ( pos , prev , left , k ) : NEW_LINE INDENT if ( pos == k ) : NEW_LINE INDENT if ( left == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( left == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT answer = 0 ; NEW_LINE for i in range ( prev , left + 1 ) : NEW_LINE INDENT answer += calculate ( pos + 1 , i , left - i , k ) ; NEW_LINE DEDENT return answer ; NEW_LINE DEDENT def countWaystoDivide ( n , k ) : NEW_LINE INDENT return calculate ( 0 , 1 , n , k ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 ; NEW_LINE K = 4 ; NEW_LINE print ( countWaystoDivide ( N , K ) ) ; NEW_LINE DEDENT
Count the number of ways to divide N in k groups incrementally | DP Table ; Function to count the number of ways to divide the number N in groups such that each group has K number of elements ; Base Case ; if N is divides completely into less than k groups ; If the subproblem has been solved , use the value ; put all possible values greater equal to prev ; Function to count the number of ways to divide the number N in groups ; Initialize DP Table as - 1 ; Driver Code
dp = [ [ [ 0 for i in range ( 50 ) ] for j in range ( 50 ) ] for j in range ( 50 ) ] NEW_LINE def calculate ( pos , prev , left , k ) : NEW_LINE INDENT if ( pos == k ) : NEW_LINE INDENT if ( left == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( left == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ pos ] [ prev ] [ left ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ prev ] [ left ] ; NEW_LINE DEDENT answer = 0 ; NEW_LINE for i in range ( prev , left + 1 ) : NEW_LINE INDENT answer += calculate ( pos + 1 , i , left - i , k ) ; NEW_LINE DEDENT dp [ pos ] [ prev ] [ left ] = answer ; NEW_LINE return dp [ pos ] [ prev ] [ left ] ; NEW_LINE DEDENT def countWaystoDivide ( n , k ) : NEW_LINE INDENT for i in range ( 50 ) : NEW_LINE INDENT for j in range ( 50 ) : NEW_LINE INDENT for l in range ( 50 ) : NEW_LINE INDENT dp [ i ] [ j ] [ l ] = - 1 ; NEW_LINE DEDENT DEDENT DEDENT return calculate ( 0 , 1 , n , k ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 ; NEW_LINE K = 4 ; NEW_LINE print ( countWaystoDivide ( N , K ) ) ; NEW_LINE DEDENT
Maximum score possible after performing given operations on an Array | Function to calculate maximum score recursively ; Base case ; Sum of array in range ( l , r ) ; If the operation is even - numbered the score is decremented ; Exploring all paths , by removing leftmost and rightmost element and selecting the maximum value ; Function to find the max score ; Prefix sum array ; Calculating prefix_sum ; Driver code
def maxScore ( l , r , prefix_sum , num ) : NEW_LINE INDENT if ( l > r ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( ( l - 1 ) >= 0 ) : NEW_LINE INDENT current_sum = ( prefix_sum [ r ] - prefix_sum [ l - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT current_sum = prefix_sum [ r ] - 0 NEW_LINE DEDENT if ( num % 2 == 0 ) : NEW_LINE INDENT current_sum *= - 1 ; NEW_LINE DEDENT return current_sum + max ( maxScore ( l + 1 , r , prefix_sum , num + 1 ) , maxScore ( l , r - 1 , prefix_sum , num + 1 ) ) ; NEW_LINE DEDENT def findMaxScore ( a , n ) : NEW_LINE INDENT prefix_sum = [ 0 ] * n NEW_LINE prefix_sum [ 0 ] = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix_sum [ i ] = prefix_sum [ i - 1 ] + a [ i ] ; NEW_LINE DEDENT return maxScore ( 0 , n - 1 , prefix_sum , 1 ) ; NEW_LINE DEDENT n = 6 ; NEW_LINE A = [ 1 , 2 , 3 , 4 , 2 , 6 ] NEW_LINE ans = findMaxScore ( A , n ) NEW_LINE print ( ans ) NEW_LINE
Make all array elements divisible by a number K | Function to make array divisible ; For each element of array how much number to be subtracted to make it divisible by k ; For each element of array how much number to be added to make it divisible by K ; Calculate minimum difference ; Driver Code
def makeDivisble ( arr , k ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE b1 = [ ] NEW_LINE b2 = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT b1 . append ( arr [ i ] % k ) NEW_LINE DEDENT for j in range ( n ) : NEW_LINE INDENT if ( ( arr [ j ] % k ) != 0 ) : NEW_LINE INDENT b2 . append ( k - ( arr [ j ] % k ) ) NEW_LINE DEDENT else : NEW_LINE INDENT b2 . append ( 0 ) NEW_LINE DEDENT DEDENT c = 0 NEW_LINE mini = float ( ' inf ' ) NEW_LINE suml = 0 NEW_LINE sumr = 0 NEW_LINE index = - 1 NEW_LINE for c in range ( 0 , n + 1 , 1 ) : NEW_LINE INDENT suml = sum ( b1 [ : c + 1 ] ) NEW_LINE sumr = sum ( b2 ) NEW_LINE if suml >= sumr : NEW_LINE INDENT rem = suml - sumr NEW_LINE if rem < mini : NEW_LINE INDENT mini = rem NEW_LINE index = c NEW_LINE DEDENT DEDENT DEDENT return index , mini NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 14 , 4 , 41 , 1 ] NEW_LINE k = 7 NEW_LINE index , diff = makeDivisble ( arr , k ) NEW_LINE print ( index , diff ) NEW_LINE DEDENT
Finding powers of any number P in N ! | Python3 program to find the power of P in N ! ; Map to store all the prime factors of P ; Function to find the prime factors of N im Map ; Clear map ; Check for factors of 2 ; Find all the prime factors ; If i is a factors then increase the frequency of i ; Function to find the power of prime number P in N ! ; Loop until temp <= N ; Add the number of numbers divisible by N ; Each time multiply temp by P ; Returns ans ; Function that find the powers of any P in N ! ; Find all prime factors of number P ; To store the powers of all prime factors ; Traverse the map ; Prime factor and corres . powers ; Find power of prime factor primeFac ; Divide frequency by facPow ; Store the power of primeFac ^ facPow ; Return the minimum element in Power array ; Driver code ; Function to find power of P in N !
import math NEW_LINE Map = { } NEW_LINE def findPrimeFactors ( N ) : NEW_LINE INDENT Map . clear ( ) NEW_LINE while ( N % 2 == 0 ) : NEW_LINE INDENT if 2 in Map : NEW_LINE INDENT Map [ 2 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Map [ 2 ] = 1 NEW_LINE DEDENT N = N // 2 NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( N ) ) + 1 , 2 ) : NEW_LINE INDENT while ( N % i == 0 ) : NEW_LINE INDENT if i in Map : NEW_LINE INDENT Map [ i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Map [ i ] = 1 NEW_LINE DEDENT N = N // i NEW_LINE DEDENT DEDENT if ( N > 2 ) : NEW_LINE INDENT if N in Map : NEW_LINE INDENT Map [ N ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Map [ N ] = 1 NEW_LINE DEDENT DEDENT DEDENT def PowInFactN ( N , P ) : NEW_LINE INDENT ans = 0 NEW_LINE temp = P NEW_LINE while ( temp <= N ) : NEW_LINE INDENT ans = ans + ( N // temp ) NEW_LINE temp = temp * P NEW_LINE DEDENT return ans NEW_LINE DEDENT def findPowers ( N , P ) : NEW_LINE INDENT findPrimeFactors ( P ) NEW_LINE Powers = [ ] NEW_LINE for it1 , it2 in Map . items ( ) : NEW_LINE INDENT primeFac = it1 NEW_LINE facPow = it2 NEW_LINE p = PowInFactN ( N , primeFac ) NEW_LINE p = p // facPow NEW_LINE Powers . append ( p ) NEW_LINE DEDENT return min ( Powers ) NEW_LINE DEDENT N , P = 24 , 4 NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( findPowers ( N , P ) ) NEW_LINE DEDENT
Longest common subarray in the given two arrays | Function to find the maximum length of equal subarray ; Auxiliary dp [ ] [ ] array ; Updating the dp [ ] [ ] table in Bottom Up approach ; If A [ i ] is equal to B [ i ] then dp [ j ] [ i ] = dp [ j + 1 ] [ i + 1 ] + 1 ; Find maximum of all the values in dp [ ] [ ] array to get the maximum length ; Update the length ; Return the maximum length ; Driver Code ; Function call to find maximum length of subarray
def FindMaxLength ( A , B ) : NEW_LINE INDENT n = len ( A ) NEW_LINE m = len ( B ) NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ] NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( m - 1 , - 1 , - 1 ) : NEW_LINE INDENT if A [ i ] == B [ j ] : NEW_LINE INDENT dp [ j ] [ i ] = dp [ j + 1 ] [ i + 1 ] + 1 NEW_LINE DEDENT DEDENT DEDENT maxm = 0 NEW_LINE for i in dp : NEW_LINE INDENT for j in i : NEW_LINE INDENT maxm = max ( maxm , j ) NEW_LINE DEDENT DEDENT return maxm NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 8 , 2 , 1 ] NEW_LINE B = [ 8 , 2 , 1 , 4 , 7 ] NEW_LINE print ( FindMaxLength ( A , B ) ) NEW_LINE DEDENT
Maximum sum of elements divisible by K from the given array |
k = 16 NEW_LINE arr = [ 43 , 1 , 17 , 26 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE dp = [ [ 0 for i in range ( k ) ] for j in range ( n + 2 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( k ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT dp [ i ] [ arr [ i - 1 ] % k ] = max ( dp [ i ] [ arr [ i - 1 ] % k ] , arr [ i - 1 ] ) NEW_LINE for j in range ( k ) : NEW_LINE INDENT m = ( j + arr [ i - 1 ] ) % k NEW_LINE if dp [ i - 1 ] [ j ] != 0 : NEW_LINE INDENT dp [ i ] [ m ] = max ( dp [ i ] [ m ] , arr [ i - 1 ] + dp [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT print ( dp [ n ] [ 0 ] ) NEW_LINE
Maximum contiguous decreasing sequence obtained by removing any one element | Function to find the maximum length ; Initialise maximum length to 1 ; Initialise left [ ] to find the length of decreasing sequence from left to right ; Initialise right [ ] to find the length of decreasing sequence from right to left ; Initially store 1 at each index of left and right array ; Iterate over the array arr [ ] to store length of decreasing sequence that can be obtained at every index in the right array ; Store the length of longest continuous decreasing sequence in maximum ; Iterate over the array arr [ ] to store length of decreasing sequence that can be obtained at every index in the left array ; Check if we can obtain a longer decreasing sequence after removal of any element from the array arr [ ] with the help of left [ ] & right [ ] ; Return maximum length of sequence ; Driver code ; Function calling
def maxLength ( a , n ) : NEW_LINE INDENT maximum = 1 ; NEW_LINE left = [ 0 ] * n ; NEW_LINE right = [ 0 ] * n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT left [ i ] = 1 ; NEW_LINE right [ i ] = 1 ; NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] > a [ i + 1 ] ) : NEW_LINE INDENT right [ i ] = right [ i + 1 ] + 1 ; NEW_LINE DEDENT maximum = max ( maximum , right [ i ] ) ; NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] < a [ i - 1 ] ) : NEW_LINE INDENT left [ i ] = left [ i - 1 ] + 1 ; NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( a [ i - 1 ] > a [ i + 1 ] ) : NEW_LINE INDENT maximum = max ( maximum , left [ i - 1 ] + right [ i + 1 ] ) ; NEW_LINE DEDENT DEDENT DEDENT return maximum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 8 , 7 , 3 , 5 , 2 , 9 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxLength ( arr , n ) ) ; NEW_LINE DEDENT
Longest alternating subsequence in terms of positive and negative integers | Python3 program to find the length of longest alternate subsequence ; LAS [ i ] [ pos ] array to find the length of LAS till index i by including or excluding element arr [ i ] on the basis of value of pos ; Base Case ; If current element is positive and pos is true Include the current element and change pos to false ; Recurr for the next iteration ; If current element is negative and pos is false Include the current element and change pos to true ; Recurr for the next iteration ; If current element is excluded , reccur for next iteration ; Driver 's Code ; Print LAS
import numpy as np NEW_LINE LAS = np . zeros ( ( 1000 , 2 ) ) NEW_LINE for i in range ( 1000 ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT LAS [ i ] [ j ] = False NEW_LINE DEDENT DEDENT def solve ( arr , n , i , pos ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( LAS [ i ] [ pos ] ) : NEW_LINE INDENT return LAS [ i ] [ pos ] ; NEW_LINE DEDENT inc = 0 ; exc = 0 ; NEW_LINE if ( arr [ i ] > 0 and pos == True ) : NEW_LINE INDENT pos = False ; NEW_LINE inc = 1 + solve ( arr , n , i + 1 , pos ) ; NEW_LINE DEDENT elif ( arr [ i ] < 0 and pos == False ) : NEW_LINE INDENT pos = True ; NEW_LINE inc = 1 + solve ( arr , n , i + 1 , pos ) ; NEW_LINE DEDENT exc = solve ( arr , n , i + 1 , pos ) ; NEW_LINE LAS [ i ] [ pos ] = max ( inc , exc ) ; NEW_LINE return LAS [ i ] [ pos ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 1 , 2 , 3 , 4 , 5 , - 6 , 8 , - 99 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( max ( solve ( arr , n , 0 , 0 ) , solve ( arr , n , 0 , 1 ) ) ) ; NEW_LINE DEDENT
Number of subsequences with negative product | Python 3 implementation of the approach ; Function to return the count of all the subsequences with negative product ; To store the count of positive elements in the array ; To store the count of negative elements in the array ; If the current element is positive ; If the current element is negative ; For all the positive elements of the array ; For all the negative elements of the array ; Driver code
import math NEW_LINE def cntSubSeq ( arr , n ) : NEW_LINE INDENT pos_count = 0 ; NEW_LINE neg_count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT pos_count += 1 NEW_LINE DEDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT neg_count += 1 NEW_LINE DEDENT DEDENT result = int ( math . pow ( 2 , pos_count ) ) NEW_LINE if ( neg_count > 0 ) : NEW_LINE INDENT result *= int ( math . pow ( 2 , neg_count - 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT result = 0 NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 2 , - 3 , - 1 , 4 ] NEW_LINE n = len ( arr ) ; NEW_LINE print ( cntSubSeq ( arr , n ) ) NEW_LINE
Find minimum number of steps to reach the end of String | Python3 implementation of the approach ; Function to return the minimum number of steps to reach the end ; If the end can 't be reached ; Already at the end ; If the length is 2 or 3 then the end can be reached in a single step ; For the other cases , solve the problem using dynamic programming ; It requires no move from the end to reach the end ; From the 2 nd last and the 3 rd last index , only a single move is required ; Update the answer for every index ; If the current index is not reachable ; To store the minimum steps required from the current index ; If it is a valid move then update the minimum steps required ; Update the minimum steps required starting from the current index ; Cannot reach the end starting from str [ 0 ] ; Return the minimum steps required ; Driver code
import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def minSteps ( string , n , k ) : NEW_LINE INDENT if ( string [ n - 1 ] == '0' ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n < 4 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT dp = [ 0 ] * n ; NEW_LINE dp [ n - 1 ] = 0 ; NEW_LINE dp [ n - 2 ] = 1 ; NEW_LINE dp [ n - 3 ] = 1 ; NEW_LINE for i in range ( n - 4 , - 1 , - 1 ) : NEW_LINE INDENT if ( string [ i ] == '0' ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT steps = INT_MAX ; NEW_LINE if ( i + k < n and string [ i + k ] == '1' ) : NEW_LINE INDENT steps = min ( steps , dp [ i + k ] ) ; NEW_LINE DEDENT if ( string [ i + 1 ] == '1' ) : NEW_LINE INDENT steps = min ( steps , dp [ i + 1 ] ) ; NEW_LINE DEDENT if ( string [ i + 2 ] == '1' ) : NEW_LINE INDENT steps = min ( steps , dp [ i + 2 ] ) ; NEW_LINE DEDENT dp [ i ] = steps if ( steps == INT_MAX ) else ( 1 + steps ) ; NEW_LINE DEDENT if ( dp [ 0 ] == INT_MAX ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return dp [ 0 ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "101000011" ; NEW_LINE n = len ( string ) ; NEW_LINE k = 5 ; NEW_LINE print ( minSteps ( string , n , k ) ) ; NEW_LINE DEDENT