text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Minimize value of | A | Function to find the minimum possible value of | A - X | + | B - Y | + | C - Z | such that X * Y = Z for given A , B and C ; Stores the minimum value of | A - X | + | B - Y | + | C - Z | such that X * Y = Z ; Iterate over all values of i in the range [ 1 , 2 * C ] ; Iterate over all values of j such that i * j <= 2 * c ; Update the value of ans ; Return answer ; Driver Code | def minimizeCost ( A , B , C ) : NEW_LINE INDENT ans = A + B + C NEW_LINE for i in range ( 1 , 2 * C + 1 ) : NEW_LINE INDENT j = 0 NEW_LINE while ( i * j <= 2 * C ) : NEW_LINE INDENT ans = min ( ans , abs ( A - i ) + abs ( B - j ) + abs ( i * j - C ) ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A = 19 NEW_LINE B = 28 NEW_LINE C = 522 NEW_LINE print ( minimizeCost ( A , B , C ) ) NEW_LINE |
Average value of set bit count in given Binary string after performing all possible choices of K operations | Function to calculate the average number of Set bits after after given operations ; Stores the average number of set bits after current operation ; Stores the average number of set bits after current operation ; Iterate through the array arr [ ] and update the values of p and q ; Store the value of p and q of the previous state before their updation ; Update average number of set bits after performing the ith operation ; Update average number of off bits after performing the ith operation ; Return Answer ; Driver Code | def averageSetBits ( N , K , arr ) : NEW_LINE INDENT p = N NEW_LINE q = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT _p = p NEW_LINE _q = q NEW_LINE p = _p - _p * arr [ i ] / N + _q * arr [ i ] / N NEW_LINE q = _q - _q * arr [ i ] / N + _p * arr [ i ] / N NEW_LINE DEDENT return p NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE arr = [ 1 , 2 , 3 ] NEW_LINE K = len ( arr ) NEW_LINE print ( " % .2f " % averageSetBits ( N , K , arr ) ) NEW_LINE DEDENT |
Find maximum sum of subsequence after flipping signs of at most K elements in given Array | Function to calculate the max sum of subsequence ; Variable to store the max sum ; Sort the array ; Iterate over the array ; Flip sign ; Decrement k ; Traverse over the array ; Add only positive elements ; Return the max sum ; Driver Code ; Given array ; Variable to store number of flips are allowed ; Function call to find the maximum sum of subsequence | def maxSubseq ( arr , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT arr [ i ] = - arr [ i ] NEW_LINE K -= 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , - 10 , - 1 , 0 , - 4 , 2 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( maxSubseq ( arr , N , K ) ) NEW_LINE DEDENT |
Minimum number of intervals to cover the target interval | Function to find the minimum number of intervals in the array A [ ] to cover the entire target interval ; Sort the array A [ ] in increasing order of starting point ; Insert a pair of INT_MAX to prevent going out of bounds ; Stores start of current interval ; Stores end of current interval ; Stores the count of intervals ; Iterate over all the intervals ; If starting point of current index <= start ; Update the value of start ; Increment the value of count ; If the target interval is already covered or it is not possible to move then break the loop ; If the entire target interval is not covered ; Return Answer ; Driver Code | def minimizeSegment ( A , X ) : NEW_LINE INDENT A . sort ( ) NEW_LINE INT_MAX = 2147483647 NEW_LINE A . append ( [ INT_MAX , INT_MAX ] ) NEW_LINE start = X [ 0 ] NEW_LINE end = X [ 0 ] - 1 NEW_LINE cnt = 0 NEW_LINE for i in range ( 0 , len ( A ) ) : NEW_LINE INDENT if ( A [ i ] [ 0 ] <= start ) : NEW_LINE INDENT end = max ( A [ i ] [ 1 ] , end ) NEW_LINE i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = end NEW_LINE cnt = cnt + 1 NEW_LINE if ( A [ i ] [ 0 ] > end or end >= X [ 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if ( end < X [ 1 ] ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ [ 1 , 3 ] , [ 2 , 4 ] , [ 2 , 10 ] , [ 2 , 3 ] , [ 1 , 1 ] ] NEW_LINE X = [ 1 , 10 ] NEW_LINE print ( minimizeSegment ( A , X ) ) NEW_LINE DEDENT |
K | Function to calculate K - th smallest solution ( Y ) of equation X + Y = X | Y ; Initialize the variable to store the answer ; The i - th bit of X is off ; The i - bit of K is on ; Divide K by 2 ; If K becomes 0 then break ; Driver Code | def KthSolution ( X , K ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , 64 ) : NEW_LINE INDENT if ( not ( X & ( 1 << i ) ) ) : NEW_LINE INDENT if ( K & 1 ) : NEW_LINE INDENT ans |= ( 1 << i ) NEW_LINE DEDENT K >>= 1 NEW_LINE if ( not K ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 5 NEW_LINE K = 5 NEW_LINE print ( KthSolution ( X , K ) ) NEW_LINE DEDENT |
Rearrange sorted array such that all odd indices elements comes before all even indices element | Function to print the array ; Function to rearrange the array such that odd indexed elements come before even indexed elements ; Reduces the size of array by one because last element does not need to be changed in case N = odd ; Initialize the variables ; Iterate over the range ; Add the modified element at the odd position ; Iterate over the range ; Add the modified element at the even position ; Iterate over the range ; Divide by the maximum element ; Driver Code | def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT def rearrange ( arr , N ) : NEW_LINE INDENT if ( N & 1 ) : NEW_LINE INDENT N -= 1 NEW_LINE DEDENT odd_idx = 1 NEW_LINE even_idx = 0 NEW_LINE max_elem = arr [ N - 1 ] + 1 NEW_LINE for i in range ( N // 2 ) : NEW_LINE INDENT arr [ i ] += ( arr [ odd_idx ] % max_elem ) * max_elem NEW_LINE odd_idx += 2 NEW_LINE DEDENT for i in range ( N // 2 , N ) : NEW_LINE INDENT arr [ i ] += ( arr [ even_idx ] % max_elem ) * max_elem NEW_LINE even_idx += 2 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT arr [ i ] = arr [ i ] // max_elem NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 16 , 18 , 19 ] NEW_LINE N = len ( arr ) NEW_LINE rearrange ( arr , N ) NEW_LINE printArray ( arr , N ) ; NEW_LINE DEDENT |
Find range of values for S in given Array with values satisfying [ arr [ i ] = floor ( ( i * S ) / K ) ] | Python 3 program for the above approach ; Function to find the range of values for S in a given array that satisfies the given condition ; Stores the left range value ; Stores the right range value ; Find the current left range value for S ; Find the current right range value for S ; Updating L value ; Updating R value ; Driver Code | from math import ceil , floor NEW_LINE import sys NEW_LINE def findRange ( arr , N , K ) : NEW_LINE INDENT L = - sys . maxsize - 1 NEW_LINE R = sys . maxsize NEW_LINE for i in range ( N ) : NEW_LINE INDENT l = ceil ( 1.0 * arr [ i ] * K / ( i + 1 ) ) NEW_LINE r = ceil ( ( 1.0 + arr [ i ] ) * K / ( i + 1 ) - 1 ) NEW_LINE L = max ( L , l ) NEW_LINE R = min ( R , r ) NEW_LINE DEDENT print ( L , R ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 6 , 9 , 11 ] NEW_LINE K = 10 NEW_LINE N = len ( arr ) NEW_LINE findRange ( arr , N , K ) NEW_LINE DEDENT |
Find an anagram of given String having different characters at corresponding indices | Function to find anagram of string such that characters at the same indices are different ; Copying our original string for comparison ; Declaring the two pointers ; Checking the given condition ; When string length is odd ; The mid element ; If the characters are the same , then perform the swap operation as illustrated ; Check if the corresponding indices has the same character or not ; If string follows required condition ; Driver Code | def findAnagram ( s ) : NEW_LINE INDENT check = s NEW_LINE st = list ( s ) NEW_LINE i = 0 NEW_LINE j = len ( st ) - 1 NEW_LINE while ( i < len ( st ) and j >= 0 ) : NEW_LINE INDENT if ( st [ i ] != st [ j ] and check [ i ] != st [ j ] and check [ j ] != st [ i ] ) : NEW_LINE INDENT st [ i ] , st [ j ] = st [ j ] , st [ i ] NEW_LINE i += 1 NEW_LINE j = len ( st ) - 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT if ( len ( st ) % 2 != 0 ) : NEW_LINE INDENT mid = len ( st ) / 2 NEW_LINE if ( check [ mid ] == st [ mid ] ) : NEW_LINE INDENT for i in range ( len ( st ) ) : NEW_LINE INDENT if ( check [ i ] != st [ mid ] and st [ i ] != st [ mid ] ) : NEW_LINE INDENT st [ i ] , st [ mid ] = st [ mid ] , st [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT ok = True NEW_LINE for i in range ( len ( st ) ) : NEW_LINE INDENT if ( check [ i ] == st [ i ] ) : NEW_LINE INDENT ok = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( ok ) : NEW_LINE INDENT print ( " " . join ( st ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geek " NEW_LINE findAnagram ( S ) NEW_LINE DEDENT |
Lexicographically smallest permutation of [ 1 , N ] based on given Binary string | Function to generate the lexicographically smallest permutation according to the given criteria ; Stores the resultant permutation ; Initialize the first elements to 1 ; Traverse the given string S ; Number greater than last number ; Number equal to the last number ; Correct all numbers to the left of the current index ; Printing the permutation ; Driver Code | def constructPermutation ( S , N ) : NEW_LINE INDENT ans = [ 0 ] * N NEW_LINE ans [ 0 ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( S [ i - 1 ] == '0' ) : NEW_LINE INDENT ans [ i ] = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans [ i ] = ans [ i - 1 ] NEW_LINE DEDENT for j in range ( i ) : NEW_LINE INDENT if ( ans [ j ] >= ans [ i ] ) : NEW_LINE INDENT ans [ j ] += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( ans [ i ] , end = " " ) NEW_LINE if ( i != N - 1 ) : NEW_LINE INDENT print ( " β " , end = " " ) NEW_LINE DEDENT DEDENT DEDENT S = "100101" NEW_LINE constructPermutation ( S , len ( S ) + 1 ) NEW_LINE |
Kth smallest positive integer Y such that its sum with X is same as its bitwise OR with X | Function to calculate K - th smallest solution ( Y ) of equation X + Y = X | Y ; Initialize the variable to store the answer ; The i - th bit of X is off ; The i - bit of K is on ; Divide K by 2 ; If K becomes 0 then break ; Driver Code | def KthSolution ( X , K ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 64 ) : NEW_LINE INDENT if not ( X & ( 1 << i ) ) : NEW_LINE INDENT if ( K & 1 ) : NEW_LINE INDENT ans |= ( 1 << i ) NEW_LINE DEDENT K >>= 1 NEW_LINE if not K : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT X = 10 NEW_LINE K = 5 NEW_LINE print ( KthSolution ( X , K ) ) NEW_LINE |
Count of distinct N | Function to find the count of distinct arrays of size n having elements in range [ 1 , k ] and all adjacent elements ( P , Q ) follows ( P <= Q ) or ( P % Q > 0 ) ; Stores the divisors of all integers in the range [ 1 , k ] ; Calculate the divisors of all integers using the Sieve ; Stores the dp states such that dp [ i ] [ j ] with i elements having j as the last element of array ; Initialize the dp array ; Calculate the dp states using the derived relation ; Calculate the sum for len - 1 ; Subtract dp [ len - 1 ] [ j ] for each factor of j from [ 1 , K ] ; Calculate the final result ; Return the resultant sum ; Driver Code | def countArrays ( n , k ) : NEW_LINE INDENT divisors = [ [ ] for i in range ( k + 1 ) ] NEW_LINE for i in range ( 1 , k + 1 , 1 ) : NEW_LINE INDENT for j in range ( 2 * i , k + 1 , i ) : NEW_LINE INDENT divisors [ j ] . append ( i ) NEW_LINE DEDENT DEDENT dp = [ [ 0 for i in range ( k + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for j in range ( 1 , k + 1 , 1 ) : NEW_LINE INDENT dp [ 1 ] [ j ] = 1 NEW_LINE DEDENT for x in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( 1 , k + 1 , 1 ) : NEW_LINE INDENT sum += dp [ x - 1 ] [ j ] NEW_LINE DEDENT for y in range ( 1 , k + 1 , 1 ) : NEW_LINE INDENT dp [ x ] [ y ] = sum NEW_LINE for d in divisors [ y ] : NEW_LINE INDENT dp [ x ] [ y ] = ( dp [ x ] [ y ] - dp [ x - 1 ] [ d ] ) NEW_LINE DEDENT DEDENT DEDENT sum = 0 NEW_LINE for j in range ( 1 , k + 1 , 1 ) : NEW_LINE INDENT sum += dp [ n ] [ j ] NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE K = 3 NEW_LINE print ( countArrays ( N , K ) ) NEW_LINE DEDENT |
Minimize increment | Function to calculate the minimum number of operations to convert array A to array B by incrementing and decrementing adjacent elements ; Stores the final count ; Stores the sum of array A and B respectivelly ; Check of the sums are unequall ; Pointer to iterate through array ; Case 1 where A [ i ] > B [ i ] ; Stores the extra values for the current index ; Iterate the array from [ i - 1 , 0 ] ; Stores the count of values being transfered from A [ i ] to A [ j ] ; Add operation count ; Iterate the array in right direction id A [ i ] - B [ i ] > 0 ; Iterate the array from [ i + 1 , n - 1 ] ; Stores the count of values being transfered from A [ i ] to A [ j ] ; Add operation count ; Return Answer ; Driver Code ; Function Call | def minimumMoves ( A , B , N ) : NEW_LINE INDENT ans = 0 NEW_LINE sum_A = 0 NEW_LINE sum_B = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum_A += A [ i ] NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT sum_B += B [ i ] NEW_LINE DEDENT if ( sum_A != sum_B ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT i = 0 NEW_LINE while ( i < N ) : NEW_LINE INDENT if ( A [ i ] > B [ i ] ) : NEW_LINE INDENT temp = A [ i ] - B [ i ] NEW_LINE j = i - 1 NEW_LINE while ( j >= 0 and temp > 0 ) : NEW_LINE INDENT if ( B [ j ] > A [ j ] ) : NEW_LINE INDENT cnt = min ( temp , ( B [ j ] - A [ j ] ) ) NEW_LINE A [ j ] += cnt NEW_LINE temp -= cnt NEW_LINE ans += ( cnt * abs ( j - i ) ) NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT if ( temp > 0 ) : NEW_LINE INDENT j = i + 1 NEW_LINE while ( j < N and temp > 0 ) : NEW_LINE INDENT if ( B [ j ] > A [ j ] ) : NEW_LINE INDENT cnt = min ( temp , ( B [ j ] - A [ j ] ) ) NEW_LINE A [ j ] += cnt NEW_LINE temp -= cnt NEW_LINE ans += ( cnt * abs ( j - i ) ) NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT i += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 5 , 7 ] NEW_LINE B = [ 13 , 0 , 0 ] NEW_LINE N = len ( A ) NEW_LINE print ( minimumMoves ( A , B , N ) ) NEW_LINE DEDENT |
Check if X can be reduced to 0 in exactly T moves by substracting D or 1 from it | Function to check the above problem condition ; Check the base case . ; check if X - T is a divisor of D - 1 ; Driver code | def possibleReachingSequence ( X , D , T ) : NEW_LINE INDENT if X < T : NEW_LINE INDENT return " NO " NEW_LINE DEDENT if T * D < X : NEW_LINE INDENT return " NO " NEW_LINE DEDENT if ( X - T ) % ( D - 1 ) == 0 : NEW_LINE INDENT return " YES " NEW_LINE DEDENT return " NO " NEW_LINE DEDENT X = 10 NEW_LINE D = 3 NEW_LINE T = 6 NEW_LINE print ( possibleReachingSequence ( X , D , T ) ) NEW_LINE |
Maximum number of times Array can be reduced in half when its all elements are even | Python 3 code implementation for the above approach ; Function to return the number of operations possible ; counter to store the number of times the current element is divisible by 2 ; variable to store the final answer ; Initialize the counter to zero for each element ; update the counter till the number is divisible by 2 ; update the answer as the minimum of all the counts ; Driver code | import sys NEW_LINE def arrayDivisionByTwo ( arr , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT arr [ i ] = arr [ i ] // 2 NEW_LINE cnt += 1 NEW_LINE DEDENT ans = min ( ans , cnt ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 12 , 40 ] NEW_LINE n = len ( arr ) NEW_LINE print ( arrayDivisionByTwo ( arr , n ) ) NEW_LINE DEDENT |
Find smallest number with given digits and sum of digits | Function to print minimum integer having only digits P and Q and the sum of digits as N ; If Q is greater that P then swap the values of P and Q ; If P and Q are both zero or if Q is zero and N is not divisible by P then there is no possible integer which satisfies the given conditions ; Loop to find the maximum value of count_P that also satisfy P * count_P + Q * count_Q = N ; If N is 0 , their is a valid integer possible that satisfies all the requires conditions ; Print Answer ; Driver Code ; Function Call | def printMinInteger ( P , Q , N ) : NEW_LINE INDENT if ( Q > P ) : NEW_LINE INDENT t = P NEW_LINE P = Q NEW_LINE Q = t NEW_LINE DEDENT if ( Q == 0 and ( P == 0 or N % P != 0 ) ) : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE return NEW_LINE DEDENT count_P = 0 NEW_LINE count_Q = 0 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N % P == 0 ) : NEW_LINE INDENT count_P += N / P NEW_LINE N = 0 NEW_LINE DEDENT else : NEW_LINE INDENT N = N - Q NEW_LINE count_Q += 1 NEW_LINE DEDENT DEDENT if ( N == 0 ) : NEW_LINE INDENT for i in range ( count_Q ) : NEW_LINE INDENT print ( Q , end = " " ) NEW_LINE DEDENT for i in range ( int ( count_P ) ) : NEW_LINE INDENT print ( P , end = " " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT DEDENT N = 32 NEW_LINE P = 7 NEW_LINE Q = 4 NEW_LINE printMinInteger ( P , Q , N ) NEW_LINE |
Minimum number of sum and modulo operations using given numbers to reach target | Function to find the minimum moves to reach K from N ; Initialization of dp vector ; dp [ i ] = minimum pushes required to reach i ; Traversing through the buttons ; Iterating through all the positions ; If not visited ; Next status of lock ; Advance to next state ; Return the final dp [ target ] ; Given Input ; Function Call | def minPushes ( N , K , arr ) : NEW_LINE INDENT dp = [ - 1 ] * 100000 NEW_LINE dp [ N ] = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT for xx in range ( 100000 ) : NEW_LINE INDENT x = xx NEW_LINE if ( dp [ x ] == - 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT next = ( x + arr [ i ] ) % 100000 NEW_LINE while ( dp [ next ] == - 1 or dp [ next ] > dp [ x ] + 1 ) : NEW_LINE INDENT dp [ next ] = dp [ x ] + 1 NEW_LINE x = next NEW_LINE next = ( next + arr [ i ] ) % 100000 NEW_LINE DEDENT DEDENT DEDENT return dp [ K ] NEW_LINE DEDENT N = 99880 NEW_LINE K = 89 NEW_LINE arr = [ 100 , 3 ] NEW_LINE print ( minPushes ( N , K , arr ) ) NEW_LINE |
Minimum number of Apples to be collected from trees to guarantee M red apples | Function to minimum no . of apples ; If we get all required apple from South ; If we required trees at East and West ; If we doesn 't have enough red apples ; Driver Code ; No . of red apple for gift ; No . of red apple in each tree ; No . of tree in North ; No . of tree in South ; No . of tree in West ; No . of tree in East ; Function Call | def minApples ( ) : NEW_LINE INDENT if M <= S * K : NEW_LINE INDENT return M NEW_LINE DEDENT elif M <= S * K + E + W : NEW_LINE INDENT return S * K + ( M - S * K ) * K NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT M = 10 NEW_LINE K = 15 NEW_LINE N = 0 NEW_LINE S = 1 NEW_LINE W = 0 NEW_LINE E = 0 NEW_LINE ans = minApples ( ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Minimum increments or decrements required to signs of prefix sum array elements alternating | Function to find the minimum number of increments / decrements of array elements by 1 to make signs of prefix sum array elements alternating ; Case 1. neg - pos - neg ; Stores the current sign of the prefix sum of array ; Stores minimum number of operations for Case 1 ; Traverse the array ; Checking both conditions ; Update the current prefix1 to currentPrefixSum ; Case 2. pos - neg - pos ; Stores the prefix sum of array ; Stores minimum number of operations for Case 1 ; Checking both conditions ; Update the current prefix2 to currentPrefixSum ; Driver Code | def minimumOperations ( A , N ) : NEW_LINE INDENT cur_prefix_1 = 0 NEW_LINE parity = - 1 NEW_LINE minOperationsCase1 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cur_prefix_1 += A [ i ] NEW_LINE if ( cur_prefix_1 == 0 or parity * cur_prefix_1 < 0 ) : NEW_LINE INDENT minOperationsCase1 += abs ( parity - cur_prefix_1 ) NEW_LINE cur_prefix_1 = parity NEW_LINE DEDENT parity *= - 1 NEW_LINE DEDENT cur_prefix_2 = 0 NEW_LINE parity = 1 NEW_LINE minOperationsCase2 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cur_prefix_2 += A [ i ] NEW_LINE if ( cur_prefix_2 == 0 or parity * cur_prefix_2 < 0 ) : NEW_LINE INDENT minOperationsCase2 += abs ( parity - cur_prefix_2 ) NEW_LINE cur_prefix_2 = parity NEW_LINE DEDENT parity *= - 1 NEW_LINE DEDENT return min ( minOperationsCase1 , minOperationsCase2 ) NEW_LINE DEDENT A = [ 1 , - 3 , 1 , 0 ] NEW_LINE N = len ( A ) NEW_LINE print ( minimumOperations ( A , N ) ) NEW_LINE |
Generate an array of maximum sum such that each element exceeds all elements present either on its left or right | Function to construct the array having maximum sum satisfying the given criteria ; Declaration of the array arrA [ ] and ans [ ] ; Stores the maximum sum of the resultant array ; Initialize the array arrA [ ] ; Traversing the array arrA [ ] ; Initialize the array arrB [ ] ; Assign the maximum element to the current element ; Form the first increasing till every index i ; Make the current element as the maximum element ; Forming decreasing from the index i + 1 to the index N ; Initialize the sum ; Find the total sum ; Check if the total sum is at least the sum found then make ans as ansB ; Print the final array formed ; Driver Code | def maximumSumArray ( arr , N ) : NEW_LINE INDENT arrA = [ 0 ] * N NEW_LINE ans = [ 0 ] * N NEW_LINE maxSum = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT arrA [ i ] = arr [ i ] ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT arrB = [ 0 ] * N NEW_LINE maximum = arrA [ i ] ; NEW_LINE arrB [ i ] = maximum ; NEW_LINE temp = 0 NEW_LINE for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT arrB [ j ] = min ( maximum , arrA [ j ] ) ; NEW_LINE maximum = arrB [ j ] ; NEW_LINE temp = j NEW_LINE DEDENT maximum = arrA [ i ] ; NEW_LINE for j in range ( i + 1 , N ) : NEW_LINE INDENT arrB [ j ] = min ( maximum , arrA [ j ] ) ; NEW_LINE maximum = arrB [ j ] ; NEW_LINE DEDENT sum = 0 ; NEW_LINE for j in range ( N ) : NEW_LINE INDENT sum += arrB [ j ] ; NEW_LINE DEDENT if ( sum > maxSum ) : NEW_LINE INDENT maxSum = sum ; NEW_LINE ans = arrB ; NEW_LINE DEDENT DEDENT for val in ans : NEW_LINE INDENT print ( val ) ; NEW_LINE DEDENT DEDENT A = [ 10 , 6 , 8 ] ; NEW_LINE N = len ( A ) NEW_LINE maximumSumArray ( A , N ) ; NEW_LINE |
Minimize product of two scores possible by at most M reductions | Utility function to find the minimum product of R1 and R2 possible ; Reaching to its limit ; If M is remaining ; Function to find the minimum product of R1 and R2 ; Case 1 - R1 reduces first ; case 2 - R2 reduces first ; Driver Code ; Given Input ; Function Call | def minProductUtil ( R1 , B1 , R2 , B2 , M ) : NEW_LINE INDENT x = min ( R1 - B1 , M ) NEW_LINE M -= x NEW_LINE R1 -= x NEW_LINE if M > 0 : NEW_LINE INDENT y = min ( R2 - B2 , M ) NEW_LINE M -= y NEW_LINE R2 -= y NEW_LINE DEDENT return R1 * R2 NEW_LINE DEDENT def minProduct ( R1 , B1 , R2 , B2 , M ) : NEW_LINE INDENT res1 = minProductUtil ( R1 , B1 , R2 , B2 , M ) NEW_LINE res2 = minProductUtil ( R2 , B2 , R1 , B1 , M ) NEW_LINE return min ( res1 , res2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT R1 = 21 ; B1 = 10 ; R2 = 13 ; B2 = 11 ; M = 3 NEW_LINE print ( minProduct ( R1 , B1 , R2 , B2 , M ) ) NEW_LINE DEDENT |
Maximize the profit after selling the tickets | Set 2 ( For elements in range [ 1 , 10 ^ 6 ] ) | Function to find maximum profit after selling K tickets ; Frequency array to store freq of every element of the array ; Modify the arr [ ] so that the array is sorted in O ( N ) ; Variable to store answer ; Traverse the array while K > 0 and j >= 0 ; If arr [ i ] > arr [ j ] then ticket can be brought from counter [ j + 1 , N ] ; If arr [ j ] = = arr [ i ] decrement j until arr [ j ] != arr [ i ] ; Sell tickets from counter [ j + 1 , N ] ; All elements of array are equal Send tickets from each counter 1 time until K > 0. ; Converting answer from long long to int ; Driver Code ; Given Input ; Function Call | def maxAmount ( n , k , arr ) : NEW_LINE INDENT A = [ 0 for i in range ( 1000001 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT A [ arr [ i ] ] += 1 NEW_LINE DEDENT j = 0 NEW_LINE for j in range ( 1000001 ) : NEW_LINE INDENT while ( A [ i ] != 0 ) : NEW_LINE INDENT arr [ j ] = i ; NEW_LINE j += 1 NEW_LINE A [ i ] -= 1 NEW_LINE DEDENT DEDENT ans = 6 NEW_LINE mod = 1000000007 NEW_LINE i = n - 1 NEW_LINE j = n - 2 NEW_LINE while ( k > 0 and j >= 0 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] ) : NEW_LINE INDENT ans = ans + min ( k , ( i - j ) ) * arr [ i ] NEW_LINE k = k - ( i - j ) NEW_LINE arr [ i ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT while ( j >= 0 and arr [ j ] == arr [ i ] ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if ( j < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT ans = ans + min ( k , ( i - j ) ) * arr [ i ] NEW_LINE k = k - ( i - j ) NEW_LINE arr [ i ] -= 1 NEW_LINE DEDENT DEDENT while ( k > 0 and arr [ i ] != 0 ) : NEW_LINE INDENT ans = ans + min ( n , k ) * arr [ i ] NEW_LINE k -= n NEW_LINE arr [ i ] -= 1 NEW_LINE DEDENT ans = ans % mod NEW_LINE x = ans NEW_LINE return x NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE k = 3 NEW_LINE arr = [ 4 , 3 , 6 , 2 , 4 ] NEW_LINE ans = maxAmount ( n , k , arr ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Maximize sum of averages of subsequences of lengths lying in a given range | Function to find the maximum sum of average of groups ; Sort the given array ; Stores the sum of averages ; Stores count of array element ; Add the current value to the variable sum ; Increment the count by 1 ; If the current size is X ; If the remaining elements can 't become a group ; Iterate until i is less than N ; Update the value of X ; Update the average ; Find the average ; Reset the sum and count ; Print maximum sum of averages ; Driver Code | def maxAverage ( A , N , X , Y ) : NEW_LINE INDENT A . sort ( ) NEW_LINE sum = 0 NEW_LINE res = 0 NEW_LINE count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE count += 1 NEW_LINE if ( count == X ) : NEW_LINE INDENT if ( N - i - 1 < X ) : NEW_LINE INDENT i += 1 NEW_LINE cnt = 0 NEW_LINE while ( i < N ) : NEW_LINE INDENT cnt += 1 NEW_LINE sum += A [ i ] NEW_LINE i += 1 NEW_LINE DEDENT X = X + cnt NEW_LINE res += sum / X NEW_LINE break NEW_LINE DEDENT res += sum / X NEW_LINE sum = 0 NEW_LINE count = 0 NEW_LINE DEDENT DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 4 , 10 , 6 , 5 ] NEW_LINE N = len ( A ) NEW_LINE X = 2 NEW_LINE Y = 3 NEW_LINE maxAverage ( A , N , X , Y ) NEW_LINE DEDENT |
Rearrange characters in a sorted string such that no pair of adjacent characters are the same | Python 3 program for the above approach ; Function to check if a string S contains pair of adjacent characters that are equal or not ; Traverse the string S ; If S [ i ] and S [ i + 1 ] are equal ; Otherwise , return false ; Function to rearrange characters of a string such that no pair of adjacent characters are the same ; Initialize 3 variables ; Iterate until k < N ; If S [ i ] is not equal to S [ j ] ; Increment i and j by 1 ; If j equals k and increment the value of K by 1 ; Else ; If S [ j ] equals S [ k ] ; Increment k by 1 ; Else ; Swap ; Increment i and j by 1 ; If j equals k ; Increment k by 1 ; Function to rearrange characters in a string so that no two adjacent characters are same ; If string is already valid ; If size of the string is 2 ; Function Call ; Reversing the string ; Function Call ; If the string is valid ; Otherwise ; Driver Code | S = " aaabc " NEW_LINE def isAdjChar ( s ) : NEW_LINE INDENT for i in range ( len ( s ) - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def rearrangeStringUtil ( N ) : NEW_LINE INDENT global S NEW_LINE S = list ( S ) NEW_LINE i = 0 NEW_LINE j = 1 NEW_LINE k = 2 NEW_LINE while ( k < N ) : NEW_LINE INDENT if ( S [ i ] != S [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE j += 1 NEW_LINE if ( j == k ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( S [ j ] == S [ k ] ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp = S [ k ] NEW_LINE S [ k ] = S [ j ] NEW_LINE S [ j ] = temp NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE if ( j == k ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT S = ' ' . join ( S ) NEW_LINE DEDENT def rearrangeString ( N ) : NEW_LINE INDENT global S NEW_LINE if ( isAdjChar ( S ) == False ) : NEW_LINE INDENT return S NEW_LINE DEDENT if ( len ( S ) == 2 ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT rearrangeStringUtil ( N ) NEW_LINE S = S [ : : - 1 ] NEW_LINE rearrangeStringUtil ( N ) NEW_LINE if ( isAdjChar ( S ) == False ) : NEW_LINE INDENT return S NEW_LINE DEDENT return " - 1" NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = len ( S ) NEW_LINE print ( rearrangeString ( N ) ) NEW_LINE DEDENT |
Lexicographically largest string possible by repeatedly appending first character of two given strings | Function to make the lexicographically largest string by merging two strings ; Stores the resultant string ; If the string word1 is lexographically greater than or equal to word2 ; Update the string merge ; Erase the first index of the string word1 ; Otherwise ; Update the string merge ; Erase the first index of the string word2 ; Return the final string ; Driver code | def largestMerge ( word1 , word2 ) : NEW_LINE INDENT merge = " " NEW_LINE while len ( word1 ) != 0 or len ( word2 ) != 0 : NEW_LINE INDENT if word1 >= word2 : NEW_LINE INDENT merge = merge + word1 [ 0 ] NEW_LINE word1 = word1 [ 1 : ] NEW_LINE DEDENT else : NEW_LINE INDENT merge = merge + word2 [ 0 ] NEW_LINE word2 = word2 [ 1 : ] NEW_LINE DEDENT DEDENT return merge NEW_LINE DEDENT S1 = " xyzxyz " NEW_LINE S2 = " xywzxyx " NEW_LINE print ( largestMerge ( S1 , S2 ) ) NEW_LINE |
Maximum rods to put horizontally such that no two rods overlap on X coordinate | Python 3 program for the above approach ; Function to find the maximum number of rods that can be put horizontally ; Stores the result ; Stores the last occupied point ; Traverse the array arr [ ] ; If the current point can be put on the left side ; Increment the ans by 1 ; Update prev ; Else if the given point can be put on the right side ; Increment the ans by 1 ; Update prev ; Otherwise , ; Update prev ; Return the ans ; Driver Code | import sys NEW_LINE def findMaximumPoints ( N , X , H ) : NEW_LINE INDENT ans = 0 NEW_LINE prev = - sys . maxsize - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( prev < ( X [ i ] - H [ i ] ) ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = X [ i ] NEW_LINE DEDENT elif ( i == N - 1 or ( X [ i ] + H [ i ] ) < X [ i + 1 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = X [ i ] + H [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT prev = X [ i ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = [ 1 , 2 , 3 ] NEW_LINE H = [ 2 , 5 , 5 ] NEW_LINE N = len ( X ) NEW_LINE print ( findMaximumPoints ( N , X , H ) ) NEW_LINE DEDENT |
Maximize the missing values in given time in HH : MM format | Function to find the maximum time by replacing ' ? ' by any digits ; If the 0 th index is '? ; If the 1 st index is '? ; If the 3 rd index is '? ; If the 4 th index is '? ; Return new string ; Driver Code | def maxTime ( s ) : NEW_LINE ' NEW_LINE INDENT s = list ( s ) NEW_LINE if ( s [ 0 ] == ' ? ' ) : NEW_LINE INDENT if ( s [ 1 ] <= '3' or s [ 1 ] == ' ? ' ) : NEW_LINE INDENT s [ 0 ] = '2' NEW_LINE DEDENT else : NEW_LINE INDENT s [ 0 ] = '1' NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT if ( s [ 1 ] == ' ? ' ) : NEW_LINE INDENT if ( s [ 0 ] != '2' ) : NEW_LINE INDENT s [ 1 ] = 9 NEW_LINE DEDENT else : NEW_LINE INDENT s [ 1 ] = 3 NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT if ( s [ 3 ] == ' ? ' ) : NEW_LINE INDENT s [ 3 ] = '5' NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( s [ 4 ] == ' ? ' ) : NEW_LINE INDENT s [ 4 ] = '9' NEW_LINE DEDENT print ( " " . join ( s ) ) NEW_LINE DEDENT S = " ? 4:5 ? " NEW_LINE maxTime ( S ) NEW_LINE |
Maximum GCD of two numbers possible by adding same value to them | Function to calculate maximum gcd of two numbers possible by adding same value to both a and b ; Given Input | def maxGcd ( a , b ) : NEW_LINE INDENT print ( abs ( a - b ) ) NEW_LINE DEDENT a = 2231 NEW_LINE b = 343 NEW_LINE maxGcd ( a , b ) NEW_LINE |
Count the combination of 4 s and / or 5 s required to make each Array element 0 | Function to print the count of the combination of 4 or 5 required to make the arr [ i ] for each 0 < i < N ; Vector to store the answer ; Iterate in the range [ 0 , N - 1 ] ; Initialize sum to store the count of numbers and cnt for the current factor of 4 ; Iterate in the range [ 0 , arr [ i ] ] with increment of 4 ; Check if arr [ i ] - j ( the current factor of 4 ) is divisible by 5 or not ; If sum is not maximum then answer is found ; Finally , print the required answer ; Given Input ; Function Call | def sumOfCombinationOf4OR5 ( arr , N ) : NEW_LINE INDENT ans = [ - 1 for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] < 4 ) : NEW_LINE INDENT continue NEW_LINE DEDENT sum = 10 ** 9 NEW_LINE cnt = 0 NEW_LINE for j in range ( 0 , arr [ i ] + 1 , 4 ) : NEW_LINE INDENT if ( ( arr [ i ] - j ) % 5 == 0 ) : NEW_LINE INDENT sum = min ( sum , cnt + ( arr [ i ] - j ) // 5 ) NEW_LINE DEDENT cnt += 1 NEW_LINE DEDENT if ( sum != 10 ** 9 ) : NEW_LINE INDENT ans [ i ] = sum NEW_LINE DEDENT DEDENT for num in ans : NEW_LINE INDENT print ( num , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 7 , 15 , 17 , 22 ] NEW_LINE N = len ( arr ) NEW_LINE sumOfCombinationOf4OR5 ( arr , N ) NEW_LINE |
Find an N | Function to find an N - length binary string having maximum sum of elements from all given ranges ; Iterate over the range [ 1 , N ] ; If i is odd , then print 0 ; Otherwise , print 1 ; Driver Code ; Function Call | def printBinaryString ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i % 2 ) : NEW_LINE INDENT print ( 0 , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( 1 , end = " " ) ; NEW_LINE DEDENT DEDENT DEDENT N = 5 ; NEW_LINE M = 3 ; NEW_LINE arr = [ [ 1 , 3 ] , [ 2 , 4 ] , [ 2 , 5 ] ] ; NEW_LINE printBinaryString ( arr , N ) ; NEW_LINE |
Maximize 0 s in given Array after replacing each element A [ i ] with ( A [ i ] * D + B [ i ] ) | Python program for the above approach ; Function to find the maximum number of 0 s in the array A [ ] after changing the array element to A [ i ] * D + B [ i ] ; Stores the frequency of fractions needed to make each element 0 ; Stores the maximum number of 0 ; Traverse the array ; Find the numerator and the denominator ; Check if den is not equal to 0 ; Divide num and den by their gcd ; Check if num is not greater than 0 ; Check if both num and den are equal to 0 ; Increment the value of { num , den } in the map ; Update the value of ans ; Prthe value of ans + cnt ; Driver Code | from math import gcd NEW_LINE def maxZeroes ( A , B ) : NEW_LINE INDENT mp = { } NEW_LINE N = len ( A ) NEW_LINE ans = 0 NEW_LINE cnt = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT num = - B [ i ] NEW_LINE den = A [ i ] NEW_LINE gc = gcd ( num , den ) NEW_LINE if ( den != 0 ) : NEW_LINE INDENT num //= gc NEW_LINE den //= gc NEW_LINE DEDENT if ( num <= 0 ) : NEW_LINE INDENT num *= - 1 NEW_LINE den *= - 1 NEW_LINE DEDENT if ( den == 0 and num == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if ( den != 0 ) : NEW_LINE INDENT mp [ ( num , den ) ] = mp . get ( ( num , den ) , 0 ) + 1 NEW_LINE ans = max ( mp [ ( num , den ) ] , ans ) NEW_LINE DEDENT DEDENT print ( ans + cnt ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , - 1 ] NEW_LINE B = [ - 6 , - 12 , 6 ] NEW_LINE maxZeroes ( A , B ) NEW_LINE DEDENT |
Minimum cost to complete given tasks if cost of 1 , 7 and 30 days are given | Function to find the minimum cost to hire the workers for the given days in the array days [ ] ; Initialize the array dp ; Minimum Cost for Nth day ; Poleter of the array arr [ ] ; Traverse from right to left ; If worker is hired for 1 day ; If worker is hired for 7 days ; If worker is hired for 30 days ; Update the value of dp [ i ] as minimum of 3 options ; If the day is not at the array arr [ ] ; Return the answer ; Driver Code | def MinCost ( days , cost , N ) : NEW_LINE INDENT size = days [ N - 1 ] + 1 NEW_LINE dp = [ 0 for i in range ( size ) ] NEW_LINE dp [ size - 1 ] = min ( cost [ 0 ] , min ( cost [ 1 ] , cost [ 2 ] ) ) NEW_LINE ptr = N - 2 NEW_LINE for i in range ( size - 2 , 0 , - 1 ) : NEW_LINE INDENT if ( ptr >= 0 and days [ ptr ] == i ) : NEW_LINE INDENT val1 = dp [ i + 1 ] + cost [ 0 ] NEW_LINE val2 = cost [ 1 ] + ( 0 if ( i + 7 >= size ) else dp [ i + 7 ] ) NEW_LINE val3 = cost [ 2 ] + ( 0 if ( i + 30 >= size ) else dp [ i + 30 ] ) NEW_LINE dp [ i ] = min ( val1 , min ( val2 , val3 ) ) NEW_LINE ptr -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = dp [ i + 1 ] NEW_LINE DEDENT DEDENT return dp [ 1 ] NEW_LINE DEDENT arr = [ 2 , 4 , 6 , 7 , 8 , 10 , 17 ] NEW_LINE cost = [ 3 , 8 , 20 ] NEW_LINE N = len ( arr ) NEW_LINE print ( MinCost ( arr , cost , N ) ) NEW_LINE |
Maximum Pairs of Bracket Sequences which can be concatenated to form a Regular Bracket Sequence | Function to count the number of pairs whose concatenation results in the regular bracket sequence ; Stores the count of opening and closing parenthesis for each string arr [ i ] ; Stores maximum count of pairs ; Traverse the array arr [ ] ; Traverse the string c [ ] ; Opening Bracket ; Otherwise , Closing Bracket ; Count of closing brackets needed to balance string ; Count of opening brackets needed to balance string ; Add the count of balanced sequences ; Traverse the array ; Print the resultant count ; Driver Code | def countPairs ( N , arr ) : NEW_LINE INDENT open = [ 0 ] * 100 NEW_LINE close = [ 0 ] * 100 NEW_LINE ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT c = [ i for i in arr [ i ] ] NEW_LINE d = 0 NEW_LINE minm = 0 NEW_LINE for j in range ( len ( c ) ) : NEW_LINE INDENT if ( c [ j ] == ' ( ' ) : NEW_LINE INDENT d += 1 NEW_LINE DEDENT else : NEW_LINE INDENT d -= 1 NEW_LINE if ( d < minm ) : NEW_LINE INDENT minm = d NEW_LINE DEDENT DEDENT DEDENT if ( d >= 0 ) : NEW_LINE INDENT if ( minm == 0 ) : NEW_LINE INDENT close [ d ] += 1 NEW_LINE DEDENT DEDENT elif ( d < 0 ) : NEW_LINE INDENT if ( minm == d ) : NEW_LINE INDENT open [ - d ] += 1 NEW_LINE DEDENT DEDENT DEDENT ans += close [ 0 ] // 2 NEW_LINE for i in range ( 1 , 100 ) : NEW_LINE INDENT ans += min ( open [ i ] , close [ i ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE list = [ ] NEW_LINE list . append ( " ) ( ) ) " ) NEW_LINE list . append ( " ) " ) NEW_LINE list . append ( " ( ( " ) NEW_LINE list . append ( " ( ( " ) NEW_LINE list . append ( " ( " ) NEW_LINE list . append ( " ) " ) NEW_LINE list . append ( " ) " ) NEW_LINE countPairs ( N , list ) NEW_LINE DEDENT |
Minimum count of elements to be inserted in Array to form all values in [ 1 , K ] using subset sum | Function to find the count of minimum elements to be inserted to form every number in a range ; Stores the count of numbers needed ; Stores the numbers upto which every numbers can be formed ; Stores the index of the array arr [ ] ; Iterate until requiredSum is less than or equal to K ; If i is less than N and requiredSum is greater than or equal to arr [ i ] ; Increment requiredSum by arr [ i ] ; Increment i by 1 ; Otherwise ; Increment count by 1 ; Increment requiredSum by requiredSum ; Return result ; Driver Code ; Input ; Function Call | def minElements ( arr , N , K ) : NEW_LINE INDENT count = 0 NEW_LINE requiredNum = 1 NEW_LINE i = 0 NEW_LINE while ( requiredNum <= K ) : NEW_LINE INDENT if ( i < N and requiredNum >= arr [ i ] ) : NEW_LINE INDENT requiredNum += arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE requiredNum += requiredNum NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 ] NEW_LINE K = 6 NEW_LINE N = len ( arr ) NEW_LINE print ( minElements ( arr , N , K ) ) NEW_LINE DEDENT |
Theft at World Bank | Python3 program for the above approach ; Custom comparator ; Function to find the maximum profit ; Stores the pairs of elements of B and A at the same index ; Iterate over the range [ 0 , N ] ; If current integer is perfect square ; Push the pair of B [ i ] and A [ i ] in vector V ; Sort the vector using the custom comparator ; Stores the maximum profit ; Traverse the vector V ; If V [ i ] [ 1 ] is less than W ; Increment profit by V [ i ] [ 0 ] ; Decrement V [ i ] [ 0 ] from W ; Otherwise ; Update profit ; Return the value of profit ; Driver Code | import math NEW_LINE from functools import cmp_to_key NEW_LINE def comparator ( p1 , p2 ) : NEW_LINE INDENT a = p1 [ 0 ] NEW_LINE b = p1 [ 1 ] NEW_LINE c = p2 [ 0 ] NEW_LINE d = p2 [ 1 ] NEW_LINE val1 = a / b NEW_LINE val2 = c / d NEW_LINE return val1 > val2 NEW_LINE DEDENT def maximumProfit ( A , B , N , W ) : NEW_LINE INDENT V = [ ] NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT temp = int ( math . sqrt ( A [ i ] ) ) NEW_LINE if temp * temp == A [ i ] : NEW_LINE INDENT continue NEW_LINE DEDENT V . append ( [ B [ i ] , A [ i ] ] ) NEW_LINE DEDENT V = sorted ( V , key = cmp_to_key ( comparator ) ) NEW_LINE profit = 0.00 NEW_LINE k = len ( V ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT if V [ i ] [ 1 ] <= W : NEW_LINE INDENT profit += V [ i ] [ 0 ] NEW_LINE W -= V [ i ] [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT profit += ( V [ i ] [ 0 ] * W ) / V [ i ] [ 1 ] NEW_LINE break NEW_LINE DEDENT DEDENT return profit NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE W = 10 NEW_LINE A = [ 4 , 5 , 7 ] NEW_LINE B = [ 8 , 5 , 4 ] NEW_LINE print ( round ( maximumProfit ( A , B , N , W ) , 5 ) ) NEW_LINE DEDENT |
Maximize the count of adjacent element pairs with even sum by rearranging the Array | Function to find maximum count pair of adjacent elements with even sum ; Stores count of odd numbers ; Stores count of even numbers ; Traverse the array arr [ ] ; If arr [ i ] % 2 is 1 ; Else ; If odd and even both are greater than 0 ; Otherwise ; Driver Code | def maximumCount ( arr , N ) : NEW_LINE INDENT odd = 0 NEW_LINE even = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even += 1 NEW_LINE DEDENT DEDENT if ( odd and even ) : NEW_LINE INDENT return N - 2 NEW_LINE DEDENT else : NEW_LINE INDENT return N - 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 13 , 15 , 3 , 16 , 9 , 13 , 18 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maximumCount ( arr , N ) ) NEW_LINE DEDENT |
Smallest number possible by repeatedly multiplying with K or 2 exactly N times starting from 1 | Function to find the minimum value of X after increment X by K or twice value of X in each of N operations ; Iterate over the range [ 1 , N ] ; If the value of X is less than equal to K ; Otherwise ; Return the minimum value of X ; Driver Code | def minPossibleValue ( N , K , X ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( X <= K ) : NEW_LINE INDENT X = X * 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT X = X + K ; NEW_LINE DEDENT DEDENT return X ; NEW_LINE DEDENT N = 7 ; NEW_LINE K = 4 ; NEW_LINE X = 1 ; NEW_LINE print ( minPossibleValue ( N , K , X ) ) ; NEW_LINE |
Smallest number that can replace all | Python 3 program for the above approach ; Function to find the value of K to minimize the value of maximum absolute difference between adjacent elements ; Stores the maximum and minimum among array elements that are adjacent to " - 1" ; Traverse the given array arr [ ] ; If arr [ i ] is - 1 & arr [ i + 1 ] is not - 1 ; If arr [ i + 1 ] is - 1 & arr [ i ] is not - 1 ; If all array element is - 1 ; Otherwise ; Driver Code | import sys NEW_LINE def findMissingValue ( arr , N ) : NEW_LINE INDENT minE = sys . maxsize NEW_LINE maxE = - sys . maxsize - 1 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( arr [ i ] == - 1 and arr [ i + 1 ] != - 1 ) : NEW_LINE INDENT minE = min ( minE , arr [ i + 1 ] ) NEW_LINE maxE = max ( maxE , arr [ i + 1 ] ) NEW_LINE DEDENT if ( arr [ i ] != - 1 and arr [ i + 1 ] == - 1 ) : NEW_LINE INDENT minE = min ( minE , arr [ i ] ) NEW_LINE maxE = max ( maxE , arr [ i ] ) NEW_LINE DEDENT DEDENT if ( minE == sys . maxsize and maxE == - sys . maxsize - 1 ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ( minE + maxE ) // 2 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , - 1 , - 1 , - 1 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE findMissingValue ( arr , N ) NEW_LINE DEDENT |
Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times | Function to find the last element after performing given operations ; Length of the array ; Increment j until condition is satisfied ; In each pair every value is repeating r number of times ; Print the result according to the value of k ; Driver Code ; Given K ; Given arr [ ] ; Function call | def findLastElement ( N , A ) : NEW_LINE INDENT l = len ( A ) NEW_LINE j = 0 NEW_LINE while ( N > l * ( 2 ** j ) ) : NEW_LINE INDENT N = N - l * 2 ** j NEW_LINE j += 1 NEW_LINE DEDENT k = 1 NEW_LINE r = 2 ** j NEW_LINE for i in range ( 1 , l ) : NEW_LINE INDENT if N > r * i : NEW_LINE INDENT k += 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , len ( A ) ) : NEW_LINE INDENT if ( i + 1 == k ) : NEW_LINE INDENT print ( A [ i ] ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 7 NEW_LINE A = [ 1 , 2 , 3 ] NEW_LINE findLastElement ( K , A ) NEW_LINE DEDENT |
Minimum possible value of D which when added to or subtracted from K repeatedly obtains every array element | Recursive function tox previous gcd of a and b ; Function to find the maximum value of D such that every element in the array can be obtained by performing K + D or K - D ; Traverse the array arr [ ] ; Update arr [ i ] ; Stores GCD of the array ; Iterate over the range [ 1 , N ] ; Update the value of D ; Print the value of D ; Driver Code | def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def findMaxD ( arr , N , K ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT arr [ i ] = abs ( arr [ i ] - K ) NEW_LINE DEDENT D = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT D = gcd ( D , arr [ i ] ) NEW_LINE DEDENT return D NEW_LINE DEDENT arr = [ 1 , 7 , 11 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( findMaxD ( arr , N , K ) ) NEW_LINE |
Maximize the number of times a character can be removed from substring 01 from given Binary String | Function to find the maximum moves that can be performed on a string ; Stores 0 s in suffix ; Stores 1 s in prefix ; Iterate over the characters of the string ; Iterate until i is greater than or equal to 0 ; If N is equal to x + y ; Return answer ; Driver code ; Input ; Function call | def maxOperations ( S , N ) : NEW_LINE INDENT X = 0 NEW_LINE Y = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT break NEW_LINE DEDENT Y += 1 NEW_LINE DEDENT i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT break NEW_LINE DEDENT X += 1 NEW_LINE DEDENT if ( N == X + Y ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return N - ( X + Y ) - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "001111" NEW_LINE N = len ( S ) NEW_LINE print ( maxOperations ( S , N ) ) NEW_LINE DEDENT |
Maximize frequency sum of K chosen characters from given string | Function to find the maximum sum of frequencies of the exactly K chosen characters from the string S ; Stores the resultant maximum sum ; Stores the frequency of array elements ; Find the frequency of character ; Sort the frequency array in the descending order ; Iterate to choose K elements greedily ; If the freq [ i ] cards are chosen ; K cards have been picked ; Return the resultant sum ; Driver Code | def maximumSum ( S , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE freq = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ ord ( S [ i ] ) ] += 1 NEW_LINE DEDENT freq = sorted ( freq ) [ : : - 1 ] NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT if ( K > freq [ i ] ) : NEW_LINE INDENT sum += freq [ i ] * freq [ i ] NEW_LINE K -= freq [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT sum += freq [ i ] * K NEW_LINE break NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " GEEKSFORGEEKS " NEW_LINE K = 10 NEW_LINE N = len ( S ) NEW_LINE print ( maximumSum ( S , N , K ) ) NEW_LINE DEDENT |
Count of N | Python3 program for the above approach ; Function to count N - digit numbers having absolute difference between adjacent digits in non - increasing order ; If digit = n + 1 , a valid n - digit number has been formed ; If the state has already been computed ; If the current digit is 1 , then any digit from [ 1 - 9 ] can be placed ; If the current digit is 2 , any digit from [ 0 - 9 ] can be placed ; For other digits , any digit i can be placed which satisfies abs ( prev1 - i ) <= abs ( prev1 - prev2 ) ; If absolute difference is less than or equal to diff ; Function to count N - digit numbers with absolute difference between adjacent digits in non increasing order ; Initialize dp table with - 1 ; Function Call ; Driver code | dp = [ [ [ 0 for i in range ( 10 ) ] for col in range ( 10 ) ] for row in range ( 100 ) ] NEW_LINE def countOfNumbers ( digit , prev1 , prev2 , n ) : NEW_LINE INDENT if ( digit == n + 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT val = dp [ digit ] [ prev1 ] [ prev2 ] NEW_LINE if ( val != - 1 ) : NEW_LINE INDENT return val NEW_LINE DEDENT val = 0 NEW_LINE if ( digit == 1 ) : NEW_LINE INDENT i = 1 NEW_LINE if n == 1 : NEW_LINE INDENT i = 0 NEW_LINE DEDENT for j in range ( i , 10 ) : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , j , prev1 , n ) NEW_LINE DEDENT DEDENT elif ( digit == 2 ) : NEW_LINE INDENT for i in range ( 0 , 10 ) : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , i , prev1 , n ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT diff = abs ( prev2 - prev1 ) NEW_LINE for i in range ( 0 , 10 ) : NEW_LINE INDENT if ( abs ( prev1 - i ) <= diff ) : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , i , prev1 , n ) NEW_LINE DEDENT DEDENT DEDENT return val NEW_LINE DEDENT def countNumbersUtil ( N ) : NEW_LINE INDENT for i in range ( 0 , 100 ) : NEW_LINE INDENT for j in range ( 0 , 10 ) : NEW_LINE INDENT for k in range ( 0 , 10 ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = - 1 NEW_LINE DEDENT DEDENT DEDENT print ( countOfNumbers ( 1 , 0 , 0 , N ) ) NEW_LINE DEDENT N = 3 NEW_LINE countNumbersUtil ( N ) NEW_LINE |
Print all numbers that can be obtained by adding A or B to N exactly M times | Function to find all possible numbers that can be obtained by adding A or B to N exactly N times ; If number of steps is 0 and only possible number is N ; Add A to N and make a recursive call for M - 1 steps ; Add B to N and make a recursive call for M - 1 steps . ; Driver Code ; Given Inputs ; Stores all possible numbers ; Function call ; Print all possible numbers | def possibleNumbers ( numbers , N , M , A , B ) : NEW_LINE INDENT if ( M == 0 ) : NEW_LINE INDENT numbers . add ( N ) NEW_LINE return NEW_LINE DEDENT possibleNumbers ( numbers , N + A , M - 1 , A , B ) NEW_LINE possibleNumbers ( numbers , N + B , M - 1 , A , B ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE M = 3 NEW_LINE A = 4 NEW_LINE B = 6 NEW_LINE numbers = set ( ) NEW_LINE possibleNumbers ( numbers , N , M , A , B ) NEW_LINE for x in numbers : NEW_LINE INDENT print ( x , end = " β " ) NEW_LINE DEDENT DEDENT |
Maximum sum of array after removing a positive or negative subarray | python 3 program for the above approach ; Function to find the maximum sum of array after removing either the contiguous positive or negative elements ; Store the total sum of array ; Store the maximum contiguous negative sum ; Store the sum of current contiguous negative elements ; Store the minimum element of array ; Traverse the array , arr [ ] ; Update the overall sum ; Store minimum element of array ; If arr [ i ] is positive ; Update temp_sum to 0 ; Add arr [ i ] to temp_sum ; Update max_neg ; If no negative element in array then remove smallest positive element ; Print the required sum ; Driver Code ; Given Input ; Function Call | import sys NEW_LINE def maxSum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE max_neg = sys . maxsize NEW_LINE tempsum = 0 NEW_LINE small = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE small = min ( small , arr [ i ] ) NEW_LINE if ( arr [ i ] > 0 ) : NEW_LINE INDENT tempsum = 0 NEW_LINE DEDENT else : NEW_LINE INDENT tempsum += arr [ i ] NEW_LINE DEDENT max_neg = min ( max_neg , tempsum ) NEW_LINE DEDENT if ( max_neg == 0 ) : NEW_LINE INDENT max_neg = small NEW_LINE DEDENT print ( sum - max_neg ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 ] NEW_LINE n = len ( arr ) NEW_LINE maxSum ( arr , n ) NEW_LINE DEDENT |
Count characters of a string which when removed individually makes the string equal to another string | Function to count characters from A whose removal makes the strings A and B equal ; Stores the index of the longest prefix ; Stores the index of the longest suffix ; Traverse the B ; Traverse the B ; If N - M is equal to 1 and Y is less than or equal to X ; Print count of characters ; Print positions of the characters ; Otherwise ; Driver Code | def RemoveOneChar ( A , B , N , M ) : NEW_LINE INDENT X = 0 NEW_LINE Y = N - 1 NEW_LINE for i in range ( M ) : NEW_LINE INDENT if ( A [ X ] != B [ i ] ) : NEW_LINE INDENT break NEW_LINE DEDENT X += 1 NEW_LINE DEDENT for i in range ( M - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ Y ] != B [ i ] ) : NEW_LINE INDENT break NEW_LINE DEDENT Y -= 1 NEW_LINE DEDENT if ( N - M == 1 and Y < X ) : NEW_LINE INDENT print ( X - Y + 1 ) NEW_LINE for i in range ( Y , X + 1 ) : NEW_LINE INDENT print ( i + 1 , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = " abaac " NEW_LINE B = " abac " NEW_LINE N = len ( A ) NEW_LINE M = len ( B ) NEW_LINE RemoveOneChar ( A , B , N , M ) NEW_LINE DEDENT |
Minimum flips or swapping of adjacent characters required to make a string equal to another | Function to find minimum operations required to convert A to B ; Store the size of the string ; Store the required result ; Traverse the string , a ; If a [ i ] is equal to b [ i ] ; Check if swapping adjacent characters make the same - indexed characters equal or not ; Otherwise , flip the current bit ; Print the minimum number of operations ; Driver Code ; Given Input ; Function Call | def minimumOperation ( a , b ) : NEW_LINE INDENT n = len ( a ) NEW_LINE i = 0 NEW_LINE minoperation = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( a [ i ] == b [ i ] ) : NEW_LINE INDENT i = i + 1 NEW_LINE continue NEW_LINE DEDENT elif ( a [ i ] == b [ i + 1 ] and a [ i + 1 ] == b [ i ] and i < n - 1 ) : NEW_LINE INDENT minoperation += 1 NEW_LINE i = i + 2 NEW_LINE DEDENT elif ( a [ i ] != b [ i ] ) : NEW_LINE INDENT minoperation += 1 NEW_LINE i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT print ( minoperation ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = "10010010" NEW_LINE b = "00001000" NEW_LINE minimumOperation ( a , b ) NEW_LINE DEDENT |
Minimum replacements required to make sum of all K | Function to find minimum number of operations required to make sum of all subarrays of size K equal ; Stores number of operations ; Iterate in the range [ 0 , K - 1 ] ; Stores frequency of elements separated by distance K ; Stores maximum frequency and corresponding element ; Find max frequency element and its frequency ; Update the number of operations ; Print the result ; Driver Code ; Given Input ; Function Call | def findMinOperations ( arr , N , K ) : NEW_LINE INDENT operations = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT freq = { } NEW_LINE for j in range ( i , N , K ) : NEW_LINE INDENT if arr [ j ] in freq : NEW_LINE INDENT freq [ arr [ j ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ arr [ j ] ] = 1 NEW_LINE DEDENT DEDENT max1 = 0 NEW_LINE num = 0 NEW_LINE for key , value in freq . items ( ) : NEW_LINE INDENT if ( value > max1 ) : NEW_LINE INDENT max1 = value NEW_LINE num = key NEW_LINE DEDENT DEDENT for key , value in freq . items ( ) : NEW_LINE INDENT if ( key != num ) : NEW_LINE INDENT operations += value NEW_LINE DEDENT DEDENT DEDENT print ( operations ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 3 , 5 , 6 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE findMinOperations ( arr , N , K ) NEW_LINE DEDENT |
Count of pairs of integers up to X and Y that generates equal Quotient and Remainder | python 3 Program for the above approach ; Function to calculate the number of pairs satisfying ( m / n = m % n ) ; Iterate from 1 to sqrt ( x ) ; Combining the conditions - 1 ) n > k 2 ) n <= y 3 ) n <= ( x / k - 1 ) ; Driver code | from math import sqrt NEW_LINE def countOfPairs ( x , y ) : NEW_LINE INDENT count = 0 NEW_LINE for k in range ( 1 , int ( sqrt ( x ) ) + 1 , 1 ) : NEW_LINE INDENT count += max ( 0 , min ( y , x / k - 1 ) - k ) NEW_LINE DEDENT print ( int ( count ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 4 NEW_LINE y = 5 NEW_LINE countOfPairs ( x , y ) NEW_LINE DEDENT |
Count permutations of first N natural numbers having sum of adjacent elements equal to a perfect square | python program for the above approach ; Function to count total number of permutation of the first N natural number having the sum of adjacent elements as perfect square ; Create an adjacency matrix ; bCount elements whose indegree bis 1 ; bGenerate adjacency matrix ; Find the sum of i and j ; If sum is perfect square . then move from i to j ; Add it in adjacency list of i ; If any list is of size 1 , then the indegree is 1 ; If there is no element whose indegree is 1 , then N such permutations are possible ; If there is 1 or 2 elements whose indegree is 1 , then 2 permutations are possible ; If there are more than 2 elements whose indegree is 1 , then return 0 ; Driver Code | from math import sqrt , floor , ceil NEW_LINE def countPermutations ( N ) : NEW_LINE INDENT adj = [ [ ] for i in range ( 105 ) ] NEW_LINE indeg = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT sum = i + j NEW_LINE if ( ceil ( sqrt ( sum ) ) == floor ( sqrt ( sum ) ) ) : NEW_LINE INDENT adj [ i ] . append ( j ) NEW_LINE DEDENT DEDENT if ( len ( adj [ i ] ) == 1 ) : NEW_LINE INDENT indeg += 1 NEW_LINE DEDENT DEDENT if ( indeg == 0 ) : NEW_LINE INDENT return N NEW_LINE DEDENT elif ( indeg <= 2 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 17 NEW_LINE print ( countPermutations ( N ) ) NEW_LINE DEDENT |
Generate a permutation of first N natural numbers having count of unique adjacent differences equal to K | Function to construct the lst with exactly K unique adjacent element differences ; Stores the resultant array ; Stores the left and the right most element of the range ; Traverse the array ; If k is even , the add left to array and increment the left ; If k is odd , the add right to array and decrement the right ; Repeat the steps for k - 1 times ; Print the resultant lst ; Driver Code | def makelst ( N , K ) : NEW_LINE INDENT lst = [ 0 for i in range ( N ) ] NEW_LINE left = 1 NEW_LINE right = N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( K % 2 == 0 ) : NEW_LINE INDENT lst [ i ] = left NEW_LINE left = left + 1 NEW_LINE DEDENT else : NEW_LINE INDENT lst [ i ] = right NEW_LINE right = right - 1 NEW_LINE DEDENT if ( K > 1 ) : NEW_LINE INDENT K -= 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( lst [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE K = 3 NEW_LINE makelst ( N , K ) NEW_LINE DEDENT |
Find the date after next half year from a given date | Function to find the date after the next half - year ; Stores the number of days in the months of a leap year ; List of months ; Days in half of a year ; Index of current month ; Starting day ; Decrement the value of cnt by 1 ; Increment cur_date ; If cnt is equal to 0 , then break out of the loop ; Update cur_month ; Update cur_date ; Print the resultant date ; Driver Code ; Function Call | def getDate ( d , m ) : NEW_LINE INDENT days = [ 31 , 29 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ] NEW_LINE month = [ ' January ' , ' February ' , ' March ' , ' April ' , ' May ' , ' June ' , ' July ' , ' August ' , ' September ' , ' October ' , ' November ' , ' December ' ] NEW_LINE cnt = 183 NEW_LINE cur_month = month . index ( m ) NEW_LINE cur_date = d NEW_LINE while ( 1 ) : NEW_LINE INDENT while ( cnt > 0 and cur_date <= days [ cur_month ] ) : NEW_LINE INDENT cnt -= 1 NEW_LINE cur_date += 1 NEW_LINE DEDENT if ( cnt == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT cur_month = ( cur_month + 1 ) % 12 NEW_LINE cur_date = 1 NEW_LINE DEDENT print ( cur_date , month [ cur_month ] ) NEW_LINE DEDENT D = 15 NEW_LINE M = " January " NEW_LINE getDate ( D , M ) NEW_LINE |
Maximum number made up of distinct digits whose sum is equal to N | Function to find the largest positive number made up of distinct digits having the sum of its digits as N ; If given number is greater than 45 , print - 1 ; Store the required number and the digit to be considered ; Loop until N > 0 and digit > 0 ; If the current digit is at most N then , add it to number num ; Update the value of num ; Decrement N by digit ; Consider the next lower digit ; Add 0 at the end and return the number num ; Driver Code | def largestNumber ( N ) : NEW_LINE INDENT if ( N > 45 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT num = 0 NEW_LINE digit = 9 NEW_LINE while ( N > 0 and digit > 0 ) : NEW_LINE INDENT if ( digit <= N ) : NEW_LINE INDENT num *= 10 NEW_LINE num += digit NEW_LINE N -= digit NEW_LINE DEDENT digit -= 1 NEW_LINE DEDENT return num * 10 NEW_LINE DEDENT N = 25 NEW_LINE print ( largestNumber ( N ) ) NEW_LINE |
Minimum number that can be obtained by applying ' + ' and ' * ' operations on array elements | Function to find the smallest number that can be obtained after applying the arithmetic operations mentioned in the string S ; Stores the count of multiplication operator in the string ; Store the required result ; Iterate in the range to create the mask ; Checking the number of bits that are set in the mask ; Check if the number of bits that are set in the mask is multiplication operation ; Storing the elements that is to be added ; Apply the multiplications operation first ; If sign is ' * ' , then multiply last element of deque with arr [ i ] ; append last multiplied element in the deque ; If the element is to be added , then add it to the deque ; Add all the element of the deque ; Minimize the answer with the given sum ; Driver Code | def minimumSum ( A , N , S ) : NEW_LINE INDENT mul = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( S [ i ] == " * " ) : NEW_LINE INDENT mul += 1 NEW_LINE DEDENT DEDENT ans = 1000000 NEW_LINE for i in range ( 1 << ( N - 1 ) ) : NEW_LINE INDENT cnt = 0 NEW_LINE v = [ ] NEW_LINE for j in range ( N - 1 ) : NEW_LINE INDENT if ( ( 1 << j ) & i ) : NEW_LINE INDENT cnt += 1 NEW_LINE v . append ( " * " ) NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( " + " ) NEW_LINE DEDENT DEDENT if ( cnt == mul ) : NEW_LINE INDENT d = [ ] NEW_LINE d . append ( A [ 0 ] ) NEW_LINE for j in range ( N - 1 ) : NEW_LINE INDENT if ( v [ j ] == " * " ) : NEW_LINE INDENT x = d [ len ( d ) - 1 ] NEW_LINE d . pop ( ) NEW_LINE x = x * A [ j + 1 ] NEW_LINE d . append ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT d . append ( A [ j + 1 ] ) NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE while ( len ( d ) > 0 ) : NEW_LINE INDENT x = d [ 0 ] NEW_LINE sum += x NEW_LINE d . pop ( 0 ) NEW_LINE DEDENT ans = min ( ans , sum ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A = [ 2 , 2 , 2 , 2 ] NEW_LINE S = " * * + " NEW_LINE N = len ( A ) NEW_LINE print ( minimumSum ( A , N , S ) ) NEW_LINE |
Minimum sum of medians of all possible K length subsequences of a sorted array | Function to find the minimum sum of all the medians of the K sized sorted arrays formed from the given array ; Stores the distance between the medians ; Stores the number of subsequences required ; Stores the resultant sum ; Iterate from start and add all the medians ; Add the value of arr [ i ] to the variable minsum ; Increment i by select the median to get the next median index ; Decrement the value of totalArrays by 1 ; Print the resultant minimum sum ; Driver Code | def sumOfMedians ( arr , N , K ) : NEW_LINE INDENT selectMedian = ( K + 1 ) // 2 NEW_LINE totalArrays = N // K NEW_LINE minSum = 0 NEW_LINE i = selectMedian - 1 NEW_LINE while ( i < N and totalArrays != 0 ) : NEW_LINE INDENT minSum = minSum + arr [ i ] NEW_LINE i = i + selectMedian NEW_LINE totalArrays -= 1 NEW_LINE DEDENT print ( minSum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE sumOfMedians ( arr , N , K ) NEW_LINE DEDENT |
Find K positive integers not exceeding N and having sum S | Function to represent S as the sum of K positive integers less than or equal to N ; If S can cannot be represented as sum of K integers ; If sum of first i natural numbers exceeds S ; Insert i into nums [ ] ; Insert first K - 1 positive numbers into answer [ ] ; Insert the K - th number ; Traverse the array answer [ ] ; If current element exceeds N ; Add the extra value to the previous element ; Reduce current element to N ; Printing the K numbers ; Driver Code | def solve ( S , K , N ) : NEW_LINE INDENT if ( K > N ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT max_sum , min_sum = 0 , 0 NEW_LINE for i in range ( K + 1 ) : NEW_LINE INDENT min_sum += i NEW_LINE max_sum += N - i + 1 NEW_LINE DEDENT if ( S < min_sum or S > max_sum ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT s1 = 0 NEW_LINE nums = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( s1 > S ) : NEW_LINE INDENT break NEW_LINE DEDENT s1 += i NEW_LINE nums . append ( i ) NEW_LINE DEDENT answer = [ ] NEW_LINE s2 = 0 NEW_LINE for i in range ( K - 1 ) : NEW_LINE INDENT answer . append ( nums [ i ] ) NEW_LINE s2 += nums [ i ] NEW_LINE DEDENT answer . append ( S - s2 ) NEW_LINE Max = N NEW_LINE for i in range ( len ( answer ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( answer [ i ] > Max ) : NEW_LINE INDENT extra = answer [ i ] - Max NEW_LINE if ( i - 1 >= 0 ) : NEW_LINE INDENT answer [ i - 1 ] += extra NEW_LINE DEDENT answer [ i ] = Max NEW_LINE Max -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for x in answer : NEW_LINE INDENT print ( x , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S , K , N = 15 , 4 , 8 NEW_LINE solve ( S , K , N ) NEW_LINE DEDENT |
Generate an N | Python3 program for the above approach ; Function to minimize the maximum element present in an N - length array having sum of elements divisible by K ; Return the ceil value of ( K / N ) ; Driver Code | import math NEW_LINE def minimumValue ( N , K ) : NEW_LINE INDENT return math . ceil ( K / N ) NEW_LINE DEDENT N = 4 NEW_LINE K = 50 NEW_LINE print ( minimumValue ( N , K ) ) NEW_LINE |
Minimum removal of elements from end of an array required to obtain sum K | Function to find the minimum number of elements required to be removed from the ends of an array to obtain a sum K ; Number of elements removed from the left and right ends of the array ; Sum of left and right subarrays ; No element is taken from left initially ; Start taking elements from right side ; ( left + 1 ) : Count of elements removed from the left ( N - right ) : Count of elements removed from the right ; If sum is greater than K ; If it is not possible to obtain sum K ; Driver Code ; Given Array ; Given target sum | def minSizeArr ( A , N , K ) : NEW_LINE INDENT leftTaken = N NEW_LINE rightTaken = N NEW_LINE leftSum = 0 NEW_LINE rightSum = 0 NEW_LINE for left in range ( - 1 , N ) : NEW_LINE INDENT if ( left != - 1 ) : NEW_LINE INDENT leftSum += A [ left ] NEW_LINE DEDENT rightSum = 0 NEW_LINE for right in range ( N - 1 , left , - 1 ) : NEW_LINE INDENT rightSum += A [ right ] NEW_LINE if ( leftSum + rightSum == K ) : NEW_LINE INDENT if ( leftTaken + rightTaken > ( left + 1 ) + ( N - right ) ) : NEW_LINE INDENT leftTaken = left + 1 NEW_LINE rightTaken = N - right NEW_LINE DEDENT break NEW_LINE DEDENT if ( leftSum + rightSum > K ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if ( leftTaken + rightTaken <= N ) : NEW_LINE INDENT for i in range ( leftTaken ) : NEW_LINE INDENT print ( A [ i ] , end = " β " ) NEW_LINE DEDENT for i in range ( rightTaken ) : NEW_LINE INDENT print ( A [ N - i - 1 ] , end = " β " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 NEW_LINE A = [ 3 , 2 , 1 , 1 , 1 , 1 , 3 ] NEW_LINE K = 10 NEW_LINE minSizeArr ( A , N , K ) NEW_LINE DEDENT |
Minimum removal of elements from end of an array required to obtain sum K | Function to find the smallest array that can be removed from the ends of an array to obtain sum K ; Sum of complete array ; If given number is greater than sum of the array ; If number is equal to the sum of array ; tar is sum of middle subarray ; Find the longest subarray with sum equal to tar ; If there is no subarray with sum equal to tar ; Driver Code ; Given Array ; Given target sum | def minSizeArr ( A , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE DEDENT if ( K > sum ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE return NEW_LINE DEDENT if ( K == sum ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( A [ i ] , end = " β " ) NEW_LINE DEDENT return NEW_LINE DEDENT tar = sum - K NEW_LINE um = { } NEW_LINE um [ 0 ] = - 1 NEW_LINE left = 0 NEW_LINE right = 0 NEW_LINE cur = 0 NEW_LINE maxi = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cur += A [ i ] NEW_LINE if ( ( cur - tar ) in um and ( i - um [ cur - tar ] ) > maxi ) : NEW_LINE INDENT maxi = i - um [ cur - tar ] NEW_LINE right = i NEW_LINE left = um [ cur - tar ] NEW_LINE DEDENT if ( cur not in um ) : NEW_LINE INDENT um [ cur ] = i NEW_LINE DEDENT DEDENT if ( maxi == - 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( left + 1 ) : NEW_LINE INDENT print ( A [ i ] , end = " β " ) NEW_LINE DEDENT for i in range ( right ) : NEW_LINE INDENT print ( A [ N - i - 1 ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE A = [ 3 , 2 , 1 , 1 , 1 , 1 , 3 ] NEW_LINE K = 10 NEW_LINE minSizeArr ( A , N , K ) NEW_LINE DEDENT |
Minimum product modulo N possible for any pair from a given range | Function to return the minimum possible value of ( i * j ) % N ; Stores the minimum remainder ; Iterate from L to R ; Iterate from L to R ; Print the minimum value of remainder ; If R - L >= N ; Driver Code | def minModulo ( L , R , N ) : NEW_LINE INDENT if ( R - L < N ) : NEW_LINE INDENT ans = 10 ** 9 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT for j in range ( L , R + 1 ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT ans = min ( ans , ( i * j ) % N ) NEW_LINE DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R , N = 6 , 10 , 2019 NEW_LINE minModulo ( L , R , N ) NEW_LINE DEDENT |
Count numbers having GCD with N equal to the number itself | Function to count numbers whose GCD with N is the number itself ; Stores the count of factors of N ; Iterate over the range [ 1 , sqrt ( N ) ] ; If i is divisible by i ; Increment count ; Avoid counting the same factor twice ; Return the resultant count ; Driver Code | def countNumbers ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT if ( N % i == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE if ( N // i != i ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE print ( countNumbers ( N ) ) NEW_LINE DEDENT |
Maximum length of all possible K equal length ropes generated by cutting N ropes | Function to find the maximum size of ropes having frequency at least K by cutting the given ropes ; Stores the left and the right boundaries ; Stores the maximum length of rope possible ; Iterate while low is less than or equal to high ; Stores the mid value of the range [ low , high ] ; Stores the count of ropes of length mid ; Traverse the array arr [ ] ; If count is at least K ; Assign mid to ans ; Update the value of low ; Otherwise , update the value of high ; Return the value of ans ; Driver Code | def maximumSize ( a , k ) : NEW_LINE INDENT low = 1 NEW_LINE high = max ( a ) NEW_LINE ans = - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE count = 0 NEW_LINE for c in range ( len ( a ) ) : NEW_LINE INDENT count += a // mid NEW_LINE DEDENT if ( count >= k ) : NEW_LINE INDENT ans = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 9 ] NEW_LINE K = 6 NEW_LINE print ( maximumSize ( arr , K ) ) NEW_LINE DEDENT |
Quadratic equation whose roots are K times the roots of given equation | Function to find the quadratic equation whose roots are K times the roots of the given equation ; Prquadratic equation ; Driver Code | def findEquation ( A , B , C , K ) : NEW_LINE INDENT print ( A , K * B , K * K * C ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A , B , C , K = 1 , 2 , 1 , 2 NEW_LINE findEquation ( A , B , C , K ) NEW_LINE DEDENT |
Maximum the value of a given expression for any pair of coordinates on a 2D plane | Function to find the maximum value of the given expression possible for any pair of co - ordinates ; Stores the differences between pairs ; Stores the maximum value ; Traverse the array arr [ ] [ ] ; While pq is not empty and difference between point [ 0 ] and pq . top ( ) [ 1 ] > K ; Removes the top element ; If pq is not empty ; Update the value res ; Push pair { point [ 1 ] - point [ 0 ] , point [ 0 ] } in pq ; Prthe result ; Driver Code | def findMaxValueOfEquation ( arr , K ) : NEW_LINE INDENT pq = [ ] NEW_LINE res = - 10 ** 8 NEW_LINE for point in arr : NEW_LINE INDENT while ( len ( pq ) > 0 and point [ 0 ] - pq [ - 1 ] [ 1 ] > K ) : NEW_LINE INDENT del pq [ - 1 ] NEW_LINE DEDENT if ( len ( pq ) > 0 ) : NEW_LINE INDENT res = max ( res , pq [ - 1 ] [ 0 ] + point [ 0 ] + point [ 1 ] ) NEW_LINE DEDENT pq . append ( [ point [ 1 ] - point [ 0 ] , point [ 0 ] ] ) NEW_LINE pq = sorted ( pq ) NEW_LINE DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 3 ] , [ 2 , 0 ] , [ 5 , 10 ] , [ 6 , - 10 ] ] NEW_LINE K = 1 NEW_LINE findMaxValueOfEquation ( arr , K ) NEW_LINE DEDENT |
Minimum increments required to make absolute difference of all pairwise adjacent array elements even | Function to find the minimum number of increments of array elements required to make difference between all pairwise adjacent elements even ; Stores the count of odd and even elements ; Traverse the array ; Increment odd count ; Increment even count ; Return the minimum number of operations required ; Driver Code | def minOperations ( arr , n ) : NEW_LINE INDENT oddcount , evencount = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT oddcount += 1 NEW_LINE DEDENT else : NEW_LINE INDENT evencount += 1 NEW_LINE DEDENT DEDENT return min ( oddcount , evencount ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 3 , 1 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minOperations ( arr , N ) ) NEW_LINE DEDENT |
Count numbers up to C that can be reduced to 0 by adding or subtracting A or B | Function to calculate GCD of the two numbers a and b ; Base Case ; Recursively find the GCD ; Function to count the numbers up to C that can be reduced to 0 by adding or subtracting A or B ; Stores GCD of A and B ; Stores the count of multiples of g in the range ( 0 , C ] ; Print the result ; Driver code | def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def countDistinctNumbers ( A , B , C ) : NEW_LINE INDENT g = gcd ( A , B ) NEW_LINE count = C // g NEW_LINE print ( count ) NEW_LINE DEDENT A = 2 NEW_LINE B = 3 NEW_LINE C = 5 NEW_LINE countDistinctNumbers ( A , B , C ) NEW_LINE |
Find the last element after repeatedly removing every second element from either end alternately | Function to find the last element remaining in the array after performing the given operations ; Checks if traversal is from left to right or vice versa ; Store the elements currently present in the array ; Store the distance between 2 consecutive array elements ; Store the first element of the remaining array ; Iterate while elements are greater than 1 ; If left to right turn ; Update head ; Otherwise , check if the remaining elements are odd ; If true , update head ; Eleminate half of the array elements ; Double the steps after each turn ; Alter the turn ; Print the remaining element ; Driver Code | def printLastElement ( arr , N ) : NEW_LINE INDENT leftTurn = True NEW_LINE remainElements = N NEW_LINE step = 1 NEW_LINE head = 1 NEW_LINE while ( remainElements > 1 ) : NEW_LINE INDENT if ( leftTurn ) : NEW_LINE INDENT head = head + step NEW_LINE DEDENT else : NEW_LINE INDENT if ( remainElements % 2 == 1 ) : NEW_LINE INDENT head = head + step NEW_LINE DEDENT DEDENT remainElements = remainElements // 2 NEW_LINE step = step * 2 NEW_LINE leftTurn = not leftTurn NEW_LINE DEDENT print ( arr [ head - 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE printLastElement ( arr , N ) NEW_LINE DEDENT |
Distributed C candies among N boys such that difference between maximum and minimum candies received is K | Function to calculate the maximum and minimum number of candies a boy can possess ; All candies will be given to one boy ; All the candies will be given to 1 boy ; Give K candies to 1 st boy initially ; Count remaining candies ; If the last candy of remaining candies is given to the last boy , i . e Nth boy ; Increase minimum count ; Driver code | def max_min ( N , C , K ) : NEW_LINE INDENT maximum = 0 NEW_LINE minimum = 0 NEW_LINE if ( N == 1 ) : NEW_LINE INDENT maximum = minimum = C NEW_LINE DEDENT elif ( K >= C ) : NEW_LINE INDENT maximum = C NEW_LINE minimum = 0 NEW_LINE DEDENT else : NEW_LINE INDENT maximum = K NEW_LINE minimum = 0 NEW_LINE remain_candy = C - K NEW_LINE maximum += remain_candy // N NEW_LINE minimum = remain_candy // N NEW_LINE DEDENT if ( remain_candy % N == N - 1 ) : NEW_LINE INDENT minimum += 1 NEW_LINE DEDENT print ( " Maximum β = β { } " . format ( maximum ) ) NEW_LINE print ( " Minimum β = β { } " . format ( minimum ) ) NEW_LINE DEDENT N = 4 NEW_LINE C = 12 NEW_LINE K = 3 NEW_LINE max_min ( N , C , K ) NEW_LINE |
Length of smallest subarray required to be removed to make remaining elements consecutive | Function to find the length of the smallest subarray to be removed to make remaining array elements consecutive ; Store the ending index of the longest prefix consecutive array ; Traverse the array to find the longest prefix consecutive sequence ; A [ 0. . . left_index ] is the prefix consecutive sequence ; Store the starting index of the longest suffix consecutive sequence ; Traverse the array to find the longest suffix consecutive sequence ; A [ right_index ... N - 1 ] is the consecutive sequence ; Store the smallest subarray required to be removed ; Check if subarray from the middle can be removed ; Update the right index s . t . A [ 0 , N - 1 ] is consecutive ; If updated_right < N , then update the minimumLength ; Print the required result ; Driver Code | def shortestSubarray ( A , N ) : NEW_LINE INDENT i = 0 NEW_LINE left_index = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i ] + 1 != A [ i + 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT left_index = i NEW_LINE right_index = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT if ( A [ i ] != A [ i - 1 ] + 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT right_index = i NEW_LINE updated_right = 0 NEW_LINE minLength = min ( N - left_index - 1 , right_index ) NEW_LINE if ( A [ right_index ] <= A [ left_index ] + 1 ) : NEW_LINE INDENT updated_right = ( right_index + A [ left_index ] - A [ right_index ] + 1 ) NEW_LINE if ( updated_right < N ) : NEW_LINE INDENT minLength = min ( minLength , updated_right - left_index - 1 ) NEW_LINE DEDENT DEDENT print ( minLength ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 7 , 4 , 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE shortestSubarray ( arr , N ) NEW_LINE DEDENT |
Check if a string can be split into 3 substrings such that one of them is a substring of the other two | Function to check if string S contains any character with frequency >= 3 or not ; Stores frequency of characters ; Iterate over the string ; Update the frequency of current character ; Iterate over the hash array ; If any character has frequency >= 3 ; Otherwise ; Driver Code | def freqCheck ( S , N ) : NEW_LINE INDENT hash = [ 0 ] * 26 NEW_LINE for i in range ( N ) : NEW_LINE INDENT hash [ ord ( S [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( hash [ i ] > 2 ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT DEDENT return " No " NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geekseekforgeeks " NEW_LINE N = len ( S ) NEW_LINE print ( freqCheck ( S , N ) ) NEW_LINE DEDENT |
Minimize length of a string by removing suffixes and prefixes of same characters | Function to find the minimum length of the string after removing the same characters from the end and front of the two strings after dividing into 2 substrings ; Initialize two pointers ; Traverse the string S ; Current char on left pointer ; Shift i towards right ; Shift j towards left ; Return the minimum possible length of string ; Driver Code | def minLength ( s ) : NEW_LINE INDENT i = 0 ; j = len ( s ) - 1 NEW_LINE while ( i < j and s [ i ] == s [ j ] ) : NEW_LINE INDENT d = s [ i ] NEW_LINE while ( i <= j and s [ i ] == d ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT while ( i <= j and s [ j ] == d ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT return j - i + 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " aacbcca " NEW_LINE print ( minLength ( S ) ) NEW_LINE DEDENT |
Number of Binary Search Trees of height H consisting of H + 1 nodes | Function to calculate x ^ y modulo 1000000007 in O ( log y ) ; Stores the value of x ^ y ; Update x if it exceeds mod ; If x is divisible by mod ; If y is odd , then multiply x with result ; Divide y by 2 ; Update the value of x ; Return the value of x ^ y ; Function to count the number of of BSTs of height H consisting of ( H + 1 ) nodes ; Driver Code | def power ( x , y ) : NEW_LINE INDENT mod = 1000000007 NEW_LINE res = 1 NEW_LINE x = x % mod NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % mod NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % mod NEW_LINE DEDENT return res NEW_LINE DEDENT def CountBST ( H ) : NEW_LINE INDENT return power ( 2 , H ) NEW_LINE DEDENT H = 2 NEW_LINE print ( CountBST ( H ) ) NEW_LINE |
Check if any pair of consecutive 1 s can be separated by at most M 0 s by circular rotation of a Binary String | Function to check if any pair of consecutive 1 s can be separated by at most M 0 s by circular rotation of string S ; Stores the indices of all 1 s ; Store the number of pairs separated by at least M 0 s ; Traverse the string ; Store the current index ; Traverse the array containing indices ; If the number of 0 s > M , then increment cnt by 1 ; Increment cnt ; Check if at least M '0' s lie between the first and last occurrence of '1 ; Increment cnt ; If the value of cnt <= 1 , then rotation of string is possible ; Otherwise ; Driver Code | def rotateString ( n , m , s ) : NEW_LINE INDENT v = [ ] NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( 1 , len ( v ) ) : NEW_LINE INDENT if ( ( v [ i ] - v [ i - 1 ] - 1 ) > m ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT if ( len ( v ) >= 2 and ( n - ( v [ - 1 ] - v [ 0 ] ) - 1 ) > m ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if ( cnt <= 1 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "101001" NEW_LINE M = 1 NEW_LINE N = len ( S ) NEW_LINE rotateString ( N , M , S ) NEW_LINE DEDENT |
Number obtained by reducing sum of digits of 2 N into a single digit | Function to find the number obtained by reducing sum of digits of 2 ^ N into a single digit ; Stores answers for different values of N ; Driver Code | def findNumber ( N ) : NEW_LINE INDENT ans = [ 1 , 2 , 4 , 8 , 7 , 5 ] NEW_LINE return ans [ N % 6 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE print ( findNumber ( N ) ) NEW_LINE DEDENT |
Check if two piles of coins can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other | Function to check if two given piles can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other ; If maximum of A & B exceeds the twice of minimum of A & B ; Not possible to empty the piles ; If sum of both the coins is divisible by 3 , then print Yes ; Otherwise , print " No " ; Driver Code | def canBeEmptied ( A , B ) : NEW_LINE INDENT if ( max ( A , B ) > 2 * min ( A , B ) ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT if ( ( A + B ) % 3 == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 1 NEW_LINE B = 2 NEW_LINE canBeEmptied ( A , B ) NEW_LINE DEDENT |
Maximum index a pointer can reach in N steps by avoiding a given index B | Set 2 | Function to find the maximum index the pointer can reach ; Initialize two pointers ; Stores number of steps ; Stores sum of first N natural numbers ; Increment i with j ; Increment j with 1 ; Increment count ; If i points to B ; Break ; Print the pointer index ; Driver Code ; Given value of N & B ; Function call to find maximum index the pointer can reach | def maximumIndex ( N , B ) : NEW_LINE INDENT i , j = 0 , 1 NEW_LINE cnt = 0 NEW_LINE sum = N * ( N + 1 ) // 2 NEW_LINE flag = False NEW_LINE while ( cnt < N ) : NEW_LINE INDENT i += j NEW_LINE j += 1 NEW_LINE cnt += 1 NEW_LINE if ( i == B ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( not flag ) : NEW_LINE INDENT print ( sum ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( sum - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , B = 4 , 6 NEW_LINE maximumIndex ( N , B ) NEW_LINE DEDENT |
Generate longest possible array with product K such that each array element is divisible by its previous adjacent element | Function to construct longest array with product K such that each element is divisible by its previous element ; Stores the prime factors of K ; Stores the power to which primefactor i is raised ; Sort prime factors in descending order ; Stores the final array ; Multiply the last element by K ; Print the constructed array ; Driver Code | def findLongestArray ( K ) : NEW_LINE INDENT primefactors = [ ] NEW_LINE K_temp = K NEW_LINE i = 2 NEW_LINE while i * i <= K : NEW_LINE INDENT count = 0 NEW_LINE while ( K_temp % i == 0 ) : NEW_LINE INDENT K_temp //= i NEW_LINE count += 1 NEW_LINE DEDENT if ( count > 0 ) : NEW_LINE INDENT primefactors . append ( [ count , i ] ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( K_temp != 1 ) : NEW_LINE INDENT primefactors . append ( [ 1 , K_temp ] ) NEW_LINE DEDENT primefactors . sort ( ) NEW_LINE answer = [ primefactors [ 0 ] [ 0 ] , primefactors [ 0 ] [ 1 ] ] NEW_LINE answer [ - 1 ] *= K NEW_LINE for i in range ( primefactors [ 0 ] [ 0 ] ) : NEW_LINE INDENT answer [ - 1 ] //= primefactors [ 0 ] [ 1 ] NEW_LINE DEDENT print ( " { " , end = " " ) NEW_LINE for i in range ( len ( answer ) ) : NEW_LINE INDENT if ( i == len ( answer ) - 1 ) : NEW_LINE INDENT print ( answer [ i ] , end = " } " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( answer [ i ] , end = " , β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT K = 4 NEW_LINE findLongestArray ( K ) NEW_LINE DEDENT |
Minimum number of steps required to place all 1 s at a single index | Function to print minimum steps required to shift all 1 s to a single index in a binary array ; Size of array ; Used to store cumulative sum ; Initialize count ; Traverse the array in forward direction ; Steps needed to store all previous ones to ith index ; Count number of 1 s present till i - th index ; Initialize count ; Traverse the array in backward direction ; Steps needed to store all 1 s to the right of i at current index ; Count number of 1 s present after i - th index ; Print the number of steps required ; Driver Code | def minsteps ( A ) : NEW_LINE INDENT n = len ( A ) NEW_LINE left , right , res = [ 0 ] * n , [ 0 ] * n , [ 0 ] * n NEW_LINE count = A [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT left [ i ] = left [ i - 1 ] + count NEW_LINE count += A [ i ] NEW_LINE DEDENT count = A [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT right [ i ] = right [ i + 1 ] + count NEW_LINE count += A [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT res [ i ] = left [ i ] + right [ i ] NEW_LINE print ( res [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 0 , 1 , 0 ] NEW_LINE minsteps ( A ) NEW_LINE DEDENT |
Minimize flips on K | Function to find the minimum number K - length subarrays required to be flipped to make all array elements 1 ; Stores whether an element can be flipped or not ; Store the required number of flips ; Traverse the array , A [ ] ; Find the prefix sum for the indices i > 0 ; Check if the current element is required to be flipped ; If subarray of size K is not possible , then print - 1 and return ; Increment ans by 1 ; Change the current state of the element ; Decrement isFlipped [ i + K ] ; If subarray of size K is not possible , then print - 1 and return ; Increment ans by 1 ; Change the current state of the element ; Decrement isFlipped [ i + K ] ; Print the result ; Driver Code | def minimumOperations ( A , K ) : NEW_LINE INDENT isflipped = [ 0 ] * ( len ( A ) + 1 ) NEW_LINE ans = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( i > 0 ) : NEW_LINE INDENT isflipped [ i ] += isflipped [ i - 1 ] NEW_LINE isflipped [ i ] %= 2 NEW_LINE DEDENT if ( A [ i ] == 0 and not isflipped [ i ] ) : NEW_LINE INDENT if ( ( len ( A ) - i + 1 ) <= K ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT ans += 1 NEW_LINE isflipped [ i ] += 1 NEW_LINE isflipped [ i + K ] -= 1 NEW_LINE DEDENT elif ( A [ i ] == 1 and isflipped [ i ] ) : NEW_LINE INDENT if ( ( len ( A ) - i + 1 ) <= K ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT ans += 1 NEW_LINE isflipped [ i ] += 1 NEW_LINE isflipped [ i + K ] -= 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 1 , 0 ] NEW_LINE K = 1 NEW_LINE minimumOperations ( arr , K ) NEW_LINE DEDENT |
Calculate sum of scores after N days based on given conditions | Function to c sum of calculate sum of scores after n days ; Store the required sum ; Store the score on previous monday and current day respectively ; Iterate over the range [ 1 , n ] ; If the current day is monday ; Increment score of prev_monday by 1 ; Update score of current day ; Add score of current day and increment score for next day ; Print the result ; Driver Code | def findScoreSum ( n ) : NEW_LINE INDENT total = 0 NEW_LINE prev_monday , curr_day = 0 , 0 NEW_LINE for day in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( day % 7 == 1 ) : NEW_LINE INDENT prev_monday += 1 NEW_LINE curr_day = prev_monday NEW_LINE DEDENT total += curr_day NEW_LINE curr_day += 1 NEW_LINE DEDENT print ( total ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE findScoreSum ( N ) NEW_LINE DEDENT |
Calculate sum of scores after N days based on given conditions | Function to calculate sum of scores after n days ; Store the number of full weeks ; Stores the remaining days in the last week ; Store the sum of scores in the first F full weeks ; Store the sum of scores in the last week ; Print the result ; Driver Code | def findScoreSum ( n ) : NEW_LINE INDENT F = n // 7 NEW_LINE D = n % 7 NEW_LINE fullWeekScore = ( 49 + 7 * F ) * F // 2 NEW_LINE lastNonFullWeekScore = ( 2 * F + D + 1 ) * D // 2 NEW_LINE print ( fullWeekScore + lastNonFullWeekScore ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE findScoreSum ( N ) NEW_LINE DEDENT |
Largest number up to N whose modulus with X is equal to Y modulo X | Function to print the largest number upto N whose modulus with X is same as Y % X ; Stores the required number ; Update num as the result ; Return the resultant number ; Driver Code | def maximumNum ( X , Y , N ) : NEW_LINE INDENT num = 0 NEW_LINE if ( N - N % X + Y <= N ) : NEW_LINE INDENT num = N - N % X + Y NEW_LINE DEDENT else : NEW_LINE INDENT num = N - N % X - ( X - Y ) NEW_LINE DEDENT return num NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 10 NEW_LINE Y = 5 NEW_LINE N = 15 NEW_LINE print ( maximumNum ( X , Y , N ) ) NEW_LINE DEDENT |
Number of points lying inside a rectangle as well as a triangle | Function to calculate area of a triangle ; Return the resultant area ; Function to check if a point lies inside a triangle or not ; Calculate area of triangle ABC ; Calculate area of triangle formed by connecting B , C , point ; Calculate area of triangle formed by connecting A , C , point ; Calculate area of triangle formed by connecting A , B , point ; Check if the sum of the areas of above three triangles the same as ABC ; Function to count the number of points lying inside a triangle & rectangle ; Stores the coordinates of the vertices of the triangles ; Stores the number of points lying inside the triangle and rectangle ; Traverse the array of points ; Stores whether the current point lies inside triangle1 or not ; Stores whether the current point lies inside triangle2 or not ; Stores whether the current point lies inside triangle3 or not ; Stores whether the current point lies inside triangle4 or not ; Stores whether the current point lies inside given triangle or not ; If current point lies inside given triangle as well as inside any of the four obtained triangles ; Print the count of points ; Driver Code | def getArea ( x1 , y1 , x2 , y2 , x3 , y3 ) : NEW_LINE INDENT return abs ( ( x1 * ( y2 - y3 ) + x2 * ( y3 - y1 ) + x3 * ( y1 - y2 ) ) / 2 ) NEW_LINE DEDENT def isInside ( triangle , point ) : NEW_LINE INDENT A , B , C = triangle NEW_LINE x , y = point NEW_LINE ABC = getArea ( A [ 0 ] , A [ 1 ] , B [ 0 ] , B [ 1 ] , C [ 0 ] , C [ 1 ] ) NEW_LINE BPC = getArea ( x , y , B [ 0 ] , B [ 1 ] , C [ 0 ] , C [ 1 ] ) NEW_LINE APC = getArea ( A [ 0 ] , A [ 1 ] , x , y , C [ 0 ] , C [ 1 ] ) NEW_LINE APB = getArea ( A [ 0 ] , A [ 1 ] , B [ 0 ] , B [ 1 ] , x , y ) NEW_LINE return ABC == ( APC + APB + BPC ) NEW_LINE DEDENT def countPoints ( rectangle , triangle , points ) : NEW_LINE INDENT triangle1 = rectangle [ 1 : ] NEW_LINE triangle2 = rectangle [ : 3 ] NEW_LINE triangle3 = rectangle [ : 2 ] NEW_LINE triangle3 . append ( rectangle [ 3 ] ) NEW_LINE triangle4 = rectangle [ - 2 : ] NEW_LINE triangle4 . append ( rectangle [ 0 ] ) NEW_LINE ans = 0 NEW_LINE for point in points : NEW_LINE INDENT condOne = isInside ( triangle1 , point ) NEW_LINE condTwo = isInside ( triangle2 , point ) NEW_LINE condThree = isInside ( triangle3 , point ) NEW_LINE condFour = isInside ( triangle4 , point ) NEW_LINE condFive = isInside ( triangle , point ) NEW_LINE if ( condOne or condTwo or condThree \ or condFour ) and condFive : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT rectangle = [ [ 6 , 5 ] , [ 2 , 2 ] , [ 2 , 1 ] , [ 5 , 5 ] ] NEW_LINE points = [ [ 1 , 1 ] , [ 6 , 1 ] , [ 6 , 6 ] , [ 1 , 6 ] ] NEW_LINE triangle = [ [ 4 , 4 ] , [ 0 , 4 ] , [ 0 , - 2 ] ] NEW_LINE countPoints ( points , triangle , rectangle ) NEW_LINE |
Generate an N | Function to calculate GCD of two integers ; Function to calculate GCD of a given array ; Utility function to check for all the possible combinations ; If an N - length sequence is obtained ; If GCD of the sequence is K ; Otherwise ; Add an element from the first array ; Recursively proceed further ; If combination satisfies the necessary condition ; Remove the element from the combination ; Add an element from the second array ; Recursive proceed further ; If combination satisfies the necessary condition ; Remove the element from the combination ; Function to check all the possible combinations ; Stores the subsequence ; If GCD is not equal to K for any combination ; Given arrays ; Given value of K ; Function call to generate the required subsequence | def GCD ( a , b ) : NEW_LINE INDENT if not b : NEW_LINE INDENT return a NEW_LINE DEDENT return GCD ( b , a % b ) NEW_LINE DEDENT def GCDArr ( a ) : NEW_LINE INDENT ans = a [ 0 ] NEW_LINE for i in a : NEW_LINE INDENT ans = GCD ( ans , i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def findSubseqUtil ( a , b , ans , k , i ) : NEW_LINE INDENT if len ( ans ) == len ( a ) : NEW_LINE INDENT if GCDArr ( ans ) == k : NEW_LINE INDENT print ( ans ) NEW_LINE return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT ans . append ( a [ i ] ) NEW_LINE temp = findSubseqUtil ( a , b , ans , k , i + 1 ) NEW_LINE if temp == True : NEW_LINE INDENT return True NEW_LINE DEDENT ans . pop ( ) NEW_LINE ans . append ( b [ i ] ) NEW_LINE temp = findSubseqUtil ( a , b , ans , k , i + 1 ) NEW_LINE if temp == True : NEW_LINE INDENT return True NEW_LINE DEDENT ans . pop ( ) NEW_LINE DEDENT def findSubseq ( A , B , K , i ) : NEW_LINE INDENT ans = [ ] NEW_LINE findSubseqUtil ( A , B , ans , K , i ) NEW_LINE if not ans : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT A = [ 5 , 3 , 6 , 2 , 9 ] NEW_LINE B = [ 21 , 7 , 14 , 12 , 28 ] NEW_LINE K = 3 NEW_LINE ans = findSubseq ( A , B , K , 0 ) NEW_LINE |
Minimize count of swaps of adjacent elements required to make an array increasing | Function to count minimum number of operations required to obtain an increasing array from given array A [ ] ; Store the required result ; Traverse the array A [ ] ; If the current element is not in its correct position ; Check if it is present at index i - 1 ; Check if it is present at index i - 2 ; Otherwise , print - 1 ( Since A [ i ] can not be swapped more than twice ) ; Print the result ; Driver Code ; Given array ; Store the size of the array | def minimumOperations ( A , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ i ] != ( i + 1 ) ) : NEW_LINE INDENT if ( ( ( i - 1 ) >= 0 ) and A [ i - 1 ] == ( i + 1 ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE A [ i ] , A [ i - 1 ] = A [ i - 1 ] , A [ i ] NEW_LINE DEDENT elif ( ( ( i - 2 ) >= 0 ) and A [ i - 2 ] == ( i + 1 ) ) : NEW_LINE INDENT cnt += 2 NEW_LINE A [ i - 2 ] = A [ i - 1 ] NEW_LINE A [ i - 1 ] = A [ i ] NEW_LINE A [ i ] = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( cnt ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 7 , 3 , 2 , 1 , 4 ] NEW_LINE n = len ( A ) NEW_LINE minimumOperations ( A , n ) NEW_LINE DEDENT |
Count occurrences of an element in a matrix of size N * N generated such that each element is equal to product of its indices | Set | Function to count the occurrences of X in the generated square matrix ; Store the required result ; Iterate over the range [ 1 , N ] ; Check if x is a multiple of i or not ; Check if the other multiple exists in the range or not ; Print the result ; Driver Code | def countOccurrences ( n , x ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT if ( x // i <= n ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 NEW_LINE X = 12 NEW_LINE countOccurrences ( N , X ) NEW_LINE DEDENT |
Reduce all array elements to zero by performing given operations thrice | Function to reduce all array elements to zero ; If size of array is 1 ; First operation ; 2 nd Operation ; 3 rd Operation ; Otherwise ; 1 st Operation ; 2 nd Operation ; 3 rd Operation ; Driver Code ; Input ; Function call to make all array elements equal to 0 | def ConvertArray ( arr , N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( " Operation β 1 β : " , 1 , 1 ) NEW_LINE print ( " Added β elements : " , - 1 * arr [ 0 ] ) NEW_LINE print ( " " , end β = β " " ) NEW_LINE print ( " Operation β 2 β : " , 1 , 1 ) NEW_LINE print ( " Added β elements : " , 1 * arr [ 0 ] ) NEW_LINE print ( " " , end β = β " " ) NEW_LINE print ( " Operation β 3 β : " , 1 , 1 ) NEW_LINE print ( " Added β elements : " , - 1 * arr [ 0 ] ) NEW_LINE print ( " " , end β = β " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Operation β 1 β : " , 1 , N ) NEW_LINE print ( " Added β elements : " , end = " β " ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( - 1 * arr [ i ] * N , end = " β " ) NEW_LINE DEDENT print ( " " ) NEW_LINE print ( " Operation β 2 β : " , 1 , N - 1 ) NEW_LINE print ( " Added β elements : " , end = " β " ) NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT print ( arr [ i ] * ( N - 1 ) , end = " β " ) NEW_LINE DEDENT print ( " " ) NEW_LINE print ( " Operation β 3 β : β " , N , N ) NEW_LINE print ( " Added β elements : " , end = " β " ) NEW_LINE print ( arr [ N - 1 ] * ( N - 1 ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE ConvertArray ( arr , N ) NEW_LINE DEDENT |
Count pairs from an array with even product of count of distinct prime factors | Python 3 implementation of the above approach ; Function to calculate count of distinct prime factors of a number ; Sieve of Eratosthenes ; Function to count pairs with even product of distinct prime factors ; Stores count of distinct prime factors ; Stores the count of numbers with even prime factors in B [ ] ; Stores the count of numbers with odd prime factors in B [ ] ; Even Product Pairs ; Traverse the array B [ ] ; Since , product has to be positive i . e > 0 ; If count of prime factors is odd ; Increment oddCount by 1 ; Increment evenCount by 1 ; Since , product has to be positive i . e > 0 ; If count of prime factors is odd ; odd * even = even ; If count of prime factors is even ; even * odd = even even * even = even ; Driver Code | MAX = 1000000 NEW_LINE def countOfPrimefactors ( CountDistinct ) : NEW_LINE INDENT global MAX NEW_LINE prime = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE for i in range ( MAX + 1 ) : NEW_LINE INDENT CountDistinct [ i ] = 0 NEW_LINE prime [ i ] = True NEW_LINE DEDENT for i in range ( 2 , MAX + 1 , 1 ) : NEW_LINE INDENT if ( prime [ i ] == True ) : NEW_LINE INDENT CountDistinct [ i ] = 1 NEW_LINE for j in range ( i * 2 , MAX + 1 , i ) : NEW_LINE INDENT CountDistinct [ j ] += 1 NEW_LINE prime [ j ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def CountEvenPair ( A , B , N , M ) : NEW_LINE INDENT global MAX NEW_LINE countDistinct = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE countOfPrimefactors ( countDistinct ) NEW_LINE evenCount = 0 NEW_LINE oddCount = 0 NEW_LINE evenPairs = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT if ( countDistinct [ B [ i ] ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( countDistinct [ B [ i ] ] & 1 ) : NEW_LINE INDENT oddCount += 1 NEW_LINE DEDENT else : NEW_LINE INDENT evenCount += 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( countDistinct [ A [ i ] ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( countDistinct [ A [ i ] ] & 1 ) : NEW_LINE INDENT evenPairs += ( evenCount ) NEW_LINE DEDENT else : NEW_LINE INDENT evenPairs += evenCount + oddCount NEW_LINE DEDENT DEDENT return evenPairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 ] NEW_LINE B = [ 4 , 5 , 6 ] NEW_LINE N = len ( A ) NEW_LINE M = len ( B ) NEW_LINE print ( CountEvenPair ( A , B , N , M ) ) NEW_LINE DEDENT |
Minimum array elements required to be subtracted from either end to reduce K to 0 | Function to find the length of longest subarray having sum K ; Stores the index of the prefix sum ; Traverse the given array ; Update sum ; If the subarray starts from index 0 ; Add the current prefix sum with index if it is not present in the map um ; Check if sum - K is present in Map um or not ; Update the maxLength ; Return the required maximum length ; Function to find the minimum removal of array elements required to reduce K to 0 ; Stores the sum of the array ; Traverse the array arr [ ] ; Update sum of the array ; Find maxLen ; If the subarray with sum doesn 't exist ; Otherwise , print the required maximum length ; Driver Code | def longestSubarray ( arr , N , K ) : NEW_LINE INDENT um = { } NEW_LINE sum , maxLen = 0 , 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE if ( sum == K ) : NEW_LINE INDENT maxLen = i + 1 NEW_LINE DEDENT if ( sum not in um ) : NEW_LINE INDENT um [ sum ] = i NEW_LINE DEDENT if ( ( sum - K ) in um ) : NEW_LINE INDENT if ( maxLen < ( i - um [ sum - K ] ) ) : NEW_LINE INDENT maxLen = i - um [ sum - K ] NEW_LINE DEDENT DEDENT DEDENT return maxLen NEW_LINE DEDENT def minRequiredOperation ( arr , N , K ) : NEW_LINE INDENT TotalSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT TotalSum += arr [ i ] NEW_LINE DEDENT maxLen = longestSubarray ( arr , N , TotalSum - K ) NEW_LINE if ( maxLen == - 1 ) : NEW_LINE INDENT print ( - 1 , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( N - maxLen , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 1 , 1 , 2 ] NEW_LINE K = 4 NEW_LINE N = len ( arr ) NEW_LINE minRequiredOperation ( arr , N , K ) NEW_LINE DEDENT |
Minimum number of digits required to be removed to make a number divisible by 4 | Function to count the minimum number of digits required to be removed to make a given number divisible by 4 ; Store the size of the string ; Stores the required result ; Check for every pair of digits if the number formed by them is divisible by 4 or not ; Store s [ i ] in a variable ; If it is divisible by 2 ; Store the number formed by s [ j ] and s [ i ] ; Check if it is divisible by 4 ; Store the number of digits required to be deleted ; Update ans ; If value of ans is unchanged , then check if any s [ i ] is divisible by 4 ; If true , update ans to n - 1 ; Prthe result ; Driver Code | def minimumDeletions ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = n NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT t = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE if ( t % 2 == 0 ) : NEW_LINE INDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT num = ( ord ( s [ j ] ) - ord ( '0' ) ) * 10 + t NEW_LINE if ( num % 4 == 0 ) : NEW_LINE INDENT k1 = i - j - 1 NEW_LINE k2 = n - i - 1 NEW_LINE ans = min ( ans , k1 + k2 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( ans == n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT num = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE if ( num % 4 == 0 ) : NEW_LINE INDENT ans = n - 1 NEW_LINE DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "12367" NEW_LINE minimumDeletions ( str ) NEW_LINE DEDENT |
Generate a sequence such that float division of array elements is maximized | Function to place the parenthesis such that the result is maximized ; Store the required string ; Add the first integer to string ; If the size of array is 1 ; If the size of array is 2 , print the 1 st integer followed by / operator followed by the next integer ; If size of array is exceeds two , pr1st integer concatenated with operators ' / ' , ' ( ' and next integers with the operator '/ ; Add parenthesis at the end ; Prthe final expression ; Driver Code | def generateSequence ( arr , n ) : NEW_LINE INDENT ans = " " NEW_LINE ans = str ( arr [ 0 ] ) NEW_LINE if ( n == 1 ) : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT elif ( n == 2 ) : NEW_LINE INDENT print ( ans + " / " + str ( arr [ 1 ] ) ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT else : NEW_LINE INDENT ans += " / ( " + str ( arr [ 1 ] ) NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT ans += " / " + str ( arr [ i ] ) NEW_LINE DEDENT ans += " ) " NEW_LINE print ( ans ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1000 , 100 , 10 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE generateSequence ( arr , N ) NEW_LINE DEDENT |
Count of pairs having even and odd LCM from an array | Function to find count of distinct pairs having even LCM and odd LCM ; Store the total number of pairs ; Stores the count of odd numbers in the array ; Traverse the array arr [ ] ; Update the count of pairs with odd LCM ; Print the count of required pairs ; Driver Code | def LCMPairs ( arr , N ) : NEW_LINE INDENT total_pairs = ( N * ( N - 1 ) ) / 2 NEW_LINE odd = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT DEDENT odd = ( odd * ( odd - 1 ) ) // 2 NEW_LINE print ( " Even β = " , int ( total_pairs - odd ) , " , " , " β Odd β = " , odd ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 5 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE LCMPairs ( arr , N ) NEW_LINE DEDENT |
Value required to be added to N to obtain the sum of first M multiples of K | Function to print the value to be added to N to obtain sum of first M multiples of K ; Store the sum of the first M multiples of K ; Store the value to be added to obtain N ; Input | def printNumber ( N , K , M ) : NEW_LINE INDENT sum = K * ( M * ( M + 1 ) / 2 ) NEW_LINE return sum - N NEW_LINE DEDENT N = 17 NEW_LINE K = 3 NEW_LINE M = 4 NEW_LINE print ( int ( printNumber ( N , K , M ) ) ) NEW_LINE |
Count even and odd Bitwise XORs of consecutive numbers in a range [ L , R ] starting from L | Prcount of even and odd numbers of XOR value from L to R ; Store the number of elements between L and R ; Count of even XOR values ; If L is odd and range % 4 = 3 ; Increment even by 1 ; If L is even and range % 4 != 0 ; Increment even by 1 ; Prthe answer ; Driver Code | def countEvenOdd ( L , R ) : NEW_LINE INDENT range = R - L + 1 ; NEW_LINE even = ( range // 4 ) * 2 ; NEW_LINE if ( ( L & 1 ) != 0 and ( range % 4 == 3 ) ) : NEW_LINE INDENT even += 1 ; NEW_LINE DEDENT elif ( ( L & 1 ) == 0 and ( range % 4 != 0 ) ) : NEW_LINE INDENT even += 1 ; NEW_LINE DEDENT print ( " Even β = β " , even , " , β Odd β = β " , ( range - even ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 2 ; R = 7 ; NEW_LINE countEvenOdd ( L , R ) ; NEW_LINE DEDENT |
Minimize swaps of same | Function to count the number of swaps required to make the sum of ASCII values of the characters of both strings odd ; Initialize alphabets with value ; Initialize values for each alphabet ; Size of the string ; Sum of S ; Sum of T ; Stores whether there is any index i such that S [ i ] and T [ i ] have different parities ; Traverse the strings ; Update sum1 and sum2 ; If ord ( S [ i ] ) anord ( ' a ) rd ( T [ i ] ) β haord ( ' a ) different parities ; If sum1 and sum2 are both odd ; If sum1 and sum2 are both even ; If exists pr1 ; Otherwise ; If sum1 and sum2 are of different parities ; Driver Code ; Function Call | def countSwaps ( S , T ) : NEW_LINE INDENT value = [ 0 ] * 26 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT value [ i ] = i + 1 NEW_LINE DEDENT N = len ( S ) NEW_LINE sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE flag = False NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum1 += value [ ord ( S [ i ] ) - ord ( ' a ' ) ] NEW_LINE sum2 += value [ ord ( T [ i ] ) - ord ( ' a ' ) ] NEW_LINE if ( value [ ord ( S [ i ] ) - ord ( ' a ' ) ] % 2 == 0 and value [ ord ( T [ i ] ) - ord ( ' a ' ) ] % 2 == 1 or value [ ord ( S [ i ] ) - ord ( ' a ' ) ] % 2 == 1 and value [ ord ( T [ i ] ) - ord ( ' a ' ) ] % 2 == 0 ) : NEW_LINE INDENT flag = False NEW_LINE DEDENT DEDENT if ( sum1 % 2 == 1 and sum2 % 2 == 1 ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT elif ( sum1 % 2 == 0 and sum2 % 2 == 0 ) : NEW_LINE INDENT if ( flag ) : NEW_LINE INDENT print ( "1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " acd " NEW_LINE T = " dbf " NEW_LINE countSwaps ( S , T ) NEW_LINE DEDENT |
Count distinct prime triplets up to N such that sum of two primes is equal to the third prime | Python3 program for the above approach ; Function to check if a number is a prime or not ; Function to count the number of valid prime triplets ; Stores the count of prime triplets ; Iterate from 2 to N and check for each p , whether p & ( p - 2 ) are prime or not ; Prthe count obtained ; Driver Code | import math NEW_LINE def isPrime ( N ) : NEW_LINE INDENT if ( N <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , int ( math . sqrt ( N ) + 1 ) ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def countPrimeTuples ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( isPrime ( i ) and isPrime ( i - 2 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT N = 6 NEW_LINE countPrimeTuples ( N ) NEW_LINE |
Count pairs from an array whose Bitwise OR is greater than Bitwise AND | Function to count the number of pairs ( i , j ) their Bitwise OR is greater than Bitwise AND ; Store the required answer ; Check for all possible pairs ; If the condition satisfy then increment count by 1 ; Prthe answer ; Driver Code ; Function Call | def countPairs ( A , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( ( A [ i ] A [ j ] ) > ( A [ i ] & A [ j ] ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT print ( count ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 4 , 7 ] ; NEW_LINE N = len ( A ) ; NEW_LINE countPairs ( A , N ) ; NEW_LINE DEDENT |
Count maximum number of consumable candies | Function to find the count of maximum consumable candies ; Store the count of total candies ; Stores the count of maximum consumable candies ; Checks if it is safe to counsume all candies ; Traverse the array arr ; If A [ i ] + M is greater than B [ i ] ; Mark all_safe as false ; Update ans ; Update ans ; Increment total by A [ i ] ; If all_safe is true ; Otherwise , ; Driver Code ; Function call to find maximum consumable candies | def maximumCandy ( candies , safety , N , M ) : NEW_LINE INDENT total = 0 NEW_LINE ans = 10 ** 8 NEW_LINE all_safe = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( candies [ i ] + M > safety [ i ] ) : NEW_LINE INDENT all_safe = False NEW_LINE ans = min ( ans , safety [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = min ( ans , candies [ i ] + M ) NEW_LINE DEDENT total += candies [ i ] NEW_LINE DEDENT if ( all_safe ) : NEW_LINE INDENT return total NEW_LINE DEDENT else : NEW_LINE INDENT return ans NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 4 , 5 , 2 , 3 ] NEW_LINE B = [ 8 , 13 , 6 , 4 ] NEW_LINE M = 5 NEW_LINE N = len ( A ) NEW_LINE print ( maximumCandy ( A , B , N , M ) ) NEW_LINE DEDENT |
Check if two arrays can be made equal by swapping pairs of one of the arrays | Function to check if two arrays can be made equal or not by swapping pairs of only one of the arrays ; Stores elements required to be replaced ; To check if the arrays can be made equal or not ; Traverse the array ; If array elements are not equal ; Increment count by 1 ; Decrement count by 1 ; If flag is true and count is 0 , pr " Yes " . Otherwise " No " ; Driver Code ; Given arrays ; Size of the array | def checkArrays ( arr1 , arr2 , N ) : NEW_LINE INDENT count = 0 NEW_LINE flag = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr1 [ i ] != arr2 [ i ] ) : NEW_LINE INDENT if ( arr1 [ i ] == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count -= 1 NEW_LINE if ( count < 0 ) : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( flag and count == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 0 , 0 , 1 , 1 ] NEW_LINE arr2 = [ 1 , 1 , 0 , 0 ] NEW_LINE N = len ( arr1 ) NEW_LINE checkArrays ( arr1 , arr2 , N ) NEW_LINE DEDENT |
Generate an N | Function to construct an array with sum of each subarray divisible by K ; Traverse a loop from 1 to N ; Pri - th multiple of K ; Driver Code | def construct_Array ( N , K ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( K * i , end = " β " ) NEW_LINE DEDENT DEDENT N = 3 NEW_LINE K = 3 NEW_LINE construct_Array ( N , K ) NEW_LINE |
Generate an N | Fun dtion to print the required sequence ; Stores count of even and odd elements ; Stores sum of even and odd elements ; Print N / 2 even elements ; Print N / 2 - 1 odd elements ; Print final odd element ; Driver Code | def Print ( N ) : NEW_LINE INDENT if ( ( N / 2 ) % 2 or ( N % 2 ) ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT CurEven = 2 NEW_LINE CurOdd = 1 NEW_LINE SumOdd = 0 NEW_LINE SumEven = 0 NEW_LINE for i in range ( N // 2 ) : NEW_LINE INDENT print ( CurEven , end = " β " ) NEW_LINE SumEven += CurEven NEW_LINE CurEven += 2 NEW_LINE DEDENT for i in range ( ( N // 2 ) - 1 ) : NEW_LINE INDENT print ( CurOdd , end = " β " ) NEW_LINE SumOdd += CurOdd NEW_LINE CurOdd += 2 NEW_LINE DEDENT CurOdd = SumEven - SumOdd NEW_LINE print ( CurOdd ) NEW_LINE DEDENT N = 12 NEW_LINE Print ( N ) NEW_LINE |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.