text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Find the Side of the smallest Square that can contain given 4 Big Squares | Function to find the maximum of two values ; Function to find the smallest side of the suitable suitcase ; sort array to find the smallest and largest side of suitcases ; side of the suitcase will be smallest if they arranged in 2 x 2 way so fi...
def max ( a , b ) : NEW_LINE INDENT if ( a > b ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return b NEW_LINE DEDENT DEDENT def smallestSide ( a ) : NEW_LINE INDENT a . sort ( reverse = False ) NEW_LINE side1 = a [ 0 ] + a [ 3 ] NEW_LINE side2 = a [ 1 ] + a [ 2 ] NEW_LINE side3 = a [ 0 ] + a [ 1 ...
Rectangle with minimum possible difference between the length and the width | Python3 implementation of the approach ; Function to print the length ( l ) and breadth ( b ) of the rectangle having area = N and | l - b | as minimum as possible ; i is a factor ; l >= sqrt ( area ) >= i ; so here l is + ve always ; Here l ...
import math as mt NEW_LINE def find_rectangle ( area ) : NEW_LINE INDENT l , b = 0 , 0 NEW_LINE M = mt . ceil ( mt . sqrt ( area ) ) NEW_LINE ans = 0 NEW_LINE for i in range ( M , 0 , - 1 ) : NEW_LINE INDENT if ( area % i == 0 ) : NEW_LINE INDENT l = ( area // i ) NEW_LINE b = i NEW_LINE break NEW_LINE DEDENT DEDENT pr...
Rectangle with minimum possible difference between the length and the width | Python3 implementation of the approach ; Function to print the length ( l ) and breadth ( b ) of the rectangle having area = N and | l - b | as minimum as possible ; Driver code
import math NEW_LINE def find_rectangle ( area ) : NEW_LINE INDENT for i in range ( int ( math . ceil ( math . sqrt ( area ) ) ) , area + 1 ) : NEW_LINE INDENT if ( ( int ( area / i ) * i ) == area ) : NEW_LINE INDENT print ( i , int ( area / i ) ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT area = 99 NEW_LINE find_r...
Largest sub | Python3 implementation of the approach ; Function to return the size of the required sub - set ; Sort the array ; Set to store the contents of the required sub - set ; Insert the elements satisfying the conditions ; Return the size of the set ; Driver code
import math as mt NEW_LINE def sizeSubSet ( a , k , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % k != 0 or a [ i ] // k not in s ) : NEW_LINE INDENT s . add ( a [ i ] ) NEW_LINE DEDENT DEDENT return len ( s ) NEW_LINE DEDENT a = [ 1 , 2 , 3 , 4 ,...
Minimum number of sets with numbers less than Y | Python3 program to find the minimum number sets with consecutive numbers and less than Y ; Function to find the minimum number of shets ; Variable to count the number of sets ; Iterate in the string ; Add the number to string ; Mark that we got a number ; Check if previ...
import math as mt NEW_LINE def minimumSets ( s , y ) : NEW_LINE INDENT cnt = 0 NEW_LINE num = 0 NEW_LINE l = len ( s ) NEW_LINE f = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT num = num * 10 + ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE if ( num <= y ) : NEW_LINE INDENT f = 1 NEW_LINE if ( f ) : NEW_LINE INDENT cn...
Find the non decreasing order array from given array | Python 3 implementation of the approach ; Utility function to print the contents of the array ; Function to build array B [ ] ; Lower and upper limits ; To store the required array ; Apply greedy approach ; Print the built array b [ ] ; Driver code
import sys NEW_LINE def printArr ( b , n ) : NEW_LINE INDENT for i in range ( 0 , n , 1 ) : NEW_LINE INDENT print ( b [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def ModifiedArray ( a , n ) : NEW_LINE INDENT l = 0 NEW_LINE r = sys . maxsize NEW_LINE b = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( 0 , int ( n ...
Count of lines required to write the given String | Function to return the number of lines required ; If string is empty ; Initialize lines and width ; Iterate through S ; Return lines and width used ; Driver Code ; Function call to print required answer
def numberOfLines ( S , widths ) : NEW_LINE INDENT if ( S == " " ) : NEW_LINE INDENT return 0 , 0 NEW_LINE DEDENT lines , width = 1 , 0 NEW_LINE for c in S : NEW_LINE INDENT w = widths [ ord ( c ) - ord ( ' a ' ) ] NEW_LINE width += w NEW_LINE if width > 10 : NEW_LINE INDENT lines += 1 NEW_LINE width = w NEW_LINE DEDEN...
Check if elements of an array can be arranged satisfying the given condition | Python implementation of the approach ; Function to return true if the elements can be arranged in the desired order ; If 2 * x is not found to pair ; Remove an occurrence of x and an occurrence of 2 * x ; Driver Code ; Function call to prin...
import collections NEW_LINE def canReorder ( A ) : NEW_LINE INDENT count = collections . Counter ( A ) NEW_LINE for x in sorted ( A , key = abs ) : NEW_LINE INDENT if count [ x ] == 0 : NEW_LINE INDENT continue NEW_LINE DEDENT if count [ 2 * x ] == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT count [ x ] -= 1 NEW_L...
Maximum sum of all elements of array after performing given operations | Python3 program to find the maximum sum after given operations ; Function to calculate Maximum Subarray Sum or Kadane 's Algorithm ; Function to find the maximum sum after given operations ; To store sum of all elements ; Maximum sum of a subarray...
import sys NEW_LINE def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - ( sys . maxsize - 1 ) NEW_LINE max_ending_here = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] NEW_LINE if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_he...
Minimize the difference between minimum and maximum elements | Function to minimize the difference between minimum and maximum elements ; Find max and min elements of the array ; Check whether the difference between the max and min element is less than or equal to k or not ; Calculate average of max and min ; If the ar...
def minimizeDiff ( arr , n , k ) : NEW_LINE INDENT max_element = max ( arr ) NEW_LINE min_element = min ( arr ) NEW_LINE if ( ( max_element - min_element ) <= k ) : NEW_LINE INDENT return ( max_element - min_element ) NEW_LINE DEDENT avg = ( max_element + min_element ) // 2 NEW_LINE for i in range ( n ) : NEW_LINE INDE...
Maximum litres of water that can be bought with N Rupees | Python3 implementation of the above approach ; if buying glass bottles is profitable ; Glass bottles that can be bought ; Change budget according the bought bottles ; Plastic bottles that can be bought ; if only plastic bottles need to be bought ; Driver Code
def maxLitres ( budget , plastic , glass , refund ) : NEW_LINE INDENT if glass - refund < plastic : NEW_LINE INDENT ans = max ( ( budget - refund ) // ( glass - refund ) , 0 ) NEW_LINE budget -= ans * ( glass - refund ) NEW_LINE ans += budget // plastic NEW_LINE print ( ans ) NEW_LINE DEDENT else : NEW_LINE INDENT prin...
Find number from given list for which value of the function is closest to A | Function to find number from given list for which value of the function is closest to A ; Stores the final index ; Declaring a variable to store the minimum absolute difference ; Finding F ( n ) ; Updating the index of the answer if new absol...
def leastValue ( P , A , N , a ) : NEW_LINE INDENT ans = - 1 NEW_LINE tmp = float ( ' inf ' ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT t = P - a [ i ] * 0.006 NEW_LINE if abs ( t - A ) < tmp : NEW_LINE INDENT tmp = abs ( t - A ) NEW_LINE ans = i NEW_LINE DEDENT DEDENT return a [ ans ] NEW_LINE DEDENT N , P , A =...
Find permutation of n which is divisible by 3 but not divisible by 6 | Python3 program to find permutation of n which is divisible by 3 but not divisible by 6 ; Function to find the permutation ; length of integer ; if integer is even ; return odd integer ; rotate integer ; return - 1 in case no required permutation ex...
from math import log10 , ceil , pow NEW_LINE def findPermutation ( n ) : NEW_LINE INDENT len = ceil ( log10 ( n ) ) NEW_LINE for i in range ( 0 , len , 1 ) : NEW_LINE INDENT if n % 2 != 0 : NEW_LINE INDENT return n NEW_LINE DEDENT else : NEW_LINE INDENT n = ( ( n / 10 ) + ( n % 10 ) * pow ( 10 , len - i - 1 ) ) NEW_LIN...
Maximum score after flipping a Binary Matrix atmost K times | Python3 program to find the maximum score after flipping a Binary Matrix atmost K times ; Function to find maximum score of matrix ; Find value of rows having first column value equal to zero ; update those rows which lead to maximum score after toggle ; Cal...
n = 3 NEW_LINE m = 4 NEW_LINE def maxMatrixScore ( A , K ) : NEW_LINE INDENT update = { } NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if A [ i ] [ 0 ] == 0 : NEW_LINE INDENT ans = 0 NEW_LINE for j in range ( 1 , m ) : NEW_LINE INDENT ans = ans + A [ i ] [ j ] * 2 ** ( m - j - 1 ) NEW_LINE DEDENT update [ ans ] ...
Check if it is possible to serve customer queue with different notes | Function that returns true is selling of the tickets is possible ; Nothing to return to the customer ; Check if 25 can be returned to customer . ; Try returning one 50 and one 25 ; Try returning three 25 ; If the loop did not break , all the tickets...
def isSellingPossible ( n , a ) : NEW_LINE INDENT c25 = 0 ; NEW_LINE c50 = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( a [ i ] == 25 ) : NEW_LINE INDENT c25 += 1 ; NEW_LINE DEDENT elif ( a [ i ] == 50 ) : NEW_LINE INDENT c50 += 1 ; NEW_LINE if ( c25 == 0 ) : NEW_LINE INDENT break ; NEW_LINE DED...
Check if a cell can be visited more than once in a String | Function to check if any cell can be visited more than once ; Array to mark cells ; Traverse the string ; Increase the visit count of the left and right cells within the array which can be visited ; If any cell can be visited more than once , Return True ; Dri...
def checkIfOverlap ( str ) : NEW_LINE INDENT length = len ( str ) NEW_LINE visited = [ 0 ] * ( length + 1 ) NEW_LINE for i in range ( length ) : NEW_LINE INDENT if str [ i ] == " . " : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( max ( 0 , i - ord ( str [ i ] ) , min ( length , i + ord ( str [ i ] ) ) + 1 ...
Check if a number has digits in the given Order | Check if the digits follow the correct order ; to store the previous digit ; pointer to tell what type of sequence are we dealing with ; check if we have same digit as the previous digit ; checking the peak point of the number ; check if we have same digit as the previo...
def isCorrectOrder ( n ) : NEW_LINE INDENT flag = True ; NEW_LINE prev = - 1 ; NEW_LINE type = - 1 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( type == - 1 ) : NEW_LINE INDENT if ( prev == - 1 ) : NEW_LINE INDENT prev = n % 10 ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE continue ; NEW_LINE DEDENT if ( prev == n % 10...
Coin game of two corners ( Greedy Approach ) | Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Find sum of odd positioned coins ; Find sum of even positioned coins ; Print even or odd coins depending upon which sum is greater . ; Driver code
def printCoins ( arr , n ) : NEW_LINE INDENT oddSum = 0 NEW_LINE for i in range ( 0 , n , 2 ) : NEW_LINE INDENT oddSum += arr [ i ] NEW_LINE DEDENT evenSum = 0 NEW_LINE for i in range ( 1 , n , 2 ) : NEW_LINE INDENT evenSum += arr [ i ] NEW_LINE DEDENT if oddSum > evenSum : NEW_LINE INDENT start = 0 NEW_LINE DEDENT els...
Prim 's Algorithm (Simple Implementation for Adjacency Matrix Representation) | Python3 implementation to find minimum spanning tree for adjacency representation . ; Returns true if edge u - v is a valid edge to be include in MST . An edge is valid if one end is already included in MST and other is not in MST . ; Inclu...
from sys import maxsize NEW_LINE INT_MAX = maxsize NEW_LINE V = 5 NEW_LINE def isValidEdge ( u , v , inMST ) : NEW_LINE INDENT if u == v : NEW_LINE INDENT return False NEW_LINE DEDENT if inMST [ u ] == False and inMST [ v ] == False : NEW_LINE INDENT return False NEW_LINE DEDENT elif inMST [ u ] == True and inMST [ v ]...
Subarray whose absolute sum is closest to K | function to return the index ; Add Last element tp currSum ; Save Difference of previous Iteration ; Calculate new Difference ; When the Sum exceeds K ; Current Difference greater in magnitude Store Temporary Result ; Difference in Previous was lesser In previous , Right in...
def getSubArray ( arr , n , K ) : NEW_LINE INDENT currSum = 0 NEW_LINE prevDif = 0 NEW_LINE currDif = 0 NEW_LINE result = [ - 1 , - 1 , abs ( K - abs ( currSum ) ) ] NEW_LINE resultTmp = result NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while ( i <= j and j < n ) : NEW_LINE INDENT currSum += arr [ j ] NEW_LINE prevDif = cu...
Length and Breadth of rectangle such that ratio of Area to diagonal ^ 2 is maximum | function to print length and breadth ; sort the input array ; create array vector of integers occurring in pairs ; push the same pairs ; calculate length and breadth as per requirement ; check for given condition ; print the required a...
def findLandB ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE arr_pairs = [ ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT arr_pairs . append ( arr [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT length = arr_pairs [ 0 ] NEW_LINE breadth = ...
Smallest sum contiguous subarray | Set | function to find the smallest sum contiguous subarray ; First invert the sign of the elements ; Apply the normal Kadane algorithm but on the elements of the array having inverted sign ; Invert the answer to get minimum val ; Driver Code
def smallestSumSubarr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = - arr [ i ] NEW_LINE DEDENT sum_here = arr [ 0 ] NEW_LINE max_sum = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT sum_here = max ( sum_here + arr [ i ] , arr [ i ] ) NEW_LINE max_sum = max ( max_sum , ...
Find k pairs with smallest sums in two arrays | Set 2 | Function to print the K smallest pairs ; if k is greater than total pairs ; _pair _one keeps track of ' first ' in a1 and ' second ' in a2 in _two , _two [ 0 ] keeps track of element in the a2and _two [ 1 ] in a1 [ ] ; Repeat the above process till all K pairs are...
def printKPairs ( a1 , a , size1 , size2 , k ) : NEW_LINE INDENT if ( k > ( size2 * size1 ) ) : NEW_LINE INDENT print ( " k pairs don ' t exist " ) NEW_LINE return NEW_LINE DEDENT _one , _two = [ 0 , 0 ] , [ 0 , 0 ] NEW_LINE cnt = 0 NEW_LINE while ( cnt < k ) : NEW_LINE INDENT if ( _one [ 0 ] == _two [ 1 ] and _two [ 0...
Maximum number by concatenating every element in a rotation of an array | Function to print the largest number ; store the index of largest left most digit of elements ; Iterate for all numbers ; check for the last digit ; check for the largest left most digit ; print the rotation of array ; print the rotation of array...
def printLargest ( a , n ) : NEW_LINE INDENT max = - 1 NEW_LINE ind = - 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT num = a [ i ] NEW_LINE while ( num ) : NEW_LINE INDENT r = num % 10 ; NEW_LINE num = num / 10 ; NEW_LINE if ( num == 0 ) : NEW_LINE INDENT if ( max < r ) : NEW_LINE INDENT max = r NEW_LINE ind =...
Minimum operations to make GCD of array a multiple of k | Python 3 program to make GCD of array a multiple of k . ; If array value is not 1 and it is greater than k then we can increase the or decrease the remainder obtained by dividing k from the ith value of array so that we get the number which is either closer to k...
def MinOperation ( a , n , k ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] != 1 and a [ i ] > k ) : NEW_LINE INDENT result = ( result + min ( a [ i ] % k , k - a [ i ] % k ) ) NEW_LINE DEDENT else : NEW_LINE INDENT result = result + k - a [ i ] NEW_LINE DEDENT DEDENT return...
Maximum product subset of an array | Python3 program to find maximum product of a subset . ; Find count of negative numbers , count of zeros , negative number with least absolute value and product of non - zero numbers ; If number is 0 , we don 't multiply it with product. ; Count negatives and keep track of negative ...
def maxProductSubset ( a , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return a [ 0 ] NEW_LINE DEDENT max_neg = - 999999999999 NEW_LINE count_neg = 0 NEW_LINE count_zero = 0 NEW_LINE prod = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] == 0 : NEW_LINE INDENT count_zero += 1 NEW_LINE continue NEW_LI...
Minimum cost to process m tasks where switching costs | Function to find out the farthest position where one of the currently ongoing tasks will rehappen . ; Iterate form last to current position and find where the task will happen next . ; Find out maximum of all these positions and it is the farthest position . ; Fun...
def find ( arr , pos , m , isRunning ) : NEW_LINE INDENT d = [ 0 ] * ( m + 1 ) NEW_LINE for i in range ( m - 1 , pos , - 1 ) : NEW_LINE INDENT if isRunning [ arr [ i ] ] : NEW_LINE INDENT d [ arr [ i ] ] = i NEW_LINE DEDENT DEDENT maxipos = 0 NEW_LINE for ele in d : NEW_LINE INDENT maxipos = max ( ele , maxipos ) NEW_L...
Minimum Fibonacci terms with sum equal to K | Function to calculate Fibonacci Terms ; Calculate all Fibonacci terms which are less than or equal to K . ; If next term is greater than K do not push it in vector and return . ; Function to find the minimum number of Fibonacci terms having sum equal to K . ; Vector to stor...
def calcFiboTerms ( fiboTerms , K ) : NEW_LINE INDENT i = 3 NEW_LINE fiboTerms . append ( 0 ) NEW_LINE fiboTerms . append ( 1 ) NEW_LINE fiboTerms . append ( 1 ) NEW_LINE while True : NEW_LINE INDENT nextTerm = ( fiboTerms [ i - 1 ] + fiboTerms [ i - 2 ] ) NEW_LINE if nextTerm > K : NEW_LINE INDENT return NEW_LINE DEDE...
Smallest number with sum of digits as N and divisible by 10 ^ N | Python program to find smallest number to find smallest number with N as sum of digits and divisible by 10 ^ N . ; If N = 0 the string will be 0 ; If n is not perfectly divisible by 9 output the remainder ; Print 9 N / 9 times ; Append N zero 's to the n...
import math NEW_LINE def digitsNum ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT print ( "0" , end = " " ) NEW_LINE DEDENT if ( N % 9 != 0 ) : NEW_LINE INDENT print ( N % 9 , end = " " ) NEW_LINE DEDENT for i in range ( 1 , int ( N / 9 ) + 1 ) : NEW_LINE INDENT print ( "9" , end = " " ) NEW_LINE DEDENT for i ...
Divide 1 to n into two groups with minimum sum difference | Python program to divide n integers in two groups such that absolute difference of their sum is minimum ; To print vector along size ; Print vector size ; Print vector elements ; To divide n in two groups such that absolute difference of their sum is minimum ;...
import math NEW_LINE def printVector ( v ) : NEW_LINE INDENT print ( len ( v ) ) NEW_LINE for i in range ( 0 , len ( v ) ) : NEW_LINE INDENT print ( v [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def findTwoGroup ( n ) : NEW_LINE INDENT sum = n * ( n + 1 ) / 2 NEW_LINE group1Sum = sum / 2 NEW_LINE gr...
Maximum number of customers that can be satisfied with given quantity | Python3 program to find maximum number of customers that can be satisfied ; print maximum number of satisfied customers and their indexes ; Creating an vector of pair of total demand and customer number ; Sorting the customers according to their to...
v = [ ] NEW_LINE def solve ( n , d , a , b , arr ) : NEW_LINE INDENT first , second = 0 , 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT m = arr [ i ] [ 0 ] NEW_LINE t = arr [ i ] [ 1 ] NEW_LINE v . append ( [ a * m + b * t , i + 1 ] ) NEW_LINE DEDENT v . sort ( ) NEW_LINE ans = [ ] NEW_LINE for i in range ( n ) : N...
Partition into two subarrays of lengths k and ( N | Function to calculate max_difference ; Sum of the array ; Sort the array in descending order ; Calculating max_difference ; Driver Code
def maxDifference ( arr , N , k ) : NEW_LINE INDENT S = 0 NEW_LINE S1 = 0 NEW_LINE max_difference = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT S += arr [ i ] NEW_LINE DEDENT arr . sort ( reverse = True ) NEW_LINE M = max ( k , N - k ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT S1 += arr [ i ] NEW_LINE DEDEN...
Minimum sum of product of two arrays | Function to find the minimum product ; Find product of current elements and update result . ; If both product and b [ i ] are negative , we must increase value of a [ i ] to minimize result . ; If both product and a [ i ] are negative , we must decrease value of a [ i ] to minimiz...
def minproduct ( a , b , n , k ) : NEW_LINE INDENT diff = 0 NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT pro = a [ i ] * b [ i ] NEW_LINE res = res + pro NEW_LINE if ( pro < 0 and b [ i ] < 0 ) : NEW_LINE INDENT temp = ( a [ i ] + 2 * k ) * b [ i ] NEW_LINE DEDENT elif ( pro < 0 and a [ i ] < 0 ) : ...
Split n into maximum composite numbers | Function to calculate the maximum number of composite numbers adding upto n ; 4 is the smallest composite number ; stores the remainder when n is divided n is divided by 4 ; if remainder is 0 , then it is perfectly divisible by 4. ; if the remainder is 1 ; If the number is less ...
def count ( n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT rem = n % 4 NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT return n // 4 NEW_LINE DEDENT if ( rem == 1 ) : NEW_LINE INDENT if ( n < 9 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return ( n - 9 ) // 4 + 1 NEW_LINE DEDENT if ( rem ...
Policemen catch thieves | Returns maximum number of thieves that can be caught . ; store indices in list ; track lowest current indices of thief : thi [ l ] , police : pol [ r ] ; can be caught ; increment the minimum index ; Driver program
def policeThief ( arr , n , k ) : NEW_LINE INDENT i = 0 NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE res = 0 NEW_LINE thi = [ ] NEW_LINE pol = [ ] NEW_LINE while i < n : NEW_LINE INDENT if arr [ i ] == ' P ' : NEW_LINE INDENT pol . append ( i ) NEW_LINE DEDENT elif arr [ i ] == ' T ' : NEW_LINE INDENT thi . append ( i ) NEW_...
Minimum rotations to unlock a circular lock | function for min rotation ; iterate till input and unlock code become 0 ; input and unlock last digit as reminder ; find min rotation ; update code and input ; Driver Code
def minRotation ( input , unlock_code ) : NEW_LINE INDENT rotation = 0 ; NEW_LINE while ( input > 0 or unlock_code > 0 ) : NEW_LINE INDENT input_digit = input % 10 ; NEW_LINE code_digit = unlock_code % 10 ; NEW_LINE rotation += min ( abs ( input_digit - code_digit ) , 10 - abs ( input_digit - code_digit ) ) ; NEW_LINE ...
Job Scheduling with two jobs allowed at a time | Python3 program to check if all jobs can be scheduled if two jobs are allowed at a time . ; making a pair of starting and ending time of job ; sorting according to starting time of job ; starting first and second job simultaneously ; Checking if starting time of next new...
def checkJobs ( startin , endin , n ) : NEW_LINE INDENT a = [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT a . append ( [ startin [ i ] , endin [ i ] ] ) NEW_LINE DEDENT a . sort ( ) NEW_LINE tv1 = a [ 0 ] [ 1 ] NEW_LINE tv2 = a [ 1 ] [ 1 ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( a [ i ] [ 0 ]...
Minimum cost for acquiring all coins with k extra coins allowed with every coin | Python3 program to acquire all n coins at minimum cost with multiple values of k . ; Converts coin [ ] to prefix sum array ; sort the coins values ; maintain prefix sum array ; Function to calculate min cost when we can get k extra coins ...
import math as mt NEW_LINE def preprocess ( coin , n ) : NEW_LINE INDENT coin . sort ( ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT coin [ i ] += coin [ i - 1 ] NEW_LINE DEDENT DEDENT def minCost ( coin , n , k ) : NEW_LINE INDENT coins_needed = mt . ceil ( 1.0 * n / ( k + 1 ) ) NEW_LINE return coin [ coins_ne...
Program for Worst Fit algorithm in Memory Management | Function to allocate memory to blocks as per worst fit algorithm ; Initially no block is assigned to any process ; pick each process and find suitable blocks according to its size ad assign to it ; Find the best fit block for current process ; If we could find a bl...
def worstFit ( blockSize , m , processSize , n ) : NEW_LINE INDENT allocation = [ - 1 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT wstIdx = - 1 NEW_LINE for j in range ( m ) : NEW_LINE INDENT if blockSize [ j ] >= processSize [ i ] : NEW_LINE INDENT if wstIdx == - 1 : NEW_LINE INDENT wstIdx = j NEW_LINE DEDENT...
Maximize array sum after K negations | Set 1 | This function does k operations on array in a way that maximize the array sum . index -- > stores the index of current minimum element for j 'th operation ; Modify array K number of times ; Find minimum element in array for current operation and modify it i . e ; arr [ j ]...
def maximumSum ( arr , n , k ) : NEW_LINE INDENT for i in range ( 1 , k + 1 ) : NEW_LINE INDENT min = + 2147483647 NEW_LINE index = - 1 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ j ] < min ) : NEW_LINE INDENT min = arr [ j ] NEW_LINE index = j NEW_LINE DEDENT DEDENT if ( min == 0 ) : NEW_LINE INDENT bre...
Maximize array sum after K negations | Set 1 | Python3 program to find maximum array sum after at most k negations ; Sorting given array using in - built java sort function ; If we find a 0 in our sorted array , we stop ; Calculating sum ; Driver code
def sol ( arr , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE Sum = 0 NEW_LINE i = 0 NEW_LINE while ( k > 0 ) : NEW_LINE INDENT if ( arr [ i ] >= 0 ) : NEW_LINE INDENT k = 0 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = ( - 1 ) * arr [ i ] NEW_LINE k = k - 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT for j in range ( ...
Maximize array sum after K negations | Set 1 | Function to calculate sum of the array ; Iterate from 0 to n - 1 ; Function to maximize sum ; Iterate from 0 to n - 1 ; Driver Code ; Function Call
def sumArray ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT def maximizeSum ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE i = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( k and arr [ i ] < 0 ) : NEW_...
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 ] ; I...
def firstFit ( weight , n , c ) : NEW_LINE INDENT res = 0 NEW_LINE bin_rem = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < res ) : NEW_LINE INDENT if ( bin_rem [ j ] >= weight [ i ] ) : NEW_LINE INDENT bin_rem [ j ] = bin_rem [ j ] - weight [ i ] NEW_LINE break NEW_LINE DEDENT j +...
Minimum cost to reduce A and B to 0 using square root or divide by 2 | Python program for the above approach ; Function to return the minimum cost of converting A and B to 0 ; If both A and B doesn 't change in this recusrive call, then return INT_MAX to save the code from going into infinite loop ; Base Case ; If t...
import math as Math NEW_LINE def getMinOperations ( A , B , prevA , prevB , dp ) : NEW_LINE INDENT if ( A == prevA and B == prevB ) : NEW_LINE INDENT return 10 ** 9 ; NEW_LINE DEDENT if ( A == 0 and B == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ A ] [ B ] != - 1 ) : NEW_LINE INDENT return dp [ A ] [ B ...
Maximize count of indices with same element by pairing rows from given Matrices | Function to find the maximum defined score ; If all students are assigned ; Check if row is not paired yet ; Check for all indexes ; If values at current indexes are same increase curSum ; Further recursive call ; Store the ans for curren...
def maxScoreSum ( a , b , row , mask , dp ) : NEW_LINE INDENT if ( row >= len ( a ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ mask ] != - 1 ) : NEW_LINE INDENT return dp [ mask ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT if ( mask & ( 1 << i ) ) : NEW_LINE INDENT newMa...
Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays | Function to find the maximum sum of differences of subarrays by splitting array into non - overlapping subarrays ; Stores the answer for prefix and initialize with zero ; Assume i - th index as right endpoint ; Choose the c...
def maxDiffSum ( arr , n ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxVal = arr [ i ] NEW_LINE minVal = arr [ i ] NEW_LINE for j in range ( i , - 1 , - 1 ) : NEW_LINE INDENT minVal = min ( minVal , arr [ j ] ) NEW_LINE maxVal = max ( maxVal , arr [ j ] ) NEW_LINE if ( j - 1 >= 0...
Count of N | python 3 program for the above approach ; Find the value of x raised to the yth power modulo MOD ; Stores the value of x ^ y ; Iterate until y is positive ; Function to perform the Modular Multiplicative Inverse using the Fermat 's little theorem ; Modular division x / y , find modular multiplicative inver...
MOD = 1000000007 NEW_LINE from math import sqrt NEW_LINE def modPow ( x , y ) : NEW_LINE INDENT r = 1 NEW_LINE a = x NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) == 1 ) : NEW_LINE INDENT r = ( r * a ) % MOD NEW_LINE DEDENT a = ( a * a ) % MOD NEW_LINE y /= 2 NEW_LINE DEDENT return r NEW_LINE DEDENT def mod...
Minimum number of days to debug all programs | Python 3 program for the above approach ; Function to calculate the minimum work sessions ; Break condition ; All bits are set ; Check if already calculated ; Store the answer ; Check if ith bit is set or unset ; Including in current work session ; Including in next work s...
import sys NEW_LINE def minSessions ( codeTime , dp , ones , n , mask , currTime , WorkingSessionTime ) : NEW_LINE INDENT if ( currTime > WorkingSessionTime ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT if ( mask == ones ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ mask ] [ currTime ] != - 1 ) : NE...
Count of non | Python 3 program for the above approach ; Define the dp table globally ; Recursive function to calculate total number of valid non - decreasing strings ; If already calculated state ; Base Case ; Stores the total count of strings formed ; Fill the value in dp matrix ; Function to find the total number of...
MAXN = 100005 NEW_LINE dp = [ [ - 1 for x in range ( 10 ) ] for y in range ( MAXN ) ] NEW_LINE def solve ( len , gap ) : NEW_LINE INDENT if ( dp [ len ] [ gap ] != - 1 ) : NEW_LINE INDENT return dp [ len ] [ gap ] NEW_LINE DEDENT if ( len == 0 or gap == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( gap < 0 ) : NE...
Count of binary arrays of size N with sum of product of adjacent pairs equal to K | Function to return the number of total possible combinations of 0 and 1 to form an array of size N having sum of product of consecutive elements K ; If value is greater than K , then return 0 as no combination is possible to have sum K ...
def combinationsPossible ( N , idx , prev , val , K , dp ) : NEW_LINE INDENT if ( val > K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ val ] [ idx ] [ prev ] != - 1 ) : NEW_LINE INDENT return dp [ val ] [ idx ] [ prev ] NEW_LINE DEDENT if ( idx == N - 1 ) : NEW_LINE INDENT if ( val == K ) : NEW_LINE INDENT re...
Count ways to split an array into subarrays such that sum of the i | Python3 program for the above approach ; Function to count ways to split an array into subarrays such that sum of the i - th subarray is divisible by i ; Stores the prefix sum of array ; Find the prefix sum ; Initialize dp [ ] [ ] array ; Stores the c...
import numpy as np NEW_LINE def countOfWays ( arr , N ) : NEW_LINE INDENT pre = [ 0 ] * ( N + 1 ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT pre [ i + 1 ] = pre [ i ] + arr [ i ] ; NEW_LINE DEDENT dp = np . zeros ( ( N + 2 , N + 2 ) ) ; NEW_LINE dp [ 1 ] [ 0 ] += 1 ; NEW_LINE ans = 0 ; NEW_LINE for i in range ( ...
Domino and Tromino tiling problem | Function to find the total number of ways to tile a 2 * N board using the given types of tile ; If N is less than 3 ; Store all dp - states ; Base Case ; Traverse the range [ 2 , N ] ; Update the value of dp [ i ] [ 0 ] ; Update the value of dp [ i ] [ 1 ] ; Update the value of dp [ ...
MOD = 1e9 + 7 NEW_LINE def numTilings ( N ) : NEW_LINE INDENT if ( N < 3 ) : NEW_LINE INDENT return N NEW_LINE DEDENT dp = [ [ 0 ] * 3 for i in range ( N + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = dp [ 1 ] [ 0 ] = 1 NEW_LINE dp [ 1 ] [ 1 ] = dp [ 1 ] [ 2 ] = 1 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] [ 0...
Count of N | Store the recurring recursive states ; Function to find the number of strings of length N such that it is a concatenation it substrings ; Single character cant be repeated ; Check if this state has been already calculated ; Stores the resultant count for the current recursive calls ; Iterate over all divis...
dp = { } NEW_LINE def countStrings ( N ) : NEW_LINE INDENT if N == 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if dp . get ( N , - 1 ) != - 1 : NEW_LINE INDENT return dp [ N ] NEW_LINE DEDENT ret = 0 NEW_LINE for div in range ( 1 , int ( N ** .5 ) + 1 ) : NEW_LINE INDENT if N % div == 0 : NEW_LINE INDENT ret += ( 1 <<...
Count N | python program for the above approach ; Function to count N - digit numbers such that each position is divisible by the digit occurring at that position ; Stores the answer . ; Iterate from indices 1 to N ; Stores count of digits that can be placed at the current index ; Iterate from digit 1 to 9 ; If index i...
mod = 1000000000 + 7 NEW_LINE def countOfNumbers ( N ) : NEW_LINE INDENT ans = 1 NEW_LINE for index in range ( 1 , N + 1 ) : NEW_LINE INDENT choices = 0 NEW_LINE for digit in range ( 1 , 10 ) : NEW_LINE INDENT if ( index % digit == 0 ) : NEW_LINE INDENT choices += 1 NEW_LINE DEDENT DEDENT ans = ( ans * choices ) % mod ...
Maximum number of groups that can receive fresh donuts distributed in batches of size K | Recursive function to find the maximum number of groups that will receive fresh donuts ; Store the result for the current state ; Check if the leftover donuts from the previous batch is 0 ; If true , then one by one give the fresh...
def dfs ( arr , left , K ) : NEW_LINE INDENT q = 0 NEW_LINE if ( left == 0 ) : NEW_LINE INDENT for i in range ( 1 , K , 1 ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT arr [ i ] -= 1 NEW_LINE q = max ( q , 1 + dfs ( arr , K - i , K ) ) NEW_LINE arr [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE I...
Maximum jumps to reach end of Array with condition that index i can make arr [ i ] jumps | Function to find the maximum jumps to reach end of array ; Stores the jumps needed to reach end from each index ; Traverse the array ; Check if j is less than N ; Add dp [ j ] to the value of dp [ i ] ; Update the value of ans ; ...
def findMaxJumps ( arr , N ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE ans = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT dp [ i ] = arr [ i ] NEW_LINE j = i + arr [ i ] NEW_LINE if ( j < N ) : NEW_LINE INDENT dp [ i ] = dp [ i ] + dp [ j ] NEW_LINE DEDENT ans = max ( ans , dp [ i ]...
Longest subsequence with non negative prefix sum at each position | Function to find the length of the longest subsequence with non negative prefix sum at each position ; Initialize dp array with - 1 ; Maximum subsequence sum by including no elements till position 'i ; Maximum subsequence sum by including first element...
def longestSubsequence ( arr , N ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( N + 1 ) ] for i in range ( N ) ] NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 0 NEW_LINE DEDENT dp [ 0 ] [ 1 ] = arr [ 0 ] if arr [ 0 ] >= 0 else - 1 NEW_LINE for i in range ( 1 , N ) : NEW_LI...
Count of strictly increasing N | Declaration of dp table ; Function to find the count of all N digit numbers such that all the digit is less than its adjacent digits ; Base Case : If i = n , then return 1 as valid number has been formed ; If the state has already been computed , then return it ; Stores the total count ...
dp = [ [ [ - 1 for x in range ( 2 ) ] for y in range ( 10 ) ] for z in range ( 100 ) ] NEW_LINE def solve ( i , n , prev , sign ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT val = dp [ i ] [ prev ] [ sign ] NEW_LINE if ( val != - 1 ) : NEW_LINE INDENT return val NEW_LINE DEDENT val = 0 NE...
Total count of sorted numbers upto N digits in range [ L , R ] ( Magnificent necklace combinatorics problem ) | Function to count total number of ways ; Stores all DP - states ; Stores the result ; Traverse the range [ 0 , N ] ; Traverse the range [ 1 , R - L ] ; Update dp [ i ] [ j ] ; Assign dp [ 0 ] [ R - L ] to ans...
def Count ( N , L , R ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( R - L + 1 ) ] for i in range ( N ) ] NEW_LINE ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , len ( dp [ 0 ] ) ) : NEW_LINE INDENT dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + 1 NEW_LINE DEDENT...
Length of largest common subarray in all the rows of given Matrix | Function to find longest common subarray in all the rows of the matrix ; Array to store the position of element in every row ; Traverse the matrix ; Store the position of every element in every row ; Variable to store length of largest common Subarray ...
def largestCommonSubarray ( arr , n , m ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( m + 1 ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT dp [ i ] [ arr [ i ] [ j ] ] = j NEW_LINE DEDENT DEDENT ans = 1 NEW_LINE len1 = 1 NEW_LINE for i in range ( 1 , ...
Maximize sum that can be obtained from two given arrays based on given conditions | Function to find the maximum sum that can be obtained from two given arrays based on the following conditions ; Stores the maximum sum from 0 to i ; Initialize the value of dp [ 0 ] [ 0 ] and dp [ 0 ] [ 1 ] ; Traverse the array A [ ] an...
def MaximumSum ( a , b , n ) : NEW_LINE INDENT dp = [ [ - 1 for j in range ( 2 ) ] for i in range ( n ) ] NEW_LINE dp [ 0 ] [ 0 ] = a [ 0 ] NEW_LINE dp [ 0 ] [ 1 ] = b [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] [ 0 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) + a [ i ] NEW_LINE dp [ i ] [...
Lexicographically Kth | Python3 program for the above approach ; Function to fill dp array ; Initialize all the entries with 0 ; Update dp [ 0 ] [ 0 ] to 1 ; Traverse the dp array ; Update the value of dp [ i ] [ j ] ; Recursive function to find the Kth lexicographical smallest string ; Handle the base cases ; If there...
from typing import Mapping NEW_LINE MAX = 30 NEW_LINE def findNumString ( X , Y , dp ) : NEW_LINE INDENT for i in range ( 0 , MAX ) : NEW_LINE INDENT for j in range ( 0 , MAX ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 0 , X + 1 ) : NEW_LINE INDENT for j in...
Maximum Tip Calculator | Function that finds the maximum tips from the given arrays as per the given conditions ; Base Condition ; If both have non - zero count then return max element from both array ; Traverse first array , as y count has become 0 ; Traverse 2 nd array , as x count has become 0 ; Drive Code ; Functio...
def maximumTip ( arr1 , arr2 , n , x , y ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if x != 0 and y != 0 : NEW_LINE INDENT return max ( arr1 [ n - 1 ] + maximumTip ( arr1 , arr2 , n - 1 , x - 1 , y ) , arr2 [ n - 1 ] + maximumTip ( arr1 , arr2 , n - 1 , x , y - 1 ) ) NEW_LINE DEDENT if y =...
Number of ways such that only K bars are visible from the left | Function to calculate the number of bars that are visible from the left for a particular arrangement ; If current element is greater than the last greater element , it is visible ; Function to calculate the number of rearrangements where K bars are visibl...
def noOfbarsVisibleFromLeft ( v ) : NEW_LINE INDENT last = 0 NEW_LINE ans = 0 NEW_LINE for u in v : NEW_LINE INDENT if ( last < u ) : NEW_LINE INDENT ans += 1 NEW_LINE last = u NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def nextPermutation ( nums ) : NEW_LINE INDENT i = len ( nums ) - 2 NEW_LINE while i > - 1 : ...
Number of ways such that only K bars are visible from the left | Function to calculate the number of permutations of N , where only K bars are visible from the left . ; Only ascending order is possible ; N is placed at the first position The nest N - 1 are arranged in ( N - 1 ) ! ways ; Recursing ; Driver code ; Input ...
def KvisibleFromLeft ( N , K ) : NEW_LINE INDENT if ( N == K ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( K == 1 ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT ans *= i NEW_LINE DEDENT return ans NEW_LINE DEDENT return KvisibleFromLeft ( N - 1 , K - 1 ) + ( N - 1 ) * KvisibleFr...
Minimum deletions in Array to make difference of adjacent elements non | Function for finding minimum deletions so that the array becomes non decreasing and the difference between adjacent elements also becomes non decreasing ; initialize answer to a large value ; generating all subsets ; checking the first condition ;...
def minimumDeletions ( A , N ) : NEW_LINE INDENT ans = 10 ** 8 NEW_LINE for i in range ( 1 , ( 1 << N ) ) : NEW_LINE INDENT temp = [ ] NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( ( i & ( 1 << j ) ) != 0 ) : NEW_LINE INDENT temp . append ( A [ j ] ) NEW_LINE DEDENT DEDENT flag = 0 NEW_LINE for j in range ( 1 , ...
Find maximum subset | Function to calculate maximum sum possible by taking at most K elements that is divisibly by D ; Variable to store final answer ; Traverse all subsets ; Update ans if necessary conditions are satisfied ; Driver code ; Input ; Function call
def maximumSum ( A , N , K , D ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( ( 1 << N ) ) : NEW_LINE INDENT sum = 0 NEW_LINE c = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( i >> j & 1 ) : NEW_LINE INDENT sum += A [ j ] NEW_LINE c += 1 NEW_LINE DEDENT DEDENT if ( sum % D == 0 and c <= K ) : NEW_LINE I...
Find the longest subsequence of a string that is a substring of another string | Function to find the longest subsequence that matches with the substring of other string ; Stores the lengths of strings X and Y ; Create a matrix ; Initialize the matrix ; Fill all the remaining rows ; If the characters are equal ; If not...
def longestSubsequence ( X , Y ) : NEW_LINE INDENT n = len ( X ) NEW_LINE m = len ( Y ) NEW_LINE mat = [ [ 0 for i in range ( m + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT for j in range ( 0 , m + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT mat [ i ] [ ...
Divide chocolate bar into pieces , minimizing the area of invalid pieces | Python3 program for the above approach ; Store valid dimensions ; Stores memoization ; Utility function to calculate minimum invalid area for Chocolate piece having dimension ( l , r ) ; Check whether current piece is valid or not If it is , the...
sz = 1001 NEW_LINE ok = [ [ 0 for i in range ( sz ) ] for i in range ( sz ) ] NEW_LINE dp = [ [ 0 for i in range ( sz ) ] for i in range ( sz ) ] NEW_LINE def minInvalidAreaUtil ( l , b ) : NEW_LINE INDENT global dp , ok NEW_LINE if ( dp [ l ] [ b ] == - 1 ) : NEW_LINE INDENT if ( ok [ l ] [ b ] ) : NEW_LINE INDENT dp ...
Count unordered pairs of equal elements for all subarrays | Function to count all pairs ( i , j ) such that arr [ i ] equals arr [ j ] in all possible subarrays of the array ; Stores the size of the array ; Stores the positions of all the distinct elements ; Append index corresponding to arr [ i ] in the map ; Traverse...
def countPairs ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE ans = 0 NEW_LINE M = { } NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if arr [ i ] in M : NEW_LINE INDENT M [ arr [ i ] ] . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT M [ arr [ i ] ] = [ i ] NEW_LINE DEDENT DEDENT for key , value in...
Number of alternating substrings from a given Binary String | Function to count number of alternating substrings from a given binary string ; Initialize dp array , where dp [ i ] [ j ] stores the number of alternating strings starts with i and having j elements . ; Traverse the string from the end ; If i is equal to N ...
def countAlternatingSubstrings ( S , N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( N ) ] for i in range ( 2 ) ] NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( i == N - 1 ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT dp [ 1 ] [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0...
Count ways to place ' + ' and ' | Function to count number of ways ' + ' and ' - ' operators can be placed in front of array elements to make the sum of array elements equal to K ; Stores sum of the array ; Stores count of 0 s in A [ ] ; Traverse the array ; Update sum ; Update count of 0 s ; Conditions where no arrang...
def solve ( A , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE c = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE if ( A [ i ] == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( K > sum or ( sum + K ) % 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT sum = ( sum + K ) // 2 NEW_LINE dp = [...
Rearrange an array to maximize sum of Bitwise AND of same | Function to implement recursive DP ; If i is equal to N ; If dp [ i ] [ mask ] is not equal to - 1 ; Iterate over the array B [ ] ; If current element is not yet selected ; Update dp [ i ] [ mask ] ; Return dp [ i ] [ mask ] ; Function to obtain maximum sum of...
def maximizeAnd ( i , mask , A , B , N , dp ) : NEW_LINE INDENT if ( i == N ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ mask ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ mask ] NEW_LINE DEDENT for j in range ( N ) : NEW_LINE INDENT if ( ( mask & ( 1 << j ) ) == 0 ) : NEW_LINE INDENT dp [ i ] [ mask ]...
Find the winner of a game of removing at most 3 stones from a pile in each turn | Function to find the maximum score of Player 1 ; Base Case ; If the result is already computed , then return the result ; Variable to store maximum score ; Pick one stone ; Pick 2 stones ; Pick 3 stones ; Return the score of the player ; ...
def maximumStonesUtil ( arr , n , i , dp ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = dp [ i ] NEW_LINE if ( ans != - 1 ) : NEW_LINE INDENT return ans NEW_LINE DEDENT ans = - 2 ** 31 NEW_LINE ans = max ( ans , arr [ i ] - maximumStonesUtil ( arr , n , i + 1 , dp ) ) NEW_LINE if ( i...
Count ways to reach the Nth station | Function to find the number of ways to reach Nth station ; Declares the DP [ ] array ; Only 1 way to reach station 1 ; Find the remaining states from the 2 nd station ; If the train A is present at station i - 1 ; If the train B is present at station i - 2 ; If train C is present a...
def numberOfWays ( N ) : NEW_LINE INDENT DP = [ [ 0 for i in range ( 5 ) ] for i in range ( N + 1 ) ] NEW_LINE DP [ 1 ] [ 1 ] = 1 NEW_LINE DP [ 1 ] [ 2 ] = 1 NEW_LINE DP [ 1 ] [ 3 ] = 1 NEW_LINE DP [ 1 ] [ 4 ] = 1 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( i - 1 > 0 and DP [ i - 1 ] [ 1 ] > 0 ) : NEW_...
Number of M | Function to find the number of M - length sorted arrays possible using numbers from the range [ 1 , N ] ; If size becomes equal to m , that means an array is found ; Include current element , increase size by 1 and remain on the same element as it can be included again ; Exclude current element ; Return t...
def countSortedArrays ( start , m , size , n ) : NEW_LINE INDENT if ( size == m ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( start > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT notTaken , taken = 0 , 0 NEW_LINE taken = countSortedArrays ( start , m , size + 1 , n ) NEW_LINE notTaken = countSortedArrays ( start ...
Maximum subarray sum possible after removing at most one subarray | Function to find maximum subarray sum possible after removing at most one subarray ; Calculate the preSum [ ] array ; Update the value of sum ; Update the value of maxSum ; Update the value of preSum [ i ] ; Calculate the postSum [ ] array ; Update the...
def maximumSum ( arr , n ) : NEW_LINE INDENT preSum = [ 0 ] * n NEW_LINE sum = 0 NEW_LINE maxSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = max ( arr [ i ] , sum + arr [ i ] ) NEW_LINE maxSum = max ( maxSum , sum ) NEW_LINE preSum [ i ] = maxSum NEW_LINE DEDENT sum = 0 NEW_LINE maxSum = 0 NEW_LINE postSu...
Count all unique outcomes possible by performing S flips on N coins | Function to recursively count the number of unique outcomes possible S flips are performed on N coins ; Base Cases ; Recursive Calls ; Driver Code
def numberOfUniqueOutcomes ( N , S ) : NEW_LINE INDENT if ( S < N ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( N == 1 or N == S ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( numberOfUniqueOutcomes ( N - 1 , S - 1 ) + numberOfUniqueOutcomes ( N - 1 , S - 2 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ '...
Length of longest increasing subsequence in a string | Function to find length of longest increasing subsequence in a string ; Stores at every i - th index , the length of the longest increasing subsequence ending with character i ; Size of string ; Stores the length of LIS ; Iterate over each character of the string ;...
def lisOtimised ( s ) : NEW_LINE INDENT dp = [ 0 ] * 30 NEW_LINE N = len ( s ) NEW_LINE lis = - 10 ** 9 NEW_LINE for i in range ( N ) : NEW_LINE INDENT val = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE curr = 0 NEW_LINE for j in range ( val ) : NEW_LINE INDENT curr = max ( curr , dp [ j ] ) NEW_LINE DEDENT curr += 1 NEW_L...
Sum of length of two smallest subsets possible from a given array with sum at least K | Python3 program for the above approach ; Function to calculate sum of lengths of two smallest subsets with sum >= K ; Sort the array in ascending order ; Stores suffix sum of the array ; Update the suffix sum array ; Stores all dp -...
MAX = 1e9 NEW_LINE def MinimumLength ( A , N , K ) : NEW_LINE INDENT A . sort ( ) NEW_LINE suffix = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT suffix [ i ] = suffix [ i + 1 ] + A [ i ] NEW_LINE DEDENT dp = [ [ 0 ] * ( K + 1 ) ] * ( N + 1 ) NEW_LINE for i in range ( N + 1 ) : NEW_L...
Count distinct possible Bitwise XOR values of subsets of an array | Stores the mask of the vector ; Stores the current 20 of dp [ ] ; Function to store the mask of given integer ; Iterate over the range [ 0 , 20 ] ; If i - th bit 0 ; If dp [ i ] is zero ; Store the position in dp ; Increment the answer ; Return from th...
dp = [ 0 ] * 20 NEW_LINE ans = 0 NEW_LINE def insertVector ( mask ) : NEW_LINE INDENT global dp , ans NEW_LINE for i in range ( 20 ) : NEW_LINE INDENT if ( ( mask & 1 << i ) == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( not dp [ i ] ) : NEW_LINE INDENT dp [ i ] = mask NEW_LINE ans += 1 NEW_LINE return NEW_LINE...
Maximize sum possible from an array by jumps of length i + K * arr [ i ] from any ith index | Function to find the maximum sum possible by jumps of length i + K * arr [ i ] from any i - th index ; Initialize an array dp [ ] ; Stores the maximum sum ; Iterate over the range [ N - 1 , 0 ] ; If length of the jump exceeds ...
def maxSum ( arr , N , K ) : NEW_LINE INDENT dp = [ 0 for i in range ( N + 2 ) ] NEW_LINE maxval = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( ( i + K * arr [ i ] ) >= N ) : NEW_LINE INDENT dp [ i ] = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = dp [ i + K * arr [ i ] ] + arr [ ...
Maximum sum submatrix | Function to find maximum sum submatrix ; Stores the number of rows and columns in the matrix ; Stores maximum submatrix sum ; Take each row as starting row ; Take each column as the starting column ; Take each row as the ending row ; Take each column as the ending column ; Stores the sum of subm...
def maxSubmatrixSum ( matrix ) : NEW_LINE INDENT r = len ( matrix ) NEW_LINE c = len ( matrix [ 0 ] ) NEW_LINE maxSubmatrix = 0 NEW_LINE for i in range ( r ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT for k in range ( i , r ) : NEW_LINE INDENT for l in range ( j , c ) : NEW_LINE INDENT sumSubmatrix = 0 NE...
Maximize sum of subsets from two arrays having no consecutive values | Function to calculate maximum subset sum ; Initialize array to store dp states ; Base Cases ; Pre initializing for dp [ 0 ] & dp [ 1 ] ; Calculating dp [ index ] based on above formula ; Prmaximum subset sum ; Given arrays ; Length of the array
def maximumSubsetSum ( arr1 , arr2 , length ) : NEW_LINE INDENT dp = [ 0 ] * ( length + 1 ) NEW_LINE if ( length == 1 ) : NEW_LINE INDENT print ( max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) NEW_LINE return NEW_LINE DEDENT if ( length == 2 ) : NEW_LINE INDENT print ( max ( max ( arr1 [ 1 ] , arr2 [ 1 ] ) , max ( arr1 [ 0 ] , arr2...
Modify array by replacing every array element with minimum possible value of arr [ j ] + | j | Function to find minimum value of arr [ j ] + | j - i | for every array index ; Stores minimum of a [ j ] + | i - j | upto position i ; Stores minimum of a [ j ] + | i - j | upto position i from the end ; Traversing and stori...
def minAtEachIndex ( n , arr ) : NEW_LINE INDENT dp1 = [ 0 ] * n NEW_LINE dp2 = [ 0 ] * n NEW_LINE i = 0 NEW_LINE dp1 [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp1 [ i ] = min ( arr [ i ] , dp1 [ i - 1 ] + 1 ) NEW_LINE DEDENT dp2 [ n - 1 ] = arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , - ...
Count all N | Function to prthe count of arrays satisfying given condition ; First element of array is set as 1 ; Since the first element of arr is 1 , the second element can 't be 1 ; Traverse the remaining indices ; If arr [ i ] = 1 ; If arr [ i ] a 1 ; Since last element needs to be 1 ; Driver Code ; Stores the coun...
def totalArrays ( N , M ) : NEW_LINE INDENT end_with_one = [ 0 ] * ( N + 1 ) ; NEW_LINE end_not_with_one = [ 0 ] * ( N + 1 ) ; NEW_LINE end_with_one [ 0 ] = 1 ; NEW_LINE end_not_with_one [ 0 ] = 0 ; NEW_LINE end_with_one [ 1 ] = 0 ; NEW_LINE end_not_with_one [ 1 ] = M - 1 ; NEW_LINE for i in range ( 2 , N ) : NEW_LINE ...
Count numbers from a given range whose product of digits is K | Function to find the product of digits of a number ; Stores product of digits of N ; Update res ; Update N ; Function to count numbers in the range [ 0 , X ] whose product of digit is K ; Stores count of numbers in the range [ L , R ] whose product of digi...
def prodOfDigit ( N ) : NEW_LINE INDENT res = 1 NEW_LINE while ( N ) : NEW_LINE INDENT res = res * ( N % 10 ) NEW_LINE N //= 10 NEW_LINE DEDENT return res NEW_LINE DEDENT def cntNumRange ( L , R , K ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( prodOfDigit ( i ) == K ) : NEW_L...
Median of Bitwise XOR of all submatrices starting from the top left corner | Function to find the median of bitwise XOR of all the submatrix whose topmost leftmost corner is ( 0 , 0 ) ; dp [ i ] [ j ] : Stores the bitwise XOR of submatrix having top left corner at ( 0 , 0 ) and bottom right corner at ( i , j ) ; Stores...
def findMedXOR ( mat , N , M ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( M ) ] for j in range ( N ) ] ; NEW_LINE med = [ 0 ] * ( N * M ) ; NEW_LINE dp [ 0 ] [ 0 ] = mat [ 0 ] [ 0 ] ; NEW_LINE med [ 0 ] = dp [ 0 ] [ 0 ] ; NEW_LINE len = 1 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i ...
Count ways to tile an N | Function to count the ways to tile N * 1 board using 1 * 1 and 2 * 1 tiles ; dp [ i ] : Stores count of ways to tile i * 1 board using given tiles ; Base Case ; Iterate over the range [ 2 , N ] ; Fill dp [ i ] using the recurrence relation ; Driver Code ; Given N ; Function Call
def countWaysToTileBoard ( N ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 1 ) NEW_LINE dp [ 0 ] = 1 NEW_LINE dp [ 1 ] = 2 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] = ( 2 * dp [ i - 1 ] + dp [ i - 2 ] ) NEW_LINE DEDENT print ( dp [ N ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT ...
Subsequences generated by including characters or ASCII value of characters of given string | Function to print subsequences containing ASCII value of the characters or the the characters of the given string ; Base Case ; If length of the subsequence exceeds 0 ; Print the subsequence ; Stores character present at i - t...
def FindSub ( string , res , i ) : NEW_LINE INDENT if ( i == len ( string ) ) : NEW_LINE INDENT if ( len ( res ) > 0 ) : NEW_LINE INDENT print ( res , end = " ▁ " ) ; NEW_LINE DEDENT return ; NEW_LINE DEDENT ch = string [ i ] ; NEW_LINE FindSub ( string , res , i + 1 ) ; NEW_LINE FindSub ( string , res + ch , i + 1 ) ;...
Minimize given flips required to reduce N to 0 | Function to find the minimum count of operations required to Reduce N to 0 ; Stores count of bits in N ; Recurrence relation ; Driver code
import math NEW_LINE def MinOp ( N ) : NEW_LINE INDENT if ( N <= 1 ) : NEW_LINE INDENT return N ; NEW_LINE DEDENT bit = ( int ) ( math . log ( N ) / math . log ( 2 ) ) + 1 ; NEW_LINE return ( ( 1 << bit ) - 1 ) - MinOp ( N - ( 1 << ( bit - 1 ) ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = ...
Maximum non | Function to find the maximum product from the top left and bottom right cell of the given matrix grid [ ] [ ] ; Store dimension of grid ; Stores maximum product path ; Stores minimum product path ; Traverse the grid and update maxPath and minPath array ; Initialize to inf and - inf ; Base Case ; Calculate...
def maxProductPath ( grid ) : NEW_LINE INDENT n , m = len ( grid ) , len ( grid [ 0 ] ) NEW_LINE maxPath = [ [ 0 for i in range ( m ) ] for j in range ( n ) ] NEW_LINE minPath = [ [ 0 for i in range ( m ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT mn ...
Smallest submatrix required to be removed such that sum of the remaining matrix is divisible by K | Python3 program to implement the above approach ; Function to find the length of the smallest subarray to be removed such that sum of elements is equal to S % K ; Remainder when total_sum is divided by K ; Stores curr_re...
import sys NEW_LINE def removeSmallestSubarray ( arr , S , n , k ) : NEW_LINE INDENT target_remainder = S % k NEW_LINE map1 = { } NEW_LINE map1 [ 0 ] = - 1 NEW_LINE curr_remainder = 0 NEW_LINE res = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_remainder = ( curr_remainder + arr [ i ] + k ) % k NEW...
Count N | to keep the string in lexicographically sorted order use start index to add the vowels starting the from that index ; base case : if string length is 0 add to the count ; if last character in string is ' e ' add vowels starting from ' e ' i . e ' e ' , ' i ' , ' o ' , 'u ; decrease the length of string ; char...
def countstrings ( n , start ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT cnt = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( start , 5 ) : NEW_LINE INDENT cnt += countstrings ( n - 1 , i ) NEW_LINE DEDENT return cnt NEW_LINE DEDENT def countVowelStrings ( n ) : NEW_LINE INDENT return...
Count N | Function to count N - length strings consisting of vowels only sorted lexicographically ; Driver Code ; Function Call
def findNumberOfStrings ( n ) : NEW_LINE INDENT return int ( ( n + 1 ) * ( n + 2 ) * ( n + 3 ) * ( n + 4 ) / 24 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE print ( findNumberOfStrings ( N ) ) NEW_LINE DEDENT
Count unique paths with given sum in an N | Python3 program for the above approach ; Function for counting total no of paths possible with the sum is equal to X ; If the path of the sum from the root to current node is stored in sum ; If already computed ; Count different no of paths using all possible ways ; Return to...
mod = int ( 1e9 + 7 ) NEW_LINE def findTotalPath ( X , n , dp ) : NEW_LINE INDENT if ( X == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT ans = 0 NEW_LINE if ( dp [ X ] != - 1 ) : NEW_LINE INDENT return dp [ X ] NEW_LINE DEDENT for i in range ( 1 , min ( X , n ) + 1 ) : NEW_LINE INDENT ans = ans + findTotalPath ( X - ...
Count sequences of positive integers having product X | Python3 program for the above approach ; Function to prthe total number of possible sequences with product X ; Precomputation of binomial coefficients ; Max length of a subsequence ; Ways dp array ; Fill i slots using all the primes ; Subtract ways for all slots t...
bin = [ [ 0 for i in range ( 3000 ) ] for i in range ( 3000 ) ] NEW_LINE def countWays ( arr ) : NEW_LINE INDENT mod = 10 ** 9 + 7 NEW_LINE bin [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , 3000 ) : NEW_LINE INDENT bin [ i ] [ 0 ] = 1 NEW_LINE for j in range ( 1 , i + 1 ) : NEW_LINE INDENT bin [ i ] [ j ] = ( bin [ i -...
Maximum subsequence sum obtained by concatenating disjoint subarrays whose lengths are prime | Python3 program for the above approach ; Function to return all prime numbers smaller than N ; Create a boolean array " prime [ 0 . . n ] " ; Initialize all its entries as true memset ( seive , true , sizeof ( seive ) ) ; If ...
MAX = 100005 NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT seive = [ True for i in range ( MAX ) ] NEW_LINE for p in range ( 2 , MAX ) : NEW_LINE INDENT if p * p > MAX : NEW_LINE INDENT break NEW_LINE DEDENT if ( seive [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , MAX , p ) : NEW_LINE INDENT seive...
Maximum possible score that can be obtained by constructing a Binary Tree based on given conditions | Function to find the maximum score for one possible tree having N nodes N - 1 Edges ; Number of nodes ; Initialize dp [ ] [ ] ; Score with 0 vertices is 0 ; Traverse the nodes from 1 to N ; Find maximum scores for each...
def maxScore ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE N += 1 NEW_LINE dp = [ [ - 100000 for i in range ( 2 * N ) ] for i in range ( N + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for s in range ( 1 , 2 * ( N - 1 ) + 1 ) : NEW_LINE INDENT j = 1 NEW_LINE while j <=...
Minimize cost of choosing and skipping array elements to reach end of the given array | Function to find the minimum cost to reach the end of the array from the first element ; Store the results ; Consider first index cost ; Find answer for each position i ; First Element ; Second Element ; For remaining element ; Cons...
def minimumCost ( cost , n , x ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 2 ) NEW_LINE dp [ 0 ] = cost [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( i == 1 ) : NEW_LINE INDENT dp [ i ] = cost [ i ] + dp [ i - 1 ] NEW_LINE DEDENT if ( i == 2 ) : NEW_LINE INDENT dp [ i ] = cost [ i ] + min ( dp [ i - 1 ] , x...