text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Number of closing brackets needed to complete a regular bracket sequence | Function to find number of closing brackets and complete a regular bracket sequence ; Finding the length of sequence ; Counting opening brackets ; Counting closing brackets ; Checking if at any position the number of closing bracket is more then answer is impossible ; If possible , print ' s ' and required closing brackets . ; Driver code
def completeSequence ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE open = 0 NEW_LINE close = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT open += 1 NEW_LINE DEDENT else : NEW_LINE INDENT close += 1 NEW_LINE DEDENT if ( close > open ) : NEW_LINE INDENT print ( " IMPOSSIBLE " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( s , end = " " ) NEW_LINE for i in range ( open - close ) : NEW_LINE INDENT print ( " ) " , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " ( ( ) ( ( ) ( " NEW_LINE completeSequence ( s ) NEW_LINE DEDENT
Lexicographically smallest permutation with no digits at Original Index | Function to print the smallest permutation ; when n is even ; when n is odd ; handling last 3 digit ; add EOL and print result ; Driver Code
def smallestPermute ( n ) : NEW_LINE INDENT res = [ " " ] * ( n + 1 ) NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT res [ i ] = chr ( 48 + i + 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT res [ i ] = chr ( 48 + i ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( n - 2 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT res [ i ] = chr ( 48 + i + 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT res [ i ] = chr ( 48 + i ) NEW_LINE DEDENT DEDENT res [ n - 1 ] = chr ( 48 + n - 2 ) NEW_LINE res [ n - 2 ] = chr ( 48 + n ) NEW_LINE res [ n - 3 ] = chr ( 48 + n - 1 ) NEW_LINE DEDENT res = ' ' . join ( res ) NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 7 NEW_LINE print ( smallestPermute ( n ) ) NEW_LINE DEDENT
Minimum array insertions required to make consecutive difference <= K | Python3 implementation of above approach ; Function to return minimum number of insertions required ; Initialize insertions to 0 ; return total insertions ; Driver Code
import math NEW_LINE def minInsertions ( H , n , K ) : NEW_LINE INDENT inser = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT diff = abs ( H [ i ] - H [ i - 1 ] ) ; NEW_LINE if ( diff <= K ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT else : NEW_LINE INDENT inser += math . ceil ( diff / K ) - 1 ; NEW_LINE DEDENT DEDENT return inser ; NEW_LINE DEDENT H = [ 2 , 4 , 8 , 16 ] ; NEW_LINE K = 3 ; NEW_LINE n = len ( H ) ; NEW_LINE print ( minInsertions ( H , n , K ) ) ; NEW_LINE
Minimum number of operations required to reduce N to 1 | Function that returns the minimum number of operations to be performed to reduce the number to 1 ; To stores the total number of operations to be performed ; if n is divisible by 3 then reduce it to n / 3 ; if n modulo 3 is 1 decrement it by 1 ; if n modulo 3 is 2 then increment it by 1 ; update the counter ; Driver code
def count_minimum_operations ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n > 1 ) : NEW_LINE INDENT if ( n % 3 == 0 ) : NEW_LINE INDENT n //= 3 NEW_LINE DEDENT elif ( n % 3 == 1 ) : NEW_LINE INDENT n -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( n == 2 ) : NEW_LINE INDENT n -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT n += 1 NEW_LINE DEDENT DEDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE ans = count_minimum_operations ( n ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Minimum number of operations required to reduce N to 1 | Function that returns the minimum number of operations to be performed to reduce the number to 1 ; Base cases ; Driver Code
def count_minimum_operations ( n ) : NEW_LINE INDENT if ( n == 2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n % 3 == 0 ) : NEW_LINE INDENT return 1 + count_minimum_operations ( n / 3 ) NEW_LINE DEDENT elif ( n % 3 == 1 ) : NEW_LINE INDENT return 1 + count_minimum_operations ( n - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return 1 + count_minimum_operations ( n + 1 ) NEW_LINE DEDENT DEDENT n = 4 NEW_LINE ans = count_minimum_operations ( n ) NEW_LINE print ( ans ) NEW_LINE
Maximize the sum of array by multiplying prefix of array with | Python implementation of the approach ; To store sum ; To store ending indices of the chosen prefix arrays ; Adding the absolute value of a [ i ] ; If i == 0 then there is no index to be flipped in ( i - 1 ) position ; print the maximised sum ; print the ending indices of the chosen prefix arrays ; Driver Code
def maxSum ( arr , n ) : NEW_LINE INDENT s = 0 NEW_LINE l = [ ] NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT s += abs ( a [ i ] ) NEW_LINE if ( a [ i ] >= 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( i == 0 ) : NEW_LINE INDENT l . append ( i + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT l . append ( i + 1 ) NEW_LINE l . append ( i ) NEW_LINE DEDENT DEDENT print ( s ) NEW_LINE print ( * l ) NEW_LINE DEDENT n = 4 NEW_LINE a = [ 1 , - 2 , - 3 , 4 ] NEW_LINE maxSum ( a , n ) NEW_LINE
Find the longest common prefix between two strings after performing swaps on second string | Python program to find the longest common prefix between two strings after performing swaps on the second string ; a = len ( x ) length of x b = len ( y ) length of y ; creating frequency array of characters of y ; storing the length of longest common prefix ; checking if the frequency of the character at position i in x in b is greater than zero or not if zero we increase the prefix count by 1 ; Driver Code
def LengthLCP ( x , y ) : NEW_LINE INDENT fr = [ 0 ] * 26 NEW_LINE for i in range ( b ) : NEW_LINE INDENT fr [ ord ( y [ i ] ) - 97 ] += 1 NEW_LINE DEDENT c = 0 NEW_LINE for i in range ( a ) : NEW_LINE INDENT if ( fr [ ord ( x [ i ] ) - 97 ] > 0 ) : NEW_LINE INDENT c += 1 NEW_LINE fr [ ord ( x [ i ] ) - 97 ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( c ) NEW_LINE DEDENT x , y = " here " , " there " NEW_LINE LengthLCP ( x , y ) NEW_LINE
All possible co | Function to count possible pairs ; total count of numbers in range ; printing count of pairs ; Driver code
def CountPair ( L , R ) : NEW_LINE INDENT x = ( R - L + 1 ) NEW_LINE print ( x // 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R = 1 , 8 NEW_LINE CountPair ( L , R ) NEW_LINE DEDENT
Problems not solved at the end of Nth day | Function to find problems not solved at the end of Nth day ; Driver Code
def problemsLeft ( K , P , N ) : NEW_LINE INDENT if ( K <= P ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( K - P ) * N ) NEW_LINE DEDENT DEDENT K , P , N = 4 , 1 , 10 NEW_LINE print ( problemsLeft ( K , P , N ) ) NEW_LINE
Kruskal 's Algorithm (Simple Implementation for Adjacency Matrix) | Find set of vertex i ; Does union of i and j . It returns false if i and j are already in same set . ; Finds MST using Kruskal 's algorithm ; Initialize sets of disjoint sets ; Include minimum weight edges one by one ; Let us create the following graph 2 3 ( 0 ) -- ( 1 ) -- ( 2 ) | / \ | 6 | 8 / \ 5 | 7 | / \ | ( 3 ) -- -- -- - ( 4 ) 9 ; Print the solution
def find ( i ) : NEW_LINE INDENT while parent [ i ] != i : NEW_LINE INDENT i = parent [ i ] NEW_LINE DEDENT return i NEW_LINE DEDENT def union ( i , j ) : NEW_LINE INDENT a = find ( i ) NEW_LINE b = find ( j ) NEW_LINE parent [ a ] = b NEW_LINE DEDENT def kruskalMST ( cost ) : NEW_LINE INDENT for i in range ( V ) : NEW_LINE INDENT parent [ i ] = i NEW_LINE DEDENT edge_count = 0 NEW_LINE while edge_count < V - 1 : NEW_LINE INDENT min = INF NEW_LINE a = - 1 NEW_LINE b = - 1 NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT if find ( i ) != find ( j ) and cost [ i ] [ j ] < min : NEW_LINE INDENT min = cost [ i ] [ j ] NEW_LINE a = i NEW_LINE b = j NEW_LINE DEDENT DEDENT DEDENT union ( a , b ) NEW_LINE print ( ' Edge ▁ { } : ( { } , ▁ { } ) ▁ cost : { } ' . format ( edge_count , a , b , min ) ) NEW_LINE edge_count += 1 NEW_LINE mincost += min NEW_LINE DEDENT print ( " Minimum ▁ cost = ▁ { } " . format ( mincost ) ) NEW_LINE DEDENT V = 5 NEW_LINE parent = [ i for i in range ( V ) ] NEW_LINE INF = float ( ' inf ' ) NEW_LINE cost = [ [ INF , 2 , INF , 6 , INF ] , [ 2 , INF , 3 , 8 , 5 ] , [ INF , 3 , INF , INF , 7 ] , [ 6 , 8 , INF , INF , 9 ] , [ INF , 5 , 7 , 9 , INF ] ] NEW_LINE kruskalMST ( cost ) NEW_LINE
Number of chocolates left after k iterations | Function to find the chocolates left ; Driver code
def results ( n , k ) : NEW_LINE INDENT return round ( pow ( n , ( 1.0 / pow ( 2 , k ) ) ) ) NEW_LINE DEDENT k = 3 NEW_LINE n = 100000000 NEW_LINE print ( " Chocolates ▁ left ▁ after " ) , NEW_LINE print ( k ) , NEW_LINE print ( " iterations ▁ are " ) , NEW_LINE print ( int ( results ( n , k ) ) ) NEW_LINE
Subarray whose absolute sum is closest to K | Python Code to find sub - array whose sum shows the minimum deviation ; starting index , ending index , Deviation ; iterate i and j to get all subarrays ; found sub - array with less sum ; exactly same sum ; Driver Code ; Array to store return values
def getSubArray ( arr , n , K ) : NEW_LINE INDENT i = - 1 NEW_LINE j = - 1 NEW_LINE currSum = 0 NEW_LINE result = [ i , j , abs ( K - abs ( currSum ) ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT currSum = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT currSum += arr [ j ] NEW_LINE currDev = abs ( K - abs ( currSum ) ) NEW_LINE if ( currDev < result [ 2 ] ) : NEW_LINE INDENT result = [ i , j , currDev ] NEW_LINE DEDENT if ( currDev == 0 ) : NEW_LINE INDENT return result NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT arr = [ 15 , - 3 , 5 , 2 , 7 , 6 , 34 , - 6 ] NEW_LINE n = len ( arr ) NEW_LINE K = 50 NEW_LINE [ i , j , minDev ] = getSubArray ( arr , n , K ) NEW_LINE if ( i == - 1 ) : NEW_LINE INDENT print ( " The ▁ empty ▁ array ▁ shows ▁ minimum ▁ Deviation " ) NEW_LINE return 0 NEW_LINE DEDENT for i in range ( i , j + 1 ) : NEW_LINE INDENT print arr [ i ] , NEW_LINE DEDENT DEDENT main ( ) NEW_LINE
Longest subsequence whose average is less than K | Python3 program to perform Q queries to find longest subsequence whose average is less than K ; Function to print the length for evey query ; sort array of N elements ; Array to store average from left ; Sort array of average ; number of queries ; print answer to every query using binary search ; Driver Code ; 4 queries
import bisect NEW_LINE def longestSubsequence ( a , n , q , m ) : NEW_LINE INDENT a . sort ( ) NEW_LINE Sum = 0 NEW_LINE b = [ None ] * n NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Sum += a [ i ] NEW_LINE av = Sum // ( i + 1 ) NEW_LINE b [ i ] = av + 1 NEW_LINE DEDENT b . sort ( ) NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT k = q [ i ] NEW_LINE longest = bisect . bisect_right ( b , k ) NEW_LINE print ( " Answer ▁ to ▁ Query " , i + 1 , " : " , longest ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 3 , 2 , 5 , 4 ] NEW_LINE n = len ( a ) NEW_LINE q = [ 4 , 2 , 1 , 5 ] NEW_LINE m = len ( q ) NEW_LINE longestSubsequence ( a , n , q , m ) NEW_LINE DEDENT
Make array elements equal in Minimum Steps | Returns the minimum steps required to make an array of N elements equal , where the first array element equals M ; Corner Case 1 : When N = 1 ; Corner Case 2 : When N = 2 ; Driver Code
def steps ( N , M ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( N == 2 ) : NEW_LINE INDENT return M NEW_LINE DEDENT return 2 * M + ( N - 3 ) NEW_LINE DEDENT N = 4 NEW_LINE M = 4 NEW_LINE print ( steps ( N , M ) ) NEW_LINE
Minimum increment / decrement to make array non | Python3 code to count the change required to convert the array into non - increasing array ; min heap ; Here in the loop we will check that whether the upcoming element of array is less than top of priority queue . If yes then we calculate the difference . After that we will remove that element and push the current element in queue . And the sum is incremented by the value of difference ; Driver code
from queue import PriorityQueue NEW_LINE def DecreasingArray ( a , n ) : NEW_LINE INDENT ss , dif = ( 0 , 0 ) NEW_LINE pq = PriorityQueue ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT tmp = 0 NEW_LINE if not pq . empty ( ) : NEW_LINE INDENT tmp = pq . get ( ) NEW_LINE pq . put ( tmp ) NEW_LINE DEDENT if not pq . empty ( ) and tmp < a [ i ] : NEW_LINE INDENT dif = a [ i ] - tmp NEW_LINE ss += dif NEW_LINE pq . get ( ) NEW_LINE DEDENT pq . put ( a [ i ] ) NEW_LINE DEDENT return ss NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 3 , 1 , 2 , 1 ] NEW_LINE n = len ( a ) NEW_LINE print ( DecreasingArray ( a , n ) ) NEW_LINE DEDENT
Schedule jobs so that each server gets equal load | Function to find new array a ; find sum S of both arrays a and b . ; Single element case . ; This checks whether sum s can be divided equally between all array elements . i . e . whether all elements can take equal value or not . ; Compute possible value of new array elements . ; Possibility 1 ; ensuring that all elements of array b are used . ; If a ( i ) already updated to x move to next element in array a . ; Possibility 2 ; Possibility 3 ; Possibility 4 ; If a ( i ) can not be made equal to x even after adding all possible elements from b ( i ) then print - 1. ; check whether all elements of b are used . ; Return the new array element value . ; Driver Code
def solve ( a , b , n ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT s += a [ i ] + b [ i ] NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return a [ 0 ] + b [ 0 ] NEW_LINE DEDENT if s % n != 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT x = s // n NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if a [ i ] > x : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if i > 0 : NEW_LINE INDENT a [ i ] += b [ i - 1 ] NEW_LINE b [ i - 1 ] = 0 NEW_LINE DEDENT if a [ i ] == x : NEW_LINE INDENT continue NEW_LINE DEDENT y = a [ i ] + b [ i ] NEW_LINE if i + 1 < n : NEW_LINE INDENT y += b [ i + 1 ] NEW_LINE DEDENT if y == x : NEW_LINE INDENT a [ i ] = y NEW_LINE b [ i ] = 0 NEW_LINE if i + 1 < n : b [ i + 1 ] = 0 NEW_LINE continue NEW_LINE DEDENT if a [ i ] + b [ i ] == x : NEW_LINE INDENT a [ i ] += b [ i ] NEW_LINE b [ i ] = 0 NEW_LINE continue NEW_LINE DEDENT if i + 1 < n and a [ i ] + b [ i + 1 ] == x : NEW_LINE INDENT a [ i ] += b [ i + 1 ] NEW_LINE b [ i + 1 ] = 0 NEW_LINE continue NEW_LINE DEDENT return - 1 NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if b [ i ] != 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 6 , 14 , 21 , 1 ] NEW_LINE b = [ 15 , 7 , 10 , 10 ] NEW_LINE n = len ( a ) NEW_LINE print ( solve ( a , b , n ) ) NEW_LINE DEDENT
Check if it is possible to survive on Island | function to find the minimum days ; If we can not buy at least a week supply of food during the first week OR We can not buy a day supply of food on the first day then we can 't survive. ; If we can survive then we can buy ceil ( A / N ) times where A is total units of food required . ; Driver code
def survival ( S , N , M ) : NEW_LINE INDENT if ( ( ( N * 6 ) < ( M * 7 ) and S > 6 ) or M > N ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT else : NEW_LINE INDENT days = ( M * S ) / N NEW_LINE if ( ( ( M * S ) % N ) != 0 ) : NEW_LINE INDENT days += 1 NEW_LINE DEDENT print ( " Yes ▁ " ) , NEW_LINE print ( days ) NEW_LINE DEDENT DEDENT S = 10 ; N = 16 ; M = 2 NEW_LINE survival ( S , N , M ) NEW_LINE
Lexicographically largest subsequence such that every character occurs at least k times | Find lexicographically largest subsequence of s [ 0. . n - 1 ] such that every character appears at least k times . The result is filled in t [ ] ; Starting from largest charter ' z ' to 'a ; Counting the frequency of the character ; If frequency is greater than k ; From the last point we leave ; check if string contain ch ; If yes , append to output string ; Update the last point . ; Driver Code
def subsequence ( s , t , n , k ) : NEW_LINE INDENT last = 0 NEW_LINE cnt = 0 NEW_LINE new_last = 0 NEW_LINE size = 0 NEW_LINE string = ' zyxwvutsrqponmlkjihgfedcba ' NEW_LINE DEDENT ' NEW_LINE INDENT for ch in string : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( last , n ) : NEW_LINE INDENT if s [ i ] == ch : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT if cnt >= k : NEW_LINE INDENT for i in range ( last , n ) : NEW_LINE INDENT if s [ i ] == ch : NEW_LINE INDENT t [ size ] = ch NEW_LINE new_last = i NEW_LINE size += 1 NEW_LINE DEDENT DEDENT last = new_last NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = [ ' b ' , ' a ' , ' n ' , ' a ' , ' n ' , ' a ' ] NEW_LINE n = len ( s ) NEW_LINE k = 2 NEW_LINE t = [ ' ' ] * n NEW_LINE subsequence ( s , t , n - 1 , k ) NEW_LINE t = ' ' . join ( t ) NEW_LINE print ( t ) NEW_LINE DEDENT
Largest permutation after at most k swaps | Function to find the largest permutation after k swaps ; Storing the elements and their index in map ; If number of swaps allowed are equal to number of elements then the resulting permutation will be descending order of given permutation . ; If j is not at it 's best index ; Change the index of the element which was at position 0. Swap the element basically . ; Decrement number of swaps ; Driver Code ; K is the number of swaps ; n is the size of the array ; Function calling
def bestpermutation ( arr , k , n ) : NEW_LINE INDENT h = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT h [ arr [ i ] ] = i NEW_LINE DEDENT if ( n <= k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE arr . reverse ( ) NEW_LINE DEDENT else : NEW_LINE INDENT for j in range ( n , 0 , - 1 ) : NEW_LINE INDENT if ( k > 0 ) : NEW_LINE INDENT initial_index = h [ j ] NEW_LINE best_index = n - j NEW_LINE if ( initial_index != best_index ) : NEW_LINE INDENT h [ j ] = best_index NEW_LINE element = arr [ best_index ] NEW_LINE h [ element ] = initial_index NEW_LINE arr [ best_index ] , arr [ initial_index ] = ( arr [ initial_index ] , arr [ best_index ] ) NEW_LINE k -= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT arr = [ 3 , 1 , 4 , 2 , 5 ] NEW_LINE k = 10 NEW_LINE n = len ( arr ) NEW_LINE bestpermutation ( arr , k , n ) NEW_LINE print ( " Largest ▁ possible ▁ permutation ▁ after " , k , " swaps ▁ is " , end = " ▁ " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT
Program for Best Fit algorithm in Memory Management | Function to allocate memory to blocks as per Best fit algorithm ; Stores block id of the block allocated to a process ; pick each process and find suitable blocks according to its size ad assign to it ; Find the best fit block for current process ; If we could find a block for current process ; allocate block j to p [ i ] process ; Reduce available memory in this block . ; Driver code
def bestFit ( blockSize , m , processSize , n ) : NEW_LINE INDENT allocation = [ - 1 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT bestIdx = - 1 NEW_LINE for j in range ( m ) : NEW_LINE INDENT if blockSize [ j ] >= processSize [ i ] : NEW_LINE INDENT if bestIdx == - 1 : NEW_LINE INDENT bestIdx = j NEW_LINE DEDENT elif blockSize [ bestIdx ] > blockSize [ j ] : NEW_LINE INDENT bestIdx = j NEW_LINE DEDENT DEDENT DEDENT if bestIdx != - 1 : NEW_LINE INDENT allocation [ i ] = bestIdx NEW_LINE blockSize [ bestIdx ] -= processSize [ i ] NEW_LINE DEDENT DEDENT print ( " Process ▁ No . ▁ Process ▁ Size ▁ Block ▁ no . " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( i + 1 , " ▁ " , processSize [ i ] , end = " ▁ " ) NEW_LINE if allocation [ i ] != - 1 : NEW_LINE INDENT print ( allocation [ i ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Allocated " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT blockSize = [ 100 , 500 , 200 , 300 , 600 ] NEW_LINE processSize = [ 212 , 417 , 112 , 426 ] NEW_LINE m = len ( blockSize ) NEW_LINE n = len ( processSize ) NEW_LINE bestFit ( blockSize , m , processSize , n ) NEW_LINE DEDENT
Bin Packing Problem ( Minimize number of used Bins ) | Returns number of bins required using first fit online algorithm ; Initialize result ( Count of bins ) ; Create an array to store remaining space in bins there can be at most n bins ; Place items one by one ; Find the first bin that can accommodate weight [ i ] ; Initialize minimum space left and index of best bin ; If no bin could accommodate weight [ i ] , create a new bin ; else : Assign the item to best bin ; Driver code
def firstFit ( weight , n , c ) : NEW_LINE INDENT res = 0 ; NEW_LINE bin_rem = [ 0 ] * n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = 0 ; NEW_LINE min = c + 1 ; NEW_LINE bi = 0 ; NEW_LINE for j in range ( res ) : NEW_LINE INDENT if ( bin_rem [ j ] >= weight [ i ] and bin_rem [ j ] - weight [ i ] < min ) : NEW_LINE INDENT bi = j ; NEW_LINE min = bin_rem [ j ] - weight [ i ] ; NEW_LINE DEDENT DEDENT if ( min == c + 1 ) : NEW_LINE INDENT bin_rem [ res ] = c - weight [ i ] ; NEW_LINE res += 1 ; NEW_LINE bin_rem [ bi ] -= weight [ i ] ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT weight = [ 2 , 5 , 4 , 7 , 1 , 3 , 8 ] ; NEW_LINE c = 10 ; NEW_LINE n = len ( weight ) ; NEW_LINE print ( " Number ▁ of ▁ bins ▁ required ▁ in ▁ First ▁ Fit ▁ : ▁ " , firstFit ( weight , n , c ) ) ; NEW_LINE DEDENT
Find minimum time to finish all jobs with given constraints | Utility function to get maximum element in job [ 0. . n - 1 ] ; Returns true if it is possible to finish jobs [ ] within given time 'time ; cnt is count of current assignees required for jobs ; time assigned to current assignee ; If time assigned to current assignee exceeds max , increment count of assignees . ; Else add time of job to current time and move to next job . ; Returns true if count is smaller than k ; Returns minimum time required to finish given array of jobs k -- > number of assignees T -- > Time required by every assignee to finish 1 unit m -- > Number of jobs ; Set start and end for binary search end provides an upper limit on time ; Find the job that takes maximum time ; Do binary search for minimum feasible time ; If it is possible to finish jobs in mid time ; ans = min ( ans , mid ) Update answer ; Driver program
def getMax ( arr , n ) : NEW_LINE INDENT result = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] > result : NEW_LINE INDENT result = arr [ i ] NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT ' NEW_LINE def isPossible ( time , K , job , n ) : NEW_LINE INDENT cnt = 1 NEW_LINE curr_time = 0 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT if curr_time + job [ i ] > time : NEW_LINE INDENT curr_time = 0 NEW_LINE cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT curr_time += job [ i ] NEW_LINE i += 1 NEW_LINE DEDENT DEDENT return cnt <= K NEW_LINE DEDENT def findMinTime ( K , T , job , n ) : NEW_LINE INDENT end = 0 NEW_LINE start = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT end += job [ i ] NEW_LINE DEDENT job_max = getMax ( job , n ) NEW_LINE while start <= end : NEW_LINE INDENT mid = int ( ( start + end ) / 2 ) NEW_LINE if mid >= job_max and isPossible ( mid , K , job , n ) : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT DEDENT return ans * T NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT job = [ 10 , 7 , 8 , 12 , 6 , 8 ] NEW_LINE n = len ( job ) NEW_LINE k = 4 NEW_LINE T = 5 NEW_LINE print ( findMinTime ( k , T , job , n ) ) NEW_LINE DEDENT
Longest subarray with all even or all odd elements | Function to calculate longest substring with odd or even elements ; Initializing dp [ ] ; Initializing dp [ 0 ] with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp [ i ] with dp [ i - 1 ] + 1 ; Storing max element to ans ; Returning the final answer ; Driver Code ; Input ; Function call
def LongestOddEvenSubarray ( A , N ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE dp [ 0 ] = 1 NEW_LINE ans = 1 NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT if ( ( A [ i ] % 2 == 0 and A [ i - 1 ] % 2 == 0 ) or ( A [ i ] % 2 != 0 and A [ i - 1 ] % 2 != 0 ) ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT ans = max ( ans , dp [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 ] NEW_LINE N = len ( A ) NEW_LINE print ( LongestOddEvenSubarray ( A , N ) ) NEW_LINE DEDENT
Count of subarrays with maximum value as K | Function to count the subarrays with maximum not greater than K ; If arr [ i ] > k then arr [ i ] cannot be a part of any subarray . ; Count the number of elements where arr [ i ] is not greater than k . ; Summation of all possible subarrays in the variable ans . ; Function to count the subarrays with maximum value is equal to K ; Stores count of subarrays with max <= k - 1. ; Stores count of subarrays with max >= k + 1. ; Stores count of subarrays with max = k . ; Driver Code ; Given Input ; Function Call
def totalSubarrays ( arr , n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] > k ) : NEW_LINE INDENT i += 1 NEW_LINE continue NEW_LINE DEDENT count = 0 NEW_LINE while ( i < n and arr [ i ] <= k ) : NEW_LINE INDENT i += 1 NEW_LINE count += 1 NEW_LINE DEDENT ans += ( ( count * ( count + 1 ) ) // 2 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def countSubarrays ( arr , n , k ) : NEW_LINE INDENT count1 = totalSubarrays ( arr , n , k - 1 ) NEW_LINE count2 = totalSubarrays ( arr , n , k ) NEW_LINE ans = count2 - count1 NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE k = 3 NEW_LINE arr = [ 2 , 1 , 3 , 4 ] NEW_LINE print ( countSubarrays ( arr , n , k ) ) NEW_LINE DEDENT
Maximum subsequence sum such that no three are consecutive in O ( 1 ) space | Function to calculate the maximum subsequence sum such that no three elements are consecutive ; when N is 1 , answer would be the only element present ; when N is 2 , answer would be sum of elements ; variable to store sum up to i - 3 ; variable to store sum up to i - 2 ; variable to store sum up to i - 1 ; variable to store the final sum of the subsequence ; find the maximum subsequence sum up to index i ; update first , second and third ; return ans ; ; Driver code ; Input ; Function call
def maxSumWO3Consec ( A , N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return A [ 0 ] NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT return A [ 0 ] + A [ 1 ] NEW_LINE DEDENT third = A [ 0 ] NEW_LINE second = third + A [ 1 ] NEW_LINE first = max ( second , A [ 1 ] + A [ 2 ] ) NEW_LINE sum = max ( max ( third , second ) , first ) NEW_LINE for i in range ( 3 , N , 1 ) : NEW_LINE INDENT sum = max ( max ( first , second + A [ i ] ) , third + A [ i ] + A [ i - 1 ] ) NEW_LINE third = second NEW_LINE second = first NEW_LINE first = sum NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3000 , 2000 , 1000 , 3 , 10 ] NEW_LINE N = len ( A ) NEW_LINE print ( maxSumWO3Consec ( A , N ) ) NEW_LINE DEDENT
Minimum number of given operations required to reduce a number to 2 | Function to find the minimum number of operations required to reduce n to 2 ; Initialize a dp array ; Handle the base case ; Iterate in the range [ 2 , n ] ; Check if i * 5 <= n ; Check if i + 3 <= n ; Return the result ; Driver code ; Given Input ; Function Call ; Print the result
def findMinOperations ( n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] = 999999 NEW_LINE DEDENT dp [ 2 ] = 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( i * 5 <= n ) : NEW_LINE INDENT dp [ i * 5 ] = min ( dp [ i * 5 ] , dp [ i ] + 1 ) NEW_LINE DEDENT if ( i + 3 <= n ) : NEW_LINE INDENT dp [ i + 3 ] = min ( dp [ i + 3 ] , dp [ i ] + 1 ) NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 28 NEW_LINE m = findMinOperations ( n ) NEW_LINE if ( m != 9999 ) : NEW_LINE INDENT print ( m ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT
Split array into subarrays such that sum of difference between their maximums and minimums is maximum | Function to find maximum sum of difference between maximums and minimums in the splitted subarrays ; Traverse the array ; Stores the maximum and minimum elements upto the i - th index ; Traverse the range [ 0 , i ] ; Update the minimum ; Update the maximum ; Update dp [ i ] ; Return the maximum sum of difference ; Driver code
def getValue ( arr , N ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT minn = arr [ i ] NEW_LINE maxx = arr [ i ] NEW_LINE j = i NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT minn = min ( arr [ j ] , minn ) NEW_LINE maxx = max ( arr [ j ] , maxx ) NEW_LINE dp [ i ] = max ( dp [ i ] , maxx - minn + ( dp [ j - 1 ] if ( j >= 1 ) else 0 ) ) NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT return dp [ N - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 1 , 7 , 9 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( getValue ( arr , N ) ) NEW_LINE DEDENT
Maximum score possible by removing substrings made up of single distinct character | Function to check if the string s consists of a single distinct character or not ; Function to calculate the maximum score possible by removing substrings ; If string is empty ; If length of string is 1 ; Store the maximum result ; Try to remove all substrings that satisfy the condition and check for resultant string after removal ; Store the substring { s [ i ] , . . , s [ j ] } ; Check if the substring contains only a single distinct character ; Return the maximum score ; Driver Code
def isUnique ( s ) : NEW_LINE INDENT return True if len ( set ( s ) ) == 1 else False NEW_LINE DEDENT def maxScore ( s , a ) : NEW_LINE INDENT n = len ( s ) NEW_LINE if n == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return a [ 0 ] NEW_LINE DEDENT mx = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT sub = s [ i : j + 1 ] NEW_LINE if isUnique ( sub ) : NEW_LINE INDENT mx = max ( mx , a [ len ( sub ) - 1 ] + maxScore ( s [ : i ] + s [ j + 1 : ] , a ) ) NEW_LINE DEDENT DEDENT DEDENT return mx NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "011" NEW_LINE a = [ 1 , 3 , 1 ] NEW_LINE print ( maxScore ( s , a ) ) NEW_LINE DEDENT
Maximum score possible by removing substrings made up of single distinct character | Initialize a dictionary to store the precomputed results ; Function to calculate the maximum score possible by removing substrings ; If s is present in dp [ ] array ; Base Cases : ; If length of string is 0 ; If length of string is 1 ; Put head pointer at start ; Initialize the max variable ; Generate the substrings using two pointers ; If s [ head ] and s [ tail ] are different ; Move head to tail and break ; Store the substring ; Update the maximum ; Move the tail ; Store the score ; Driver Code
dp = dict ( ) NEW_LINE def maxScore ( s , a ) : NEW_LINE INDENT if s in dp : NEW_LINE INDENT return dp [ s ] NEW_LINE DEDENT n = len ( s ) NEW_LINE if n == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return a [ 0 ] NEW_LINE DEDENT head = 0 NEW_LINE mx = - 1 NEW_LINE while head < n : NEW_LINE INDENT tail = head NEW_LINE while tail < n : NEW_LINE INDENT if s [ tail ] != s [ head ] : NEW_LINE INDENT head = tail NEW_LINE break NEW_LINE DEDENT sub = s [ head : tail + 1 ] NEW_LINE mx = max ( mx , a [ len ( sub ) - 1 ] + maxScore ( s [ : head ] + s [ tail + 1 : ] , a ) ) NEW_LINE tail += 1 NEW_LINE DEDENT if tail == n : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT dp [ s ] = mx NEW_LINE return mx NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abb " NEW_LINE a = [ 1 , 3 , 1 ] NEW_LINE print ( maxScore ( s , a ) ) NEW_LINE DEDENT
Count all unique outcomes possible by performing S flips on N coins | Dimensions of the DP table ; Stores the dp states ; Function to recursively count the number of unique outcomes possible by performing S flips on N coins ; Base Case ; If the count for the current state is not calculated , then calculate it recursively ; Otherwise return the already calculated value ; Driver Code
size = 100 NEW_LINE ans = [ [ 0 for i in range ( size ) ] for j in range ( size ) ] NEW_LINE def numberOfUniqueOutcomes ( n , s ) : NEW_LINE INDENT if ( s < n ) : NEW_LINE INDENT ans [ n ] [ s ] = 0 ; NEW_LINE DEDENT elif ( n == 1 or n == s ) : NEW_LINE INDENT ans [ n ] [ s ] = 1 ; NEW_LINE DEDENT elif ( ans [ n ] [ s ] == 0 ) : NEW_LINE INDENT ans [ n ] [ s ] = ( numberOfUniqueOutcomes ( n - 1 , s - 1 ) + numberOfUniqueOutcomes ( n - 1 , s - 2 ) ) NEW_LINE DEDENT return ans [ n ] [ s ] ; NEW_LINE DEDENT N = 5 NEW_LINE S = 8 NEW_LINE print ( numberOfUniqueOutcomes ( N , S ) ) NEW_LINE
Minimize removals to remove another string as a subsequence of a given string | Function to print the minimum number of character removals required to remove X as a subsequence from the string str ; Length of the string str ; Length of the string X ; Stores the dp states ; Fill first row of dp [ ] [ ] ; If X [ j ] matches with str [ 0 ] ; If s [ i ] is equal to X [ j ] ; Update state after removing str [ i [ ; Update state after keeping str [ i ] ; If str [ i ] is not equal to X [ j ] ; Print the minimum number of characters removals ; Driver Code ; Input ; Function call to get minimum number of character removals
def printMinimumRemovals ( s , X ) : NEW_LINE INDENT N = len ( s ) NEW_LINE M = len ( X ) NEW_LINE dp = [ [ 0 for x in range ( M ) ] for y in range ( N ) ] NEW_LINE for j in range ( M ) : NEW_LINE INDENT if ( s [ 0 ] == X [ j ] ) : NEW_LINE INDENT dp [ 0 ] [ j ] = 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( s [ i ] == X [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + 1 NEW_LINE if ( j != 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT print ( dp [ N - 1 ] [ M - 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " btagd " NEW_LINE X = " bad " NEW_LINE printMinimumRemovals ( s , X ) NEW_LINE DEDENT
Railway Station | TCS CodeVita 2020 | Dp table for memoization ; Function to count the number of ways to N - th station ; Base Cases ; If current state is already evaluated ; Count ways in which train 1 can be chosen ; Count ways in which train 2 can be chosen ; Count ways in which train 3 can be chosen ; Store the current state ; Return the number of ways ; Driver Code ; Given Input ; Function call to count the number of ways to reach the n - th station
dp = [ - 1 for i in range ( 100000 ) ] NEW_LINE def findWays ( x ) : NEW_LINE INDENT if ( x < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( x == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( x == 1 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT if ( x == 2 ) : NEW_LINE INDENT return 4 NEW_LINE DEDENT if ( dp [ x ] != - 1 ) : NEW_LINE INDENT return dp [ x ] NEW_LINE DEDENT count = findWays ( x - 1 ) NEW_LINE count += findWays ( x - 2 ) NEW_LINE count += findWays ( x - 3 ) NEW_LINE dp [ x ] = count NEW_LINE return dp [ x ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE print ( findWays ( n ) ) NEW_LINE DEDENT
Maximum sum not exceeding K possible for any rectangle of a Matrix | Python3 program for the above approach ; Function to find the maximum possible sum of arectangle which is less than K ; Stores the values ( cum_sum - K ) ; Insert 0 into the set sumSet ; Traverse over the rows ; Get cumulative sum from [ 0 to i ] ; Search for upperbound of ( cSum - K ) in the hashmap ; If upper_bound of ( cSum - K ) exists , then update max sum ; Insert cummulative value in the hashmap ; Return the maximum sum which is less than K ; Function to find the maximum sum of rectangle such that its sum is no larger than K ; Stores the number of rows and columns ; Store the required result ; Set the left column ; Set the right column for the left column set by outer loop ; Calculate sum between the current left and right for every row ; Stores the sum of rectangle ; Update the overall maximum sum ; Print the result ; Driver Code ; Function Call
from bisect import bisect_left , bisect_right NEW_LINE import sys NEW_LINE def maxSubarraySum ( sum , k , row ) : NEW_LINE INDENT curSum , curMax = 0 , - sys . maxsize - 1 NEW_LINE sumSet = { } NEW_LINE sumSet [ 0 ] = 1 NEW_LINE for r in range ( row ) : NEW_LINE INDENT curSum += sum [ r ] NEW_LINE arr = list ( sumSet . keys ( ) ) NEW_LINE it = bisect_left ( arr , curSum - k ) NEW_LINE if ( it != len ( arr ) ) : NEW_LINE INDENT curMax = max ( curMax , curSum - it ) NEW_LINE DEDENT sumSet [ curSum ] = 1 NEW_LINE DEDENT return curMax NEW_LINE DEDENT def maxSumSubmatrix ( matrix , k ) : NEW_LINE INDENT row = len ( matrix ) NEW_LINE col = len ( matrix [ 0 ] ) NEW_LINE ret = - sys . maxsize - 1 NEW_LINE for i in range ( col ) : NEW_LINE INDENT sum = [ 0 ] * ( row ) NEW_LINE for j in range ( i , col ) : NEW_LINE INDENT for r in range ( row ) : NEW_LINE INDENT sum [ r ] += matrix [ r ] [ j ] NEW_LINE DEDENT curMax = maxSubarraySum ( sum , k , row ) NEW_LINE ret = max ( ret , curMax ) NEW_LINE DEDENT DEDENT print ( ret ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT matrix = [ [ 1 , 0 , 1 ] , [ 0 , - 2 , 3 ] ] NEW_LINE K = 2 NEW_LINE maxSumSubmatrix ( matrix , K ) NEW_LINE DEDENT
Count N | Function to count binary strings of length N having substring "11" ; Initialize dp [ ] of size N + 1 ; Base Cases ; Stores the first N powers of 2 ; Generate ; Iterate over the range [ 2 , N ] ; Prtotal count of substrings ; Driver Code
def binaryStrings ( N ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 1 ) NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = 0 NEW_LINE power = [ 0 ] * ( N + 1 ) NEW_LINE power [ 0 ] = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT power [ i ] = 2 * power [ i - 1 ] NEW_LINE DEDENT for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] + power [ i - 2 ] NEW_LINE DEDENT print ( dp [ N ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE binaryStrings ( N ) NEW_LINE DEDENT
Maximum sum submatrix | Python3 program for the above approach ; Function to find maximum continuous maximum sum in the array ; Stores current and maximum sum ; Traverse the array v ; Add the value of the current element ; Update the maximum sum ; Return the maximum sum ; Function to find the maximum submatrix sum ; Store the rows and columns of the matrix ; Create an auxiliary matrix Traverse the matrix , prefix and initialize it will all 0 s ; Calculate prefix sum of all rows of matrix A [ ] [ ] and store in matrix prefix [ ] ; Update the prefix [ ] [ ] ; Store the maximum submatrix sum ; Iterate for starting column ; Iterate for last column ; To store current array elements ; Traverse every row ; Store the sum of the kth row ; Update the prefix sum ; Push it in a vector ; Update the maximum overall sum ; Print the answer ; Driver Code ; Function Call
import sys NEW_LINE def kadane ( v ) : NEW_LINE INDENT currSum = 0 NEW_LINE maxSum = - sys . maxsize - 1 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT currSum += v [ i ] NEW_LINE if ( currSum > maxSum ) : NEW_LINE INDENT maxSum = currSum NEW_LINE DEDENT if ( currSum < 0 ) : NEW_LINE INDENT currSum = 0 NEW_LINE DEDENT DEDENT return maxSum NEW_LINE DEDENT def maxSubmatrixSum ( A ) : NEW_LINE INDENT r = len ( A ) NEW_LINE c = len ( A [ 0 ] ) NEW_LINE prefix = [ [ 0 for i in range ( c ) ] for j in range ( r ) ] NEW_LINE for i in range ( r ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT prefix [ i ] [ j ] = A [ i ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT prefix [ i ] [ j ] = A [ i ] [ j ] + prefix [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT maxSum = - sys . maxsize - 1 NEW_LINE for i in range ( c ) : NEW_LINE INDENT for j in range ( i , c ) : NEW_LINE INDENT v = [ ] NEW_LINE for k in range ( r ) : NEW_LINE INDENT el = 0 NEW_LINE if ( i == 0 ) : NEW_LINE INDENT el = prefix [ k ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT el = prefix [ k ] [ j ] - prefix [ k ] [ i - 1 ] NEW_LINE DEDENT v . append ( el ) NEW_LINE DEDENT maxSum = max ( maxSum , kadane ( v ) ) NEW_LINE DEDENT DEDENT print ( maxSum ) NEW_LINE DEDENT matrix = [ [ 0 , - 2 , - 7 , 0 ] , [ 9 , 2 , - 6 , 2 ] , [ - 4 , 1 , - 4 , 1 ] , [ - 1 , 8 , 0 , - 2 ] ] NEW_LINE maxSubmatrixSum ( matrix ) NEW_LINE
Minimize cost of painting N houses such that adjacent houses have different colors | Function to find the minimum cost of coloring the houses such that no two adjacent houses has the same color ; Corner Case ; Auxiliary 2D dp array ; Base Case ; If current house is colored with red the take min cost of previous houses colored with ( blue and green ) ; If current house is colored with blue the take min cost of previous houses colored with ( red and green ) ; If current house is colored with green the take min cost of previous houses colored with ( red and blue ) ; Print the min cost of the last painted house ; Driver Code ; Function Call
def minCost ( costs , N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT dp = [ [ 0 for i in range ( 3 ) ] for j in range ( 3 ) ] NEW_LINE dp [ 0 ] [ 0 ] = costs [ 0 ] [ 0 ] NEW_LINE dp [ 0 ] [ 1 ] = costs [ 0 ] [ 1 ] NEW_LINE dp [ 0 ] [ 2 ] = costs [ 0 ] [ 2 ] NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = min ( dp [ i - 1 ] [ 1 ] , dp [ i - 1 ] [ 2 ] ) + costs [ i ] [ 0 ] NEW_LINE dp [ i ] [ 1 ] = min ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 2 ] ) + costs [ i ] [ 1 ] NEW_LINE dp [ i ] [ 2 ] = min ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) + costs [ i ] [ 2 ] NEW_LINE DEDENT print ( min ( dp [ N - 1 ] [ 0 ] , min ( dp [ N - 1 ] [ 1 ] , dp [ N - 1 ] [ 2 ] ) ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT costs = [ [ 14 , 2 , 11 ] , [ 11 , 14 , 5 ] , [ 14 , 3 , 10 ] ] NEW_LINE N = len ( costs ) NEW_LINE minCost ( costs , N ) NEW_LINE DEDENT
Minimize count of flips required to make sum of the given array equal to 0 | Initialize dp [ ] [ ] ; Function to find the minimum number of operations to make sum of A [ ] 0 ; Initialize answer ; Base case ; Otherwise , return 0 ; Pre - computed subproblem ; Recurrence relation for finding the minimum of the sum of subsets ; Return the result ; Function to find the minimum number of elements required to be flipped to amke sum the array equal to 0 ; Find the sum of array ; Initialise dp [ ] [ ] with - 1 ; No solution exists ; Otherwise ; If sum is odd , no subset is possible ; Driver Code ; Function Call
dp = [ [ - 1 for i in range ( 2001 ) ] for j in range ( 2001 ) ] NEW_LINE def solve ( A , i , sum , N ) : NEW_LINE INDENT res = 2001 NEW_LINE if ( sum < 0 or ( i == N and sum != 0 ) ) : NEW_LINE INDENT return 2001 NEW_LINE DEDENT if ( sum == 0 or i >= N ) : NEW_LINE INDENT dp [ i ] [ sum ] = 0 NEW_LINE return 0 NEW_LINE DEDENT if ( dp [ i ] [ sum ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ sum ] NEW_LINE DEDENT res = min ( solve ( A , i + 1 , sum - A [ i ] , N ) + 1 , solve ( A , i + 1 , sum , N ) ) NEW_LINE dp [ i ] [ sum ] = res NEW_LINE return res NEW_LINE DEDENT def minOp ( A , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for it in A : NEW_LINE INDENT sum += it NEW_LINE DEDENT if ( sum % 2 == 0 ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( 2001 ) ] for j in range ( 2001 ) ] NEW_LINE ans = solve ( A , 0 , sum // 2 , N ) NEW_LINE if ( ans < 0 or ans > N ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT A = [ 2 , 3 , 1 , 4 ] NEW_LINE N = len ( A ) NEW_LINE minOp ( A , N ) NEW_LINE
Count subsequences having average of its elements equal to K | Stores the dp states ; Function to find the count of subsequences having average K ; Base condition ; Three loops for three states ; Recurrence relation ; Stores the sum of dp [ n ] [ j ] [ K * j ] all possible values of j with average K and sum K * j ; Iterate over the range [ 1 , N ] ; Return the final count ; Driver Code
dp = [ [ [ 0 for i in range ( 1001 ) ] for i in range ( 101 ) ] for i in range ( 101 ) ] NEW_LINE def countAverage ( n , K , arr ) : NEW_LINE INDENT global dp NEW_LINE dp [ 0 ] [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for k in range ( n ) : NEW_LINE INDENT for s in range ( 100 ) : NEW_LINE INDENT dp [ i + 1 ] [ k + 1 ] [ s + arr [ i ] ] += dp [ i ] [ k ] [ s ] NEW_LINE dp [ i + 1 ] [ k ] [ s ] += dp [ i ] [ k ] [ s ] NEW_LINE DEDENT DEDENT DEDENT cnt = 0 NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT cnt += dp [ n ] [ j ] [ K * j ] NEW_LINE DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 7 , 8 , 9 ] NEW_LINE K = 8 NEW_LINE N = len ( arr ) NEW_LINE print ( countAverage ( N , K , arr ) ) NEW_LINE DEDENT
Count ways to remove pairs from a matrix such that remaining elements can be grouped in vertical or horizontal pairs | Function to count ways to remove pairs such that the remaining elements can be arranged in pairs vertically or horizontally ; Store the size of matrix ; If N is odd , then no such pair exists ; Store the number of required pairs ; Initialize an auxiliary matrix and fill it with 0 s ; Traverse the matrix v [ ] [ ] ; Check if i + j is odd or even ; Increment the value dp [ v [ i ] [ j ] - 1 ] [ 0 ] by 1 ; Increment the value dp [ v [ i ] [ j ] - 1 ] [ 1 ] by 1 ; Iterate in range [ 0 , k - 1 ] using i ; Iterate in range [ i + 1 , k - 1 ] using j ; Update the ans ; Print the answer ; Driver code
def numberofpairs ( v , k ) : NEW_LINE INDENT n = len ( v ) NEW_LINE if ( n % 2 == 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT ans = 0 NEW_LINE dp = [ [ 0 for i in range ( 2 ) ] for j in range ( k ) ] NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ( i + j ) % 2 == 0 ) : NEW_LINE INDENT dp [ v [ i ] [ j ] - 1 ] [ 0 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ v [ i ] [ j ] - 1 ] [ 1 ] += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( k ) : NEW_LINE INDENT for j in range ( i + 1 , k ) : NEW_LINE INDENT ans += dp [ i ] [ 0 ] * dp [ j ] [ 1 ] NEW_LINE ans += dp [ i ] [ 1 ] * dp [ j ] [ 0 ] NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT mat = [ [ 1 , 2 ] , [ 3 , 4 ] ] NEW_LINE K = 4 NEW_LINE numberofpairs ( mat , K ) NEW_LINE
Maximize sum by selecting X different | Python3 program for the above approach ; Store overlapping subproblems of the recurrence relation ; Function to find maximum sum of at most N with different index array elements such that at most X are from A [ ] , Y are from B [ ] and Z are from C [ ] ; Base Cases ; If the subproblem already computed ; Selecting i - th element from A [ ] ; Selecting i - th element from B [ ] ; Selecting i - th element from C [ ] ; i - th elements not selected from any of the arrays ; Select the maximum sum from all the possible calls ; Driver Code ; Given X , Y and Z ; Given A [ ] ; Given B [ ] ; Given C [ ] ; Given Size ; Function Call
import sys NEW_LINE dp = [ [ [ [ - 1 for i in range ( 50 ) ] for j in range ( 50 ) ] for k in range ( 50 ) ] for l in range ( 50 ) ] NEW_LINE def FindMaxS ( X , Y , Z , n , A , B , C ) : NEW_LINE INDENT if ( X < 0 or Y < 0 or Z < 0 ) : NEW_LINE INDENT return - sys . maxsize - 1 NEW_LINE DEDENT if ( n < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ n ] [ X ] [ Y ] [ Z ] != - 1 ) : NEW_LINE INDENT return dp [ n ] [ X ] [ Y ] [ Z ] NEW_LINE DEDENT ch = A [ n ] + FindMaxS ( X - 1 , Y , Z , n - 1 , A , B , C ) NEW_LINE ca = B [ n ] + FindMaxS ( X , Y - 1 , Z , n - 1 , A , B , C ) NEW_LINE co = C [ n ] + FindMaxS ( X , Y , Z - 1 , n - 1 , A , B , C ) NEW_LINE no = FindMaxS ( X , Y , Z , n - 1 , A , B , C ) NEW_LINE maximum = max ( ch , max ( ca , max ( co , no ) ) ) NEW_LINE dp [ n ] [ X ] [ Y ] [ Z ] = maximum NEW_LINE return dp [ n ] [ X ] [ Y ] [ Z ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 1 NEW_LINE Y = 1 NEW_LINE Z = 1 NEW_LINE A = [ 10 , 0 , 5 ] NEW_LINE B = [ 5 , 10 , 0 ] NEW_LINE C = [ 0 , 5 , 10 ] NEW_LINE n = len ( B ) NEW_LINE print ( FindMaxS ( X , Y , Z , n - 1 , A , B , C ) ) NEW_LINE DEDENT
Minimize swaps of adjacent characters to sort every possible rearrangement of given Binary String | Python3 program for the above approach ; Precalculate the values of power of 2 ; Function to calculate 2 ^ N % mod ; Function to find sum of inversions ; Initialise a list of 0 s and ? s ; Traverse the string in the reversed manner ; If the current character is 1 ; Effectively calculate a * b ^ ( b - 1 ) ; If the current character is 0 ; Increment count of zeroes ; Double count the zeroes ; Find b * 2 ^ ( b - 1 ) ; Increment count of questions ; Return the final count ; Driver Code ; Given string S ; Function Call
MOD = 10 ** 9 + 7 NEW_LINE MEM = [ 1 , 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 , 512 , 1024 , 2048 , 4096 ] NEW_LINE def mod_pow2 ( n ) : NEW_LINE INDENT while n >= len ( MEM ) : NEW_LINE INDENT MEM . append ( ( MEM [ - 1 ] * 2 ) % MOD ) NEW_LINE DEDENT return MEM [ n ] NEW_LINE DEDENT def inversions ( bstr ) : NEW_LINE INDENT total , zeros , questions = ( 0 , ) * 3 NEW_LINE for x in reversed ( bstr ) : NEW_LINE INDENT if x == '1' : NEW_LINE INDENT z = zeros * mod_pow2 ( questions ) NEW_LINE if questions == 0 : NEW_LINE INDENT q = 0 NEW_LINE DEDENT else : NEW_LINE INDENT q = questions * mod_pow2 ( questions - 1 ) NEW_LINE DEDENT total = ( total + z + q ) % MOD NEW_LINE DEDENT elif x == '0' : NEW_LINE INDENT zeros += 1 NEW_LINE DEDENT else : NEW_LINE INDENT total *= 2 NEW_LINE z = zeros * mod_pow2 ( questions ) NEW_LINE if questions == 0 : NEW_LINE INDENT q = 0 NEW_LINE DEDENT else : NEW_LINE INDENT q = questions * mod_pow2 ( questions - 1 ) NEW_LINE DEDENT total = ( total + z + q ) % MOD NEW_LINE questions += 1 NEW_LINE DEDENT DEDENT return total NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT S = " ? 0 ? " NEW_LINE print ( inversions ( S ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Minimum removals required to convert given array to a Mountain Array | Utility function to count array elements required to be removed to make array a mountain array ; Stores length of increasing subsequence from [ 0 , i - 1 ] ; Stores length of increasing subsequence from [ i + 1 , n - 1 ] ; Iterate for each position up to N - 1 to find the length of subsequence ; If j is less than i , then i - th position has leftIncreasing [ j ] + 1 lesser elements including itself ; Check if it is the maximum obtained so far ; Search for increasing subsequence from right ; Find the position following the peak condition and have maximum leftIncreasing [ i ] + rightIncreasing [ i ] ; Function to count elements to be removed to make array a mountain array ; Print the answer ; Driver Code ; Given array ; Function Call
def minRemovalsUtil ( arr ) : NEW_LINE INDENT result = 0 NEW_LINE if ( len ( arr ) < 3 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT leftIncreasing = [ 0 ] * len ( arr ) NEW_LINE rightIncreasing = [ 0 ] * len ( arr ) NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( arr [ j ] < arr [ i ] ) : NEW_LINE INDENT leftIncreasing [ i ] = max ( leftIncreasing [ i ] , leftIncreasing [ j ] + 1 ) ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( len ( arr ) - 2 , - 1 , - 1 ) : NEW_LINE INDENT j = len ( arr ) - 1 NEW_LINE while j > i : NEW_LINE INDENT if ( arr [ j ] < arr [ i ] ) : NEW_LINE INDENT rightIncreasing [ i ] = max ( rightIncreasing [ i ] , rightIncreasing [ j ] + 1 ) NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT DEDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( leftIncreasing [ i ] != 0 and rightIncreasing [ i ] != 0 ) : NEW_LINE INDENT result = max ( result , leftIncreasing [ i ] + rightIncreasing [ i ] ) ; NEW_LINE DEDENT DEDENT return len ( arr ) - ( result + 1 ) NEW_LINE DEDENT def minRemovals ( arr ) : NEW_LINE INDENT ans = minRemovalsUtil ( arr ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 1 , 1 , 5 , 6 , 2 , 3 , 1 ] NEW_LINE minRemovals ( arr ) NEW_LINE DEDENT
Minimum number of jumps to obtain an element of opposite parity | Bfs for odd numbers are source ; Initialize queue ; Stores for each node , the nodes visited and their distances ; If parity is 0 -> odd Otherwise -> even ; Perform multi - source bfs ; Extract the front element of the queue ; Traverse nodes connected to the current node ; If u is not visited ; If element with opposite parity is obtained ; Store its distance from source in ans [ ] ; Push the current neighbour to the queue ; Function to find the minimum jumps required by each index to reach element of opposite parity ; Initialise Inverse Graph ; Stores the result for each index ; For the jumped index ; If the ind is valid then add reverse directed edge ; Multi - source bfs with odd numbers as source by passing 0 ; Multi - source bfs with even numbers as source by passing 1 ; Print the answer ; Driver Code
def bfs ( n , a , invGr , ans , parity ) : NEW_LINE INDENT q = [ ] NEW_LINE vis = [ 0 for i in range ( n + 1 ) ] NEW_LINE dist = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( ( a [ i ] + parity ) & 1 ) : NEW_LINE INDENT q . append ( i ) NEW_LINE vis [ i ] = 1 NEW_LINE DEDENT DEDENT while ( len ( q ) != 0 ) : NEW_LINE INDENT v = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE for u in invGr [ v ] : NEW_LINE INDENT if ( not vis [ u ] ) : NEW_LINE INDENT dist [ u ] = dist [ v ] + 1 NEW_LINE vis [ u ] = 1 NEW_LINE if ( ( a [ u ] + parity ) % 2 == 0 ) : NEW_LINE INDENT if ( ans [ u ] == - 1 ) : NEW_LINE INDENT ans [ u ] = dist [ u ] NEW_LINE DEDENT DEDENT q . append ( u ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def minJumps ( a , jump , n ) : NEW_LINE INDENT invGr = [ [ ] for i in range ( n + 1 ) ] NEW_LINE ans = [ - 1 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for ind in [ i + jump [ i ] , i - jump [ i ] ] : NEW_LINE INDENT if ( ind >= 1 and ind <= n ) : NEW_LINE INDENT invGr [ ind ] . append ( i ) NEW_LINE DEDENT DEDENT DEDENT bfs ( n , a , invGr , ans , 0 ) NEW_LINE bfs ( n , a , invGr , ans , 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( str ( ans [ i ] ) , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 4 , 2 , 5 , 2 , 1 ] NEW_LINE jump = [ 0 , 1 , 2 , 3 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE minJumps ( arr , jump , N - 1 ) NEW_LINE DEDENT
Longest subsequence having maximum GCD between any pair of distinct elements | Python3 program for the above approach ; Function to find GCD of pair with maximum GCD ; Stores maximum element of arr [ ] ; Find the maximum element ; Maintain a count array ; Store the frequency of arr [ ] ; Stores the multiples of a number ; Iterate over the range [ MAX , 1 ] ; Iterate from current potential GCD till it is less than MAX ; A multiple found ; Increment potential GCD by itself io check i , 2 i , 3 i ... ; If 2 multiples found max GCD found ; Function to find longest subsequence such that GCD of any two distinct integers is maximum ; Base Cases ; Compare current GCD to the maximum GCD ; If true increment and move the pointer ; Return max of either subsequences ; Drivers Code ; Sorted array ; Function call to calculate GCD of pair with maximum GCD ; Print the result
import math NEW_LINE def findMaxGCD ( arr , N ) : NEW_LINE INDENT high = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT high = max ( high , arr [ i ] ) NEW_LINE DEDENT count = [ 0 ] * ( high + 1 ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT counter = 0 NEW_LINE for i in range ( high , 0 , - 1 ) : NEW_LINE INDENT j = i NEW_LINE while ( j <= high ) : NEW_LINE INDENT if ( count [ j ] > 0 ) : NEW_LINE INDENT counter += count [ j ] NEW_LINE DEDENT j += i NEW_LINE if ( counter == 2 ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT counter = 0 NEW_LINE DEDENT DEDENT def maxlen ( i , j ) : NEW_LINE INDENT a = 0 NEW_LINE if i >= N or j >= N : NEW_LINE INDENT return 0 NEW_LINE DEDENT if math . gcd ( arr [ i ] , arr1 [ j ] ) == maxgcd and arr [ i ] != arr1 [ j ] : NEW_LINE INDENT a = max ( a , 1 + maxlen ( i , j + 1 ) ) NEW_LINE return a NEW_LINE DEDENT return max ( maxlen ( i + 1 , j ) , maxlen ( i , j + 1 ) ) NEW_LINE DEDENT arr = [ 1 , 2 , 8 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE arr1 = sorted ( arr ) NEW_LINE maxgcd = findMaxGCD ( arr , N ) NEW_LINE print ( maxlen ( 0 , 0 ) ) NEW_LINE
Count unique paths is a matrix whose product of elements contains odd number of divisors | Python3 program for the above approach ; Stores the results ; Count of unique product paths ; Function to check whether number is perfect square or not ; If square root is an integer ; Function to calculate and store all the paths product in vector ; Store the value a [ 0 ] [ 0 ] ; Initialize first row of dp ; Find prefix product ; Initialize first column of dp ; Find the prefix product ; Iterate over range ( 1 , 1 ) to ( N , M ) ; Copy dp [ i - 1 ] [ j ] in top [ ] ; Copy dp [ i ] [ j - 1 ] into left [ ] ; Compute the values of current state and store it in curr [ ] ; Find the product of a [ i ] [ j ] with elements at top [ ] ; Find the product of a [ i ] [ j ] with elements at left [ ] ; Update the current state ; Traverse dp [ m - 1 ] [ n - 1 ] ; Check if perfect square ; Driver Code ; Given matrix mat [ ] [ ] ; Function Call ; Print the final count
from math import sqrt , floor NEW_LINE dp = [ [ [ ] for j in range ( 105 ) ] for k in range ( 105 ) ] NEW_LINE countPaths = 0 NEW_LINE def isPerfectSquare ( n ) : NEW_LINE INDENT sr = sqrt ( n ) NEW_LINE return ( ( sr - floor ( sr ) ) == 0 ) NEW_LINE DEDENT def countUniquePaths ( a , m , n , ans ) : NEW_LINE INDENT global dp NEW_LINE global countPaths NEW_LINE dp [ 0 ] [ 0 ] . append ( a [ 0 ] [ 0 ] ) NEW_LINE for i in range ( 1 , m ) : NEW_LINE INDENT a [ i ] [ 0 ] *= a [ i - 1 ] [ 0 ] NEW_LINE dp [ i ] [ 0 ] . append ( a [ i ] [ 0 ] ) NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT a [ 0 ] [ i ] *= a [ 0 ] [ i - 1 ] NEW_LINE dp [ 0 ] [ i ] . append ( a [ 0 ] [ i ] ) NEW_LINE DEDENT for i in range ( 1 , m ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE INDENT top = dp [ i - 1 ] [ j ] NEW_LINE left = dp [ i ] [ j - 1 ] NEW_LINE curr = [ ] NEW_LINE for k in range ( len ( top ) ) : NEW_LINE INDENT curr . append ( top [ k ] * a [ i ] [ j ] ) NEW_LINE DEDENT for k in range ( len ( left ) ) : NEW_LINE INDENT curr . append ( left [ k ] * a [ i ] [ j ] ) NEW_LINE DEDENT dp [ i ] [ j ] = curr NEW_LINE DEDENT DEDENT for i in dp [ m - 1 ] [ n - 1 ] : NEW_LINE INDENT if ( isPerfectSquare ( i ) ) : NEW_LINE INDENT countPaths += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = 3 NEW_LINE N = 4 NEW_LINE mat = [ [ 1 , 2 , 3 , 1 ] , [ 3 , 1 , 2 , 4 ] , [ 2 , 3 , 1 , 1 ] ] NEW_LINE countUniquePaths ( mat , M , N , 1 ) NEW_LINE print ( countPaths ) NEW_LINE DEDENT
Generate a combination of minimum coins that sums to a given value | Python3 program for the above approach ; dp array to memoize the results ; List to store the result ; Function to find the minimum number of coins to make the sum equals to X ; Base case ; If previously computed subproblem occurred ; Initialize result ; Try every coin that has smaller value than n ; Check for INT_MAX to avoid overflow and see if result . an be minimized ; Memoizing value of current state ; Function to find the possible combination of coins to make the sum equal to X ; Base Case ; Print Solutions ; Try every coin that has value smaller than n ; Add current denominations ; Backtrack ; Function to find the minimum combinations of coins for value X ; Min coins ; If no solution exists ; Backtrack to find the solution ; Driver code ; Set of possible denominations ; Function call
import sys NEW_LINE MAX = 100000 NEW_LINE dp = [ - 1 ] * ( MAX + 1 ) NEW_LINE denomination = [ ] NEW_LINE def countMinCoins ( n , C , m ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT dp [ 0 ] = 0 NEW_LINE return 0 NEW_LINE DEDENT if ( dp [ n ] != - 1 ) : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT ret = sys . maxsize NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( C [ i ] <= n ) : NEW_LINE INDENT x = countMinCoins ( n - C [ i ] , C , m ) NEW_LINE if ( x != sys . maxsize ) : NEW_LINE INDENT ret = min ( ret , 1 + x ) NEW_LINE DEDENT DEDENT DEDENT dp [ n ] = ret NEW_LINE return ret NEW_LINE DEDENT def findSolution ( n , C , m ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT for it in denomination : NEW_LINE INDENT print ( it , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT if ( n - C [ i ] >= 0 and dp [ n - C [ i ] ] + 1 == dp [ n ] ) : NEW_LINE INDENT denomination . append ( C [ i ] ) NEW_LINE findSolution ( n - C [ i ] , C , m ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT def countMinCoinsUtil ( X , C , N ) : NEW_LINE INDENT isPossible = countMinCoins ( X , C , N ) NEW_LINE if ( isPossible == sys . maxsize ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT findSolution ( X , C , N ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 21 NEW_LINE arr = [ 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE countMinCoinsUtil ( X , arr , N ) NEW_LINE DEDENT
Count all possible paths from top left to bottom right of a Matrix without crossing the diagonal | Function to calculate Binomial Coefficient C ( n , r ) ; C ( n , r ) = C ( n , n - r ) ; [ n * ( n - 1 ) * -- - * ( n - r + 1 ) ] / [ r * ( r - 1 ) * -- -- * 1 ] ; Function to calculate the total possible paths ; Update n to n - 1 ; Stores 2 nCn ; Stores Nth Catalan number ; Stores the required answer ; Driver Code
def binCoff ( n , r ) : NEW_LINE INDENT val = 1 NEW_LINE if ( r > ( n - r ) ) : NEW_LINE INDENT r = ( n - r ) NEW_LINE DEDENT for i in range ( r ) : NEW_LINE INDENT val *= ( n - i ) NEW_LINE val //= ( i + 1 ) NEW_LINE DEDENT return val NEW_LINE DEDENT def findWays ( n ) : NEW_LINE INDENT n = n - 1 NEW_LINE a = binCoff ( 2 * n , n ) NEW_LINE b = a // ( n + 1 ) NEW_LINE ans = b NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE print ( findWays ( n ) ) NEW_LINE DEDENT
Minimum operations to transform given string to another by moving characters to front or end | Python3 program for the above approach ; Function that finds the minimum number of steps to find the minimum characters must be moved to convert string s to t ; r = maximum value over all dp [ i ] [ j ] computed so far ; dp [ i ] [ j ] stores the longest contiguous suffix of T [ 0. . j ] that is subsequence of S [ 0. . i ] ; Update the maximum length ; Return the resulting length ; Given string s , t ; Function call
dp = [ [ 0 ] * 1010 ] * 1010 NEW_LINE def solve ( s , t ) : NEW_LINE INDENT n = len ( s ) NEW_LINE r = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE if ( i > 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j ] ) NEW_LINE DEDENT if ( s [ i ] == t [ j ] ) : NEW_LINE INDENT ans = 1 NEW_LINE if ( i > 0 and j > 0 ) : NEW_LINE INDENT ans = 1 + dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , ans ) NEW_LINE r = max ( r , dp [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return ( n - r ) NEW_LINE DEDENT s = " abcde " NEW_LINE t = " edacb " NEW_LINE print ( solve ( s , t ) ) NEW_LINE
Longest substring whose characters can be rearranged to form a Palindrome | Function to get the length of longest substring whose characters can be arranged to form a palindromic string ; To keep track of the last index of each xor ; Initialize answer with 0 ; Now iterate through each character of the string ; Convert the character from [ a , z ] to [ 0 , 25 ] ; Turn the temp - th bit on if character occurs odd number of times and turn off the temp - th bit off if the character occurs ever number of times ; If a mask is present in the index Therefore a palindrome is found from index [ mask ] to i ; If x is not found then add its position in the index dict . ; Check for the palindrome of odd length ; We cancel the occurrence of a character if it occurs odd number times ; Given String ; Length of given string ; Function call
def longestSubstring ( s : str , n : int ) : NEW_LINE INDENT index = dict ( ) NEW_LINE answer = 0 NEW_LINE mask = 0 NEW_LINE index [ mask ] = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = ord ( s [ i ] ) - 97 NEW_LINE mask ^= ( 1 << temp ) NEW_LINE if mask in index . keys ( ) : NEW_LINE INDENT answer = max ( answer , i - index [ mask ] ) NEW_LINE DEDENT else : NEW_LINE INDENT index [ mask ] = i NEW_LINE DEDENT for j in range ( 26 ) : NEW_LINE INDENT mask2 = mask ^ ( 1 << j ) NEW_LINE if mask2 in index . keys ( ) : NEW_LINE INDENT answer = max ( answer , i - index [ mask2 ] ) NEW_LINE DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT s = " adbabd " NEW_LINE n = len ( s ) NEW_LINE print ( longestSubstring ( s , n ) ) NEW_LINE
Count of N | Function to find count of N - digit numbers with single digit XOR ; dp [ i ] [ j ] stores the number of i - digit numbers with XOR equal to j ; For 1 - 9 store the value ; Iterate till N ; Calculate XOR ; Store in DP table ; Initialize count ; Print answer ; Driver Code ; Given number N ; Function Call
def countNums ( N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 16 ) ] for j in range ( N ) ] ; NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 ; NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 0 , 10 ) : NEW_LINE INDENT for k in range ( 0 , 16 ) : NEW_LINE INDENT xor = j ^ k ; NEW_LINE dp [ i ] [ xor ] += dp [ i - 1 ] [ k ] ; NEW_LINE DEDENT DEDENT DEDENT count = 0 ; NEW_LINE for i in range ( 0 , 10 ) : NEW_LINE INDENT count += dp [ N - 1 ] [ i ] ; NEW_LINE DEDENT print ( count ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 1 ; NEW_LINE countNums ( N ) ; NEW_LINE DEDENT
Count of numbers upto M divisible by given Prime Numbers | Function to count the numbers that are divisible by the numbers in the array from range 1 to M ; Initialize the count variable ; Iterate over [ 1 , M ] ; Iterate over array elements arr [ ] ; Check if i is divisible by a [ j ] ; Increment the count ; Return the answer ; Given list lst ; Given number M ; Function call
def count ( a , M , N ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( 1 , M + 1 ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( i % a [ j ] == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT lst = [ 2 , 3 , 5 , 7 ] NEW_LINE m = 100 NEW_LINE n = len ( lst ) NEW_LINE print ( count ( lst , m , n ) ) NEW_LINE
Count of numbers upto N digits formed using digits 0 to K | Python3 implementation to count the numbers upto N digits such that no two zeros are adjacent ; Function to count the numbers upto N digits such that no two zeros are adjacent ; Condition to check if only one element remains ; If last element is non zero , return K - 1 ; If last element is 0 ; Condition to check if value calculated already ; If last element is non zero , then two cases arise , current element can be either zero or non zero ; Memoize this case ; If last is 0 , then current can only be non zero ; Memoize and return ; Given N and K ; Function call
dp = [ [ 0 ] * 10 for j in range ( 15 ) ] NEW_LINE def solve ( n , last , k ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT if ( last == k ) : NEW_LINE INDENT return ( k - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT if ( dp [ n ] [ last ] ) : NEW_LINE INDENT return dp [ n ] [ last ] NEW_LINE DEDENT if ( last == k ) : NEW_LINE INDENT dp [ n ] [ last ] = ( ( k - 1 ) * solve ( n - 1 , k , k ) + ( k - 1 ) * solve ( n - 1 , 1 , k ) ) NEW_LINE return dp [ n ] [ last ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ n ] [ last ] = solve ( n - 1 , k , k ) NEW_LINE return dp [ n ] [ last ] NEW_LINE DEDENT DEDENT n = 2 NEW_LINE k = 3 NEW_LINE x = solve ( n , k , k ) + solve ( n , 1 , k ) NEW_LINE print ( x ) NEW_LINE
Count of occurrences of each prefix in a string using modified KMP algorithm | Function to print the count of all prefix in the given string ; Iterate over string s ; Print the prefix and their frequency ; Function to implement the LPS array to store the longest prefix which is also a suffix for every substring of the string S ; Array to store LPS values Value of lps [ 0 ] is 0 by definition ; Find the values of LPS [ i ] for the rest of the string using two pointers and DP ; Initially set the value of j as the longest prefix that is also a suffix for i as LPS [ i - 1 ] ; Check if the suffix of length j + 1 is also a prefix ; If s [ i ] = s [ j ] then , assign LPS [ i ] as j + 1 ; If we reached j = 0 , assign LPS [ i ] as 0 as there was no prefix equal to suffix ; Return the calculated LPS array ; Function to count the occurrence of all the prefix in the string S ; Call the prefix_function to get LPS ; To store the occurrence of all the prefix ; Count all the suffixes that are also prefix ; Add the occurences of i to smaller prefixes ; Adding 1 to all occ [ i ] for all the orignal prefix ; Function Call to print the occurence of all the prefix ; Given String ; Function Call
def Print ( occ , s ) : NEW_LINE INDENT for i in range ( 1 , len ( s ) + 1 ) : NEW_LINE INDENT print ( s [ 0 : i ] , " occur " , occ [ i ] , " times . " ) NEW_LINE DEDENT DEDENT def prefix_function ( s ) : NEW_LINE INDENT LPS = [ 0 for i in range ( len ( s ) ) ] NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT j = LPS [ i - 1 ] NEW_LINE while ( j > 0 and s [ i ] != s [ j ] ) : NEW_LINE INDENT j = LPS [ j - 1 ] NEW_LINE DEDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT LPS [ i ] = j + 1 NEW_LINE DEDENT else : NEW_LINE INDENT LPS [ i ] = 0 NEW_LINE DEDENT DEDENT return LPS NEW_LINE DEDENT def count_occurence ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE LPS = prefix_function ( s ) NEW_LINE occ = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT occ [ LPS [ i ] ] += 1 NEW_LINE DEDENT for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT occ [ LPS [ i - 1 ] ] += occ [ i ] NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT occ [ i ] += 1 NEW_LINE DEDENT Print ( occ , s ) NEW_LINE DEDENT A = " ABACABA " NEW_LINE count_occurence ( A ) NEW_LINE
Maximum sum by picking elements from two arrays in order | Set 2 | Function to calculate maximum sum ; Maximum elements that can be chosen from array A ; Maximum elements that can be chosen from array B ; Stores the maximum sum possible ; Fill the dp [ ] for base case when all elements are selected from A [ ] ; Fill the dp [ ] for base case when all elements are selected from B [ ] ; Return the final answer ; Driver Program
def maximumSum ( A , B , length , X , Y ) : NEW_LINE INDENT l = length NEW_LINE l1 = min ( length , X ) NEW_LINE l2 = min ( length , Y ) NEW_LINE dp = [ [ 0 for i in range ( l2 + 1 ) ] for i in range ( l1 + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 0 NEW_LINE max_sum = - 10 * 9 NEW_LINE for i in range ( 1 , l1 + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + A [ i - 1 ] NEW_LINE max_sum = max ( max_sum , dp [ i ] [ 0 ] ) NEW_LINE DEDENT for i in range ( 1 , l2 + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + B [ i - 1 ] NEW_LINE max_sum = max ( max_sum , dp [ 0 ] [ i ] ) NEW_LINE DEDENT for i in range ( 1 , l1 + 1 ) : NEW_LINE INDENT for j in range ( 1 , l2 + 1 ) : NEW_LINE INDENT if ( i + j <= l ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] + A [ i + j - 1 ] , dp [ i ] [ j - 1 ] + B [ i + j - 1 ] ) NEW_LINE DEDENT max_sum = max ( dp [ i ] [ j ] , max_sum ) NEW_LINE DEDENT DEDENT return max_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE B = [ 5 , 4 , 3 , 2 , 1 ] NEW_LINE X = 3 NEW_LINE Y = 2 NEW_LINE N = len ( A ) NEW_LINE print ( maximumSum ( A , B , N , X , Y ) ) NEW_LINE DEDENT
Min number of operations to reduce N to 0 by subtracting any digits from N | Function to reduce an integer N to Zero in minimum operations by removing digits from N ; Initialise dp [ ] to steps ; Iterate for all elements ; For each digit in number i ; Either select the number or do not select it ; dp [ N ] will give minimum step for N ; Given Number ; Function Call
def reduceZero ( N ) : NEW_LINE INDENT dp = [ 1e9 for i in range ( N + 1 ) ] NEW_LINE dp [ 0 ] = 0 NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT for c in str ( i ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , dp [ i - ( ord ( c ) - 48 ) ] + 1 ) NEW_LINE DEDENT DEDENT return dp [ N ] NEW_LINE DEDENT N = 25 NEW_LINE print ( reduceZero ( N ) ) NEW_LINE
Pentanacci Numbers | Function to print Nth Pentanacci number ; Initialize first five numbers to base cases ; declare a current variable ; Loop to add previous five numbers for each number starting from 5 and then assign first , second , third , fourth to second , third , fourth and curr to fifth respectively ; Driver code
def printpenta ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT first = 0 NEW_LINE second = 0 NEW_LINE third = 0 NEW_LINE fourth = 0 NEW_LINE fifth = 1 NEW_LINE curr = 0 NEW_LINE if ( n == 0 or n == 1 or \ n == 2 or n == 3 ) : NEW_LINE INDENT print ( first ) NEW_LINE DEDENT elif ( n == 5 ) : NEW_LINE INDENT print ( fifth ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 5 , n ) : NEW_LINE INDENT curr = first + second + third + fourth + fifth NEW_LINE first = second NEW_LINE second = third NEW_LINE third = fourth NEW_LINE fourth = fifth NEW_LINE fifth = curr NEW_LINE DEDENT DEDENT print ( curr ) NEW_LINE DEDENT n = 10 NEW_LINE printpenta ( n ) NEW_LINE
Count of binary strings of length N with even set bit count and at most K consecutive 1 s | Python3 program for the above approach ; Table to store solution of each subproblem ; Function to calculate the possible binary strings ; If number of ones is equal to K ; pos : current position Base Case : When n length is traversed ; sum : count of 1 ' s ▁ ▁ Return ▁ the ▁ count ▁ ▁ of ▁ 1' s obtained ; If the subproblem has already been solved ; Return the answer ; Recursive call when current position is filled with 1 ; Recursive call when current position is filled with 0 ; Store the solution to this subproblem ; Driver Code ; Initialising the table with - 1
import numpy as np NEW_LINE dp = np . ones ( ( ( 100002 , 21 , 3 ) ) ) NEW_LINE dp = - 1 * dp NEW_LINE def possibleBinaries ( pos , ones , sum , k ) : NEW_LINE INDENT if ( ones == k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( pos == 0 ) : NEW_LINE INDENT return 1 if ( sum == 0 ) else 0 NEW_LINE DEDENT if ( dp [ pos ] [ ones ] [ sum ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ ones ] [ sum ] NEW_LINE DEDENT ret = ( possibleBinaries ( pos - 1 , ones + 1 , ( sum + 1 ) % 2 , k ) + possibleBinaries ( pos - 1 , 0 , sum , k ) ) NEW_LINE dp [ pos ] [ ones ] [ sum ] = ret NEW_LINE return dp [ pos ] [ ones ] [ sum ] NEW_LINE DEDENT N = 3 NEW_LINE K = 2 NEW_LINE print ( int ( possibleBinaries ( N , 0 , 0 , K ) ) ) NEW_LINE
Sum of absolute difference of all pairs raised to power K | Python3 program for the above approach ; Since K can be 100 max ; Initializing with - 1 ; Making vector A as 1 - Indexing ; To Calculate the value nCk ; Since nCj = ( n - 1 ) Cj + ( n - 1 ) C ( j - 1 ) ; ; Function that summation of absolute differences of all pairs raised to the power k ; Sort the given array ; Precomputation part , O ( n * k ) ; Traverse the array arr [ ] ; For each K ; Return the final answer ; Driver code ; Given N and K ; Given array ; Creation of object of class ; Function call
class Solution : NEW_LINE INDENT def __init__ ( self , N , K , B ) : NEW_LINE INDENT self . ncr = [ ] NEW_LINE for i in range ( 101 ) : NEW_LINE INDENT temp = [ ] NEW_LINE for j in range ( 101 ) : NEW_LINE INDENT temp . append ( - 1 ) NEW_LINE DEDENT self . ncr . append ( temp ) NEW_LINE DEDENT self . n = N NEW_LINE self . k = K NEW_LINE self . A = [ 0 ] + B NEW_LINE DEDENT def f ( self , n , k ) : NEW_LINE INDENT if k == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n == k : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n < k : NEW_LINE INDENT return 0 NEW_LINE DEDENT if self . ncr [ n ] [ k ] != - 1 : NEW_LINE INDENT return self . ncr [ n ] [ k ] NEW_LINE DEDENT self . ncr [ n ] [ k ] = ( self . f ( n - 1 , k ) + self . f ( n - 1 , k - 1 ) ) NEW_LINE return self . ncr [ n ] [ k ] NEW_LINE DEDENT def pairsPower ( self ) : NEW_LINE INDENT pre = [ ] NEW_LINE for i in range ( self . n + 1 ) : NEW_LINE INDENT temp = [ ] NEW_LINE for j in range ( self . k + 1 ) : NEW_LINE INDENT temp . append ( 0 ) NEW_LINE DEDENT pre . append ( temp ) NEW_LINE DEDENT ans = 0 NEW_LINE self . A . sort ( ) NEW_LINE for i in range ( 1 , self . n + 1 ) : NEW_LINE INDENT pre [ i ] [ 0 ] = 1 NEW_LINE for j in range ( 1 , self . k + 1 ) : NEW_LINE INDENT pre [ i ] [ j ] = ( self . A [ i ] * pre [ i ] [ j - 1 ] ) NEW_LINE DEDENT if i != 1 : NEW_LINE INDENT for j in range ( self . k + 1 ) : NEW_LINE INDENT pre [ i ] [ j ] = ( pre [ i ] [ j ] + pre [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( self . n , 1 , - 1 ) : NEW_LINE INDENT for j in range ( self . k + 1 ) : NEW_LINE INDENT val = self . f ( self . k , j ) NEW_LINE val1 = ( pow ( self . A [ i ] , self . k - j ) * pre [ i - 1 ] [ j ] ) NEW_LINE val = val * val1 NEW_LINE if j % 2 == 0 : NEW_LINE INDENT ans = ans + val NEW_LINE DEDENT else : NEW_LINE INDENT ans = ans - val NEW_LINE DEDENT DEDENT DEDENT ans = 2 * ans NEW_LINE return ans NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE K = 3 NEW_LINE arr = [ 1 , 2 , 3 ] NEW_LINE obj = Solution ( N , K , arr ) NEW_LINE print ( obj . pairsPower ( ) ) NEW_LINE DEDENT
Count of ways to traverse a Matrix and return to origin in K steps | Python3 program to count total number of ways to return to origin after completing given number of steps . ; Function Initialize dp [ ] [ ] [ ] array with - 1 ; Function returns the total count ; Driver code
MOD = 1000000007 NEW_LINE dp = [ [ [ 0 for i in range ( 101 ) ] for i in range ( 101 ) ] for i in range ( 101 ) ] NEW_LINE N , M , K = 0 , 0 , 0 NEW_LINE def Initialize ( ) : NEW_LINE INDENT for i in range ( 101 ) : NEW_LINE INDENT for j in range ( 101 ) : NEW_LINE INDENT for z in range ( 101 ) : NEW_LINE INDENT dp [ i ] [ j ] [ z ] = - 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def CountWays ( i , j , k ) : NEW_LINE INDENT if ( i >= N or i < 0 or j >= M or j < 0 or k < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( i == 0 and j == 0 and k == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ i ] [ j ] [ k ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] [ k ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = ( CountWays ( i + 1 , j , k - 1 ) % MOD + CountWays ( i - 1 , j , k - 1 ) % MOD + CountWays ( i , j - 1 , k - 1 ) % MOD + CountWays ( i , j + 1 , k - 1 ) % MOD + CountWays ( i , j , k - 1 ) % MOD ) % MOD NEW_LINE DEDENT return dp [ i ] [ j ] [ k ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE M = 3 NEW_LINE K = 4 NEW_LINE Initialize ( ) NEW_LINE print ( CountWays ( 0 , 0 , K ) ) NEW_LINE DEDENT
Count of subsequences of length atmost K containing distinct prime elements | Python3 Program to find the count of distinct prime subsequences at most of of length K from a given array ; Initialize all indices as true ; A value in prime [ i ] will finally be false if i is not a prime , else true ; If prime [ p ] is true , then it is a prime ; Update all multiples of p as false , i . e . non - prime ; Returns number of subsequences of maximum length k and contains distinct primes ; Store the primes in the given array ; Sort the primes ; Store the frequencies of all the distinct primes ; Store the frequency of primes ; Store the sum of all frequencies ; Store the length of subsequence at every instant ; Store the frequency ; Store the previous count of updated DP ; Calculate total subsequences of current of_length ; Add the number of subsequences to the answer ; Update the value in dp [ i ] ; Store the updated dp [ i ] ; Driver Code
prime = [ True ] * 1000000 NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT global prime NEW_LINE prime [ 0 ] = prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= 100000 : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , 100001 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def distinctPrimeSubSeq ( a , n , k ) : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE primes = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( prime [ a [ i ] ] ) : NEW_LINE INDENT primes . append ( a [ i ] ) NEW_LINE DEDENT DEDENT l = len ( primes ) NEW_LINE primes . sort ( ) NEW_LINE b = [ ] NEW_LINE dp = [ ] NEW_LINE sum = 0 NEW_LINE i = 0 NEW_LINE while i < l : NEW_LINE INDENT count = 1 NEW_LINE x = a [ i ] NEW_LINE i += 1 NEW_LINE while ( i < l and a [ i ] == x ) : NEW_LINE INDENT count += 1 NEW_LINE i += 1 NEW_LINE DEDENT b . append ( count ) NEW_LINE dp . append ( count ) NEW_LINE sum += count NEW_LINE DEDENT of_length = 2 NEW_LINE leng = len ( dp ) NEW_LINE ans = 0 NEW_LINE while ( of_length <= k ) : NEW_LINE INDENT freq = 0 NEW_LINE prev = 0 NEW_LINE for i in range ( leng - 1 ) : NEW_LINE INDENT freq += dp [ i ] NEW_LINE j = sum - freq NEW_LINE subseq = b [ i ] * j NEW_LINE ans += subseq NEW_LINE dp [ i ] = subseq NEW_LINE prev += dp [ i ] NEW_LINE DEDENT leng -= 1 NEW_LINE sum = prev NEW_LINE of_length += 1 NEW_LINE DEDENT ans += ( l + 1 ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 2 , 3 , 3 , 4 , 5 ] NEW_LINE n = len ( a ) NEW_LINE k = 3 NEW_LINE print ( distinctPrimeSubSeq ( a , n , 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 iterate over every elements of the array ; Loop to find the consecutive smaller elements at left ; Loop to find the consecutive smaller elements at right ; Driver code
def findMinPrizes ( arr , n ) : NEW_LINE INDENT totalPrizes = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = 1 NEW_LINE j = i NEW_LINE while ( j > 0 and arr [ j ] > arr [ j - 1 ] ) : NEW_LINE INDENT x += 1 NEW_LINE j -= 1 NEW_LINE DEDENT j = i NEW_LINE y = 1 NEW_LINE while ( j < n - 1 and arr [ j ] > arr [ j + 1 ] ) : NEW_LINE INDENT y += 1 NEW_LINE j += 1 NEW_LINE DEDENT totalPrizes += max ( x , y ) NEW_LINE DEDENT print ( totalPrizes ) NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE findMinPrizes ( arr , n ) NEW_LINE
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 ] ; DP Table ; 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 ; 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 ; Initialize DP Table as - 1 ; Driver code
mod = 1000000007 NEW_LINE dp = [ [ - 1 for j in range ( 1000 ) ] for i in range ( 1000 ) ] 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 if ( dp [ pos ] [ left ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ left ] 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 dp [ pos ] [ left ] = answer NEW_LINE return answer NEW_LINE DEDENT def countWaystoDivide ( n , k , L , R ) : NEW_LINE INDENT return calculate ( 0 , n , k , L , R ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 12 NEW_LINE K = 3 NEW_LINE L = 1 NEW_LINE R = 5 NEW_LINE print ( countWaystoDivide ( N , K , L , R ) ) NEW_LINE DEDENT
Minimum number of squares whose sum equals to given number N | set 2 | Function for finding minimum square numbers ; arr [ i ] of array arr store minimum count of square number to get i ; sqrNum [ i ] store last square number to get i ; Find minimum count of square number for all value 1 to n ; In worst case it will be arr [ i - 1 ] + 1 we use all combination of a [ i - 1 ] and add 1 ; Check for all square number less or equal to i ; If it gives less count then update it ; v stores optimum square number whose sum give N ; Driver code ; Calling function ; Printing vector
def minSqrNum ( n ) : NEW_LINE INDENT arr = [ 0 ] * ( n + 1 ) NEW_LINE sqrNum = [ 0 ] * ( n + 1 ) NEW_LINE v = [ ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] + 1 NEW_LINE sqrNum [ i ] = 1 NEW_LINE k = 1 ; NEW_LINE while ( k * k <= i ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - k * k ] + 1 ) : NEW_LINE INDENT arr [ i ] = arr [ i - k * k ] + 1 NEW_LINE sqrNum [ i ] = k * k NEW_LINE DEDENT k += 1 NEW_LINE DEDENT DEDENT while ( n > 0 ) : NEW_LINE INDENT v . append ( sqrNum [ n ] ) NEW_LINE n -= sqrNum [ n ] ; NEW_LINE DEDENT return v NEW_LINE DEDENT n = 10 NEW_LINE v = minSqrNum ( n ) NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT print ( v [ i ] , end = " " ) NEW_LINE if ( i < len ( v ) - 1 ) : NEW_LINE INDENT print ( " ▁ + ▁ " , end = " " ) NEW_LINE DEDENT DEDENT