text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Minimize prize count required such that smaller value gets less prize in an adjacent pair | C ++ implementation to find the minimum prizes required such that adjacent smaller elements gets less number of prizes ; Function to find the minimum number of required such that adjacent smaller elements gets less number of prizes ; Loop to compute the smaller elements at the left ; Loop to find the smaller elements at the right ; Loop to find the minimum prizes required ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minPrizes ( int arr [ ] , int n ) { int dpLeft [ n ] ; dpLeft [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] ) { dpLeft [ i ] = dpLeft [ i - 1 ] + 1 ; } else { dpLeft [ i ] = 1 ; } } int dpRight [ n ] ; dpRight [ n - 1 ] = 1 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > arr [ i + 1 ] ) { dpRight [ i ] = dpRight [ i + 1 ] + 1 ; } else { dpRight [ i ] = 1 ; } } int totalPrizes = 0 ; for ( int i = 0 ; i < n ; i ++ ) { totalPrizes += max ( dpLeft [ i ] , dpRight [ i ] ) ; } cout << totalPrizes << endl ; return 0 ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minPrizes ( arr , n ) ; return 0 ; } |
Maximum sum subsequence with values differing by at least 2 | C ++ program to find maximum sum subsequence with values differing by at least 2 ; function to find maximum sum subsequence such that two adjacent values elements are not selected ; map to store the frequency of array elements ; make a dp array to store answer upto i th value ; base cases ; iterate for all possible values of arr [ i ] ; return the last value ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int get_max_sum ( int arr [ ] , int n ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } int dp [ 100001 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] = 0 ; dp [ 1 ] = freq [ 0 ] ; for ( int i = 2 ; i <= 100000 ; i ++ ) { dp [ i ] = max ( dp [ i - 1 ] , dp [ i - 2 ] + i * freq [ i ] ) ; } return dp [ 100000 ] ; } int main ( ) { int N = 3 ; int arr [ ] = { 2 , 2 , 3 } ; cout << get_max_sum ( arr , N ) ; return 0 ; } |
Minimum flips required to keep all 1 s together in a Binary string | cpp implementation for Minimum number of flips required in a binary string such that all the 1 aTMs are together ; Length of the binary string ; Initial state of the dp dp [ 0 ] [ 0 ] will be 1 if the current bit is 1 and we have to flip it ; Initial state of the dp dp [ 0 ] [ 1 ] will be 1 if the current bit is 0 and we have to flip it ; dp [ i ] [ 0 ] = Flips required to make all previous bits zero + Flip required to make current bit zero ; dp [ i ] [ 1 ] = minimum flips required to make all previous states 0 or make previous states 1 satisfying the condition ; Minimum of answer and flips required to make all bits 0 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minFlip ( string a ) { int n = a . size ( ) ; vector < vector < int > > dp ( n + 1 , vector < int > ( 2 , 0 ) ) ; dp [ 0 ] [ 0 ] = ( a [ 0 ] == '1' ) ; dp [ 0 ] [ 1 ] = ( a [ 0 ] == '0' ) ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + ( a [ i ] == '1' ) ; dp [ i ] [ 1 ] = min ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) + ( a [ i ] == '0' ) ; } int answer = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { answer = min ( answer , dp [ i ] [ 1 ] + dp [ n - 1 ] [ 0 ] - dp [ i ] [ 0 ] ) ; } return min ( answer , dp [ n - 1 ] [ 0 ] ) ; } int main ( ) { string s = "1100111000101" ; cout << ( minFlip ( s ) ) ; } |
Length of longest increasing index dividing subsequence | C ++ program to find the length of the longest increasing sub - sequence such that the index of the element is divisible by index of previous element ; Function to find the length of the longest increasing sub - sequence such that the index of the element is divisible by index of previous element ; Initialize the dp [ ] array with 1 as a single element will be of 1 length ; Traverse the given array ; If the index is divisible by the previous index ; if increasing subsequence identified ; Longest length is stored ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int LIIDS ( int arr [ ] , int N ) { int dp [ N + 1 ] ; int ans = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { dp [ i ] = 1 ; } for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = i + i ; j <= N ; j += i ) { if ( arr [ j ] > arr [ i ] ) { dp [ j ] = max ( dp [ j ] , dp [ i ] + 1 ) ; } } ans = max ( ans , dp [ i ] ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 7 , 9 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << LIIDS ( arr , N ) ; return 0 ; } |
Count of subarrays having exactly K perfect square numbers | C ++ program to Count of subarrays having exactly K perfect square numbers . ; A utility function to check if the number n is perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; Function to find number of subarrays with sum exactly equal to k ; STL map to store number of subarrays starting from index zero having particular value of sum . ; To store the sum of element traverse so far ; Add current element to currsum ; If currsum = K , then a new subarray is found ; If currsum > K then find the no . of subarrays with sum currsum - K and exclude those subarrays ; Add currsum to count of different values of sum ; Return the final result ; Function to count the subarray with K perfect square numbers ; Update the array element ; If current element is perfect square then update the arr [ i ] to 1 ; Else change arr [ i ] to 0 ; Function Call ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( long double x ) { long double sr = sqrt ( x ) ; return ( ( sr - floor ( sr ) ) == 0 ) ; } int findSubarraySum ( int arr [ ] , int n , int K ) { unordered_map < int , int > prevSum ; int res = 0 ; int currsum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { currsum += arr [ i ] ; if ( currsum == K ) { res ++ ; } if ( prevSum . find ( currsum - K ) != prevSum . end ( ) ) res += ( prevSum [ currsum - K ] ) ; prevSum [ currsum ] ++ ; } return res ; } void countSubarray ( int arr [ ] , int n , int K ) { for ( int i = 0 ; i < n ; i ++ ) { if ( isPerfectSquare ( arr [ i ] ) ) { arr [ i ] = 1 ; } else { arr [ i ] = 0 ; } } cout << findSubarraySum ( arr , n , K ) ; } int main ( ) { int arr [ ] = { 2 , 4 , 9 , 2 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countSubarray ( arr , N , K ) ; return 0 ; } |
Number of ways to split N as sum of K numbers from the given range | C ++ implementation to count the number of ways to divide N in K groups such that each group has elements in range [ L , R ] ; Function to count the number of ways to divide the number N in K groups such that each group has number of elements in range [ L , R ] ; Base Case ; if N is divides completely into less than k groups ; put all possible values greater equal to prev ; Function to count the number of ways to divide the number N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1000000007 ; int calculate ( int pos , int left , int k , int L , int R ) { if ( pos == k ) { if ( left == 0 ) return 1 ; else return 0 ; } if ( left == 0 ) return 0 ; int answer = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( i > left ) break ; answer = ( answer + calculate ( pos + 1 , left - i , k , L , R ) ) % mod ; } return answer ; } int countWaystoDivide ( int n , int k , int L , int R ) { return calculate ( 0 , n , k , L , R ) ; } int main ( ) { int N = 12 ; int K = 3 ; int L = 1 ; int R = 5 ; cout << countWaystoDivide ( N , K , L , R ) ; return 0 ; } |
Check if it is possible to get given sum by taking one element from each row | C ++ implementation to find whether is it possible to make sum equal to K ; Function that prints whether is it possible to make sum equal to K ; Base case ; Condition if we can make sum equal to current column by using above rows ; Iterate through current column and check whether we can make sum less than or equal to k ; Printing whether is it possible or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void PossibleSum ( int n , int m , vector < vector < int > > v , int k ) { int dp [ n + 1 ] [ k + 1 ] = { 0 } ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j <= k ; j ++ ) { if ( dp [ i ] [ j ] == 1 ) { for ( int d = 0 ; d < m ; d ++ ) { if ( ( j + v [ i ] [ d ] ) <= k ) { dp [ i + 1 ] [ j + v [ i ] [ d ] ] = 1 ; } } } } } if ( dp [ n ] [ k ] == 1 ) cout << " YES STRNEWLINE " ; else cout << " NO STRNEWLINE " ; } int main ( ) { int N = 2 , M = 10 , K = 5 ; vector < vector < int > > arr = { { 4 , 0 , 15 , 3 , 2 , 20 , 10 , 1 , 5 , 4 } , { 4 , 0 , 10 , 3 , 2 , 25 , 4 , 1 , 5 , 4 } } ; PossibleSum ( N , M , arr , K ) ; return 0 ; } |
Modify array by merging elements with addition such that it consists of only Primes . | C ++ program to find the array of primes ; DP array to store the ans for max 20 elements ; To check whether the number is prime or not ; Function to check whether the array can be modify so that there are only primes ; If curr is prime and all elements are visited , return true ; If all elements are not visited , set curr = 0 , to search for new prime sum ; If all elements are visited ; If the current sum is not prime return false ; If this state is already calculated , return the answer directly ; Try all state of mask ; If ith index is not set ; Add the current element and set ith index and recur ; If subset can be formed then return true ; After every possibility of mask , if the subset is not formed , return false by memoizing . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool dp [ 1 << 20 ] ; bool isprime ( int n ) { if ( n == 1 ) return false ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { return false ; } } return true ; } int solve ( int arr [ ] , int curr , int mask , int n ) { if ( isprime ( curr ) ) { if ( mask == ( 1 << n ) - 1 ) { return true ; } curr = 0 ; } if ( mask == ( 1 << n ) - 1 ) { if ( ! isprime ( curr ) ) { return false ; } } if ( dp [ mask ] ) return dp [ mask ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! ( mask & 1 << i ) ) { if ( solve ( arr , curr + arr [ i ] , mask 1 << i , n ) ) { return true ; } } } return dp [ mask ] = false ; } int main ( ) { int arr [ ] = { 3 , 6 , 7 , 13 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( solve ( arr , 0 , 0 , n ) ) { cout << " YES " ; } else { cout << " NO " ; } return 0 ; } |
Maximum sum in circular array such that no two elements are adjacent | Set 2 | C ++ program to find maximum sum in circular array such that no two elements are adjacent ; Store the maximum possible at each index ; When i exceeds the index of the last element simply return 0 ; If the value has already been calculated , directly return it from the dp array ; The next states are don 't take this element and go to (i + 1)th state else take this element and go to (i + 2)th state ; function to find the max value ; subarr contains elements from 0 to arr . size ( ) - 2 ; Initializing all the values with - 1 ; Calculating maximum possible sum for first case ; subarr contains elements from 1 to arr . size ( ) - 1 ; Re - initializing all values with - 1 ; Calculating maximum possible sum for second case ; Printing the maximum between them ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > dp ; int maxSum ( int i , vector < int > & subarr ) { if ( i >= subarr . size ( ) ) return 0 ; if ( dp [ i ] != -1 ) return dp [ i ] ; return dp [ i ] = max ( maxSum ( i + 1 , subarr ) , subarr [ i ] + maxSum ( i + 2 , subarr ) ) ; } int Func ( vector < int > arr ) { vector < int > subarr = arr ; subarr . pop_back ( ) ; dp . resize ( subarr . size ( ) , -1 ) ; int max1 = maxSum ( 0 , subarr ) ; subarr = arr ; subarr . erase ( subarr . begin ( ) ) ; dp . clear ( ) ; dp . resize ( subarr . size ( ) , -1 ) ; int max2 = maxSum ( 0 , subarr ) ; cout << max ( max1 , max2 ) << endl ; } int main ( ) { vector < int > arr = { 1 , 2 , 3 , 1 } ; Func ( arr ) ; return 0 ; } |
Count all square sub | C ++ program to count total number of k x k sub matrix whose sum is greater than the given number S ; Function to create Prefix sum matrix from the given matrix ; Store first value in table ; Initialize first row of matrix ; Initialize first column of matrix ; Initialize rest table with sum ; Utility Function to count the submatrix whose sum is greater than the S ; Loop to iterate over all the possible positions of the given matrix mat [ ] [ ] ; Condition to check , if K x K is first sub matrix ; Condition to check sub - matrix has no margin at top ; Condition when sub matrix has no margin at left ; Condition when submatrix has margin at top and left ; Increment count , If sub matrix sum is greater than S ; Function to count submatrix of size k x k such that sum if greater than or equal to S ; For loop to initialize prefix sum matrix with zero , initially ; Function to create the prefix sum matrix ; Driver Code ; Print total number of sub matrix | #include <iostream> NEW_LINE using namespace std ; #define dim 5 NEW_LINE void createTable ( int mtrx [ ] [ dim ] , int k , int p , int dp [ ] [ dim ] ) { dp [ 0 ] [ 0 ] = mtrx [ 0 ] [ 0 ] ; for ( int j = 1 ; j < dim ; j ++ ) { dp [ 0 ] [ j ] = mtrx [ 0 ] [ j ] + dp [ 0 ] [ j - 1 ] ; } for ( int i = 1 ; i < dim ; i ++ ) { dp [ i ] [ 0 ] = mtrx [ i ] [ 0 ] + dp [ i - 1 ] [ 0 ] ; } for ( int i = 1 ; i < dim ; i ++ ) { for ( int j = 1 ; j < dim ; j ++ ) { dp [ i ] [ j ] = mtrx [ i ] [ j ] + dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] - dp [ i - 1 ] [ j - 1 ] ; } } } int countSubMatrixUtil ( int dp [ ] [ dim ] , int k , int p ) { int count = 0 ; int subMatSum = 0 ; for ( int i = k - 1 ; i < dim ; i ++ ) { for ( int j = k - 1 ; j < dim ; j ++ ) { if ( i == ( k - 1 ) || j == ( k - 1 ) ) { if ( i == ( k - 1 ) && j == ( k - 1 ) ) { subMatSum = dp [ i ] [ j ] ; } else if ( i == ( k - 1 ) ) { subMatSum = dp [ i ] [ j ] - dp [ i ] [ j - k ] ; } else { subMatSum = dp [ i ] [ j ] - dp [ i - k ] [ j ] ; } } else { subMatSum = dp [ i ] [ j ] - dp [ i - k ] [ j ] - dp [ i ] [ j - k ] + dp [ i - k ] [ j - k ] ; } if ( subMatSum >= p ) { count ++ ; } } } return count ; } int countSubMatrix ( int mtrx [ ] [ dim ] , int k , int p ) { int dp [ dim ] [ dim ] ; for ( int i = 0 ; i < dim ; i ++ ) { for ( int j = 0 ; j < dim ; j ++ ) { dp [ i ] [ j ] = 0 ; } } createTable ( mtrx , k , p , dp ) ; return countSubMatrixUtil ( dp , k , p ) ; } int main ( ) { int mtrx [ dim ] [ dim ] = { { 1 , 7 , 1 , 1 , 1 } , { 2 , 2 , 2 , 2 , 2 } , { 3 , 9 , 6 , 7 , 3 } , { 4 , 3 , 2 , 4 , 5 } , { 5 , 1 , 5 , 3 , 1 } } ; int k = 3 ; int p = 35 ; cout << countSubMatrix ( mtrx , k , p ) ; return 0 ; } |
Check if a substring can be Palindromic by replacing K characters for Q queries | C ++ program for the above approach ; Function to find whether string can be made palindromic or not for each queries ; To store the count of ith character of substring str [ 0. . . i ] ; Current character ; Update dp [ ] [ ] on the basis recurrence relation ; For each queries ; To store the count of distinct character ; Find occurrence of i + ' a ' ; Half the distinct Count ; If half the distinct count is less than equals to K then palindromic string can be made ; Driver Code ; Given string str ; Given Queries ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void canMakePaliQueries ( string str , vector < vector < int > > & Q ) { int n = str . length ( ) ; vector < vector < int > > dp ( 26 , vector < int > ( n , 0 ) ) ; for ( int i = 0 ; i < 26 ; i ++ ) { char currentChar = i + ' a ' ; for ( int j = 0 ; j < n ; j ++ ) { if ( j == 0 ) { dp [ i ] [ j ] = ( str [ j ] == currentChar ) ; } else { dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + ( str [ j ] == currentChar ) ; } } } for ( auto query : Q ) { int left = query [ 0 ] ; int right = query [ 1 ] ; int k = query [ 2 ] ; int unMatchedCount = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { int occurrence = dp [ i ] [ right ] - dp [ i ] [ left ] + ( str [ left ] == ( i + ' a ' ) ) ; if ( occurrence & 1 ) unMatchedCount ++ ; } int ans = unMatchedCount / 2 ; if ( ans <= k ) { cout << " YES STRNEWLINE " ; } else { cout << " NO STRNEWLINE " ; } } } int main ( ) { string str = " GeeksforGeeks " ; vector < vector < int > > Q ; Q = { { 1 , 5 , 3 } , { 5 , 7 , 0 } , { 8 , 11 , 3 } , { 3 , 10 , 5 } , { 0 , 9 , 5 } } ; canMakePaliQueries ( str , Q ) ; return 0 ; } |
Word Break Problem | DP | C ++ implementation to break a sequence into the words of the dictionary ; Unordered_map used for storing the sentences the key string can be broken into ; Unordered_set used to store the dictionary . ; Utility function used for printing the obtained result ; Utility function for appending new words to already existing strings ; Loop to find the append string which can be broken into ; Utility function for word Break ; Condition to check if the subproblem is already computed ; If the whole word is a dictionary word then directly append into the result array for the string ; Loop to iterate over the substring ; If the substring is present into the dictionary then recurse for other substring of the string ; Store the subproblem into the map ; Master wordBreak function converts the string vector to unordered_set ; Clear the previous stored data ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_map < string , vector < string > > mp ; unordered_set < string > dict ; void printResult ( vector < string > A ) { for ( int i = 0 ; i < A . size ( ) ; i ++ ) cout << A [ i ] << ' ' ; } vector < string > combine ( vector < string > prev , string word ) { for ( int i = 0 ; i < prev . size ( ) ; i ++ ) { prev [ i ] += " β " + word ; } return prev ; } vector < string > wordBreakUtil ( string s ) { if ( mp . find ( s ) != mp . end ( ) ) return mp [ s ] ; vector < string > res ; if ( dict . find ( s ) != dict . end ( ) ) res . push_back ( s ) ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { string word = s . substr ( i ) ; if ( dict . find ( word ) != dict . end ( ) ) { string rem = s . substr ( 0 , i ) ; vector < string > prev = combine ( wordBreakUtil ( rem ) , word ) ; res . insert ( res . end ( ) , prev . begin ( ) , prev . end ( ) ) ; } } mp [ s ] = res ; return res ; } vector < string > wordBreak ( string s , vector < string > & wordDict ) { mp . clear ( ) ; dict . clear ( ) ; dict . insert ( wordDict . begin ( ) , wordDict . end ( ) ) ; return wordBreakUtil ( s ) ; } int main ( ) { vector < string > wordDict1 = { " cat " , " cats " , " and " , " sand " , " dog " } ; printResult ( wordBreak ( " catsanddog " , wordDict1 ) ) ; return 0 ; } |
Maximize product of digit sum of consecutive pairs in a subsequence of length K | C ++ implementation to find the maximum product of the digit sum of the consecutive pairs of the subsequence of the length K ; Function to find the product of two numbers digit sum in the pair ; Loop to find the digits of the number ; Loop to find the digits of other number ; Function to find the subsequence of the length K ; Base Case ; Condition when we didn 't reach the length K, but ran out of elements of the array ; Condition if already calculated ; If length upto this point is odd ; If length is odd , it means we need second element of this current pair , calculate the product of digit sum of current and previous element and recur by moving towards next index ; If length upto this point is even ; Exclude this current element and recur for next elements . ; return by memoizing it , by selecting the maximum among two choices . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; int dp [ 1000 ] [ MAX ] [ MAX ] ; int productDigitSum ( int x , int y ) { int sumx = 0 ; while ( x ) { sumx += ( x % 10 ) ; x /= 10 ; } int sumy = 0 ; while ( y ) { sumy += ( y % 10 ) ; y /= 10 ; } return ( sumx * sumy ) ; } int solve ( int arr [ ] , int i , int len , int prev , int n , int k ) { if ( len == k ) return 0 ; if ( i == n ) return INT_MIN ; if ( dp [ i ] [ len ] [ prev ] ) return dp [ i ] [ len ] [ prev ] ; int inc = 0 , exc = 0 ; if ( len & 1 ) { inc = productDigitSum ( arr [ prev ] , arr [ i ] ) + solve ( arr , i + 1 , len + 1 , 0 , n , k ) ; } else { inc = solve ( arr , i + 1 , len + 1 , i , n , k ) ; } exc = solve ( arr , i + 1 , len , prev , n , k ) ; return dp [ i ] [ len ] [ prev ] = max ( inc , exc ) ; } int main ( ) { int arr [ ] = { 10 , 5 , 9 , 101 , 24 , 2 , 20 , 14 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 6 ; cout << solve ( arr , 0 , 0 , 0 , n , k ) ; } |
Count minimum factor jumps required to reach the end of an Array | C ++ code to count minimum factor jumps to reach the end of array ; vector to store factors of each integer ; dp array ; Precomputing all factors of integers from 1 to 100000 ; Function to count the minimum jumps ; If we reach the end of array , no more jumps are required ; If the jump results in out of index , return INT_MAX ; If the answer has been already computed , return it directly ; Else compute the answer using the recurrence relation ; Iterating over all choices of jumps ; Considering current factor as a jump ; Jump leads to the destination ; Return ans and memorize it ; Driver code ; pre - calculating the factors | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > factors [ 100005 ] ; int dp [ 100005 ] ; void precompute ( ) { for ( int i = 1 ; i <= 100000 ; i ++ ) { for ( int j = i ; j <= 100000 ; j += i ) { factors [ j ] . push_back ( i ) ; } } } int solve ( int arr [ ] , int k , int n ) { if ( k == n - 1 ) { return 0 ; } if ( k >= n ) { return INT_MAX ; } if ( dp [ k ] ) { return dp [ k ] ; } int ans = INT_MAX ; for ( auto j : factors [ arr [ k ] ] ) { int res = solve ( arr , k + j , n ) ; if ( res != INT_MAX ) { ans = min ( ans , res + 1 ) ; } } return dp [ k ] = ans ; } int main ( ) { precompute ( ) ; int arr [ ] = { 2 , 8 , 16 , 55 , 99 , 100 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << solve ( arr , 0 , n ) ; } |
Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | C ++ Program to find the maximum distance from a 0 - cell to a 1 - cell ; If the matrix consists of only 0 ' s β β or β only β 1' s ; If it 's a 0-cell ; calculate its distance with every 1 - cell ; Compare and store the minimum ; Compare ans store the maximum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDistance ( vector < vector < int > > & grid ) { vector < pair < int , int > > one ; int M = grid . size ( ) ; int N = grid [ 0 ] . size ( ) ; int ans = -1 ; for ( int i = 0 ; i < M ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { if ( grid [ i ] [ j ] == 1 ) one . emplace_back ( i , j ) ; } } if ( one . empty ( ) || M * N == one . size ( ) ) return -1 ; for ( int i = 0 ; i < M ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { if ( grid [ i ] [ j ] == 1 ) continue ; int dist = INT_MAX ; for ( auto & p : one ) { int d = abs ( p . first - i ) + abs ( p . second - j ) ; dist = min ( dist , d ) ; if ( dist <= ans ) break ; } ans = max ( ans , dist ) ; } } return ans ; } int main ( ) { vector < vector < int > > arr = { { 0 , 0 , 1 } , { 0 , 0 , 0 } , { 0 , 0 , 0 } } ; cout << maxDistance ( arr ) << endl ; return 0 ; } |
Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | C ++ Program to find the maximum distance from a 0 - cell to a 1 - cell ; Function to find the maximum distance ; Queue to store all 1 - cells ; Grid dimensions ; Directions traversable from a given a particular cell ; If the grid contains only 0 s or only 1 s ; Access every 1 - cell ; Traverse all possible directions from the cells ; Check if the cell is within the boundaries or contains a 1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDistance ( vector < vector < int > > & grid ) { queue < pair < int , int > > q ; int M = grid . size ( ) ; int N = grid [ 0 ] . size ( ) ; int ans = -1 ; int dirs [ 4 ] [ 2 ] = { { 0 , 1 } , { 1 , 0 } , { 0 , -1 } , { -1 , 0 } } ; for ( int i = 0 ; i < M ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { if ( grid [ i ] [ j ] == 1 ) q . emplace ( i , j ) ; } } if ( q . empty ( ) || M * N == q . size ( ) ) return -1 ; while ( q . size ( ) ) { int cnt = q . size ( ) ; while ( cnt -- ) { auto p = q . front ( ) ; q . pop ( ) ; for ( auto & dir : dirs ) { int x = p . first + dir [ 0 ] ; int y = p . second + dir [ 1 ] ; if ( x < 0 x > = M y < 0 y > = N grid [ x ] [ y ] ) continue ; q . emplace ( x , y ) ; grid [ x ] [ y ] = 1 ; } } ++ ans ; } return ans ; } int main ( ) { vector < vector < int > > arr = { { 0 , 0 , 1 } , { 0 , 0 , 0 } , { 0 , 0 , 1 } } ; cout << maxDistance ( arr ) << endl ; return 0 ; } |
Count the number of ways to give ranks for N students such that same ranks are possible | C ++ program to calculate the number of ways to give ranks for N students such that same ranks are possible ; Initializing a table in order to store the bell triangle ; Function to calculate the K - th bell number ; If we have already calculated the bell numbers until the required N ; Base case ; First Bell Number ; If the value of the bell triangle has already been calculated ; Fill the defined dp table ; Function to return the number of ways to give ranks for N students such that same ranks are possible ; Resizing the dp table for the given value of n ; Variables to store the answer and the factorial value ; Iterating till N ; Simultaneously calculate the k ! ; Computing the K - th bell number and multiplying it with K ! ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1e9 + 7 ; vector < vector < int > > dp ; int f ( int n , int k ) { if ( n < k ) return 0 ; if ( n == k ) return 1 ; if ( k == 1 ) return 1 ; if ( dp [ n ] [ k ] != -1 ) return dp [ n ] [ k ] ; return dp [ n ] [ k ] = ( ( k * f ( n - 1 , k ) ) % mod + ( f ( n - 1 , k - 1 ) ) % mod ) % mod ; } long operation ( int n ) { dp . resize ( n + 1 , vector < int > ( n + 1 , -1 ) ) ; long ans = 0 , fac = 1 ; for ( int k = 1 ; k <= n ; k ++ ) { fac *= k ; ans = ( ans + ( fac * f ( n , k ) ) % mod ) % mod ; } return ans ; } int main ( ) { int n = 5 ; cout << operation ( n ) << endl ; return 0 ; } |
Print all Longest dividing subsequence in an Array | C ++ program for the above approach ; Function to print LDS [ i ] element ; Traverse the Max [ ] ; Function to construct and print Longest Dividing Subsequence ; 2D vector for storing sequences ; Push the first element to LDS [ ] [ ] ; Iterate over all element ; Loop for every index till i ; if current elements divides arr [ i ] and length is greater than the previous index , then insert the current element to the sequences LDS [ i ] ; L [ i ] ends with arr [ i ] ; LDS stores the sequences till each element of arr [ ] Traverse the LDS [ ] [ ] to find the the maximum length ; Print all LDS with maximum length ; Find size ; If size = maxLength ; Print LDS ; Driver Code ; Function Call | #include " bits / stdc + + . h " NEW_LINE using namespace std ; void printLDS ( vector < int > & Max ) { for ( auto & it : Max ) { cout << it << ' β ' ; } } void LongestDividingSeq ( int arr [ ] , int N ) { vector < vector < int > > LDS ( N ) ; LDS [ 0 ] . push_back ( arr [ 0 ] ) ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( ( arr [ i ] % arr [ j ] == 0 ) && ( LDS [ i ] . size ( ) < LDS [ j ] . size ( ) + 1 ) ) LDS [ i ] = LDS [ j ] ; } LDS [ i ] . push_back ( arr [ i ] ) ; } int maxLength = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int x = LDS [ i ] . size ( ) ; maxLength = max ( maxLength , x ) ; } for ( int i = 0 ; i < N ; i ++ ) { int size = LDS [ i ] . size ( ) ; if ( size == maxLength ) { printLDS ( LDS [ i ] ) ; cout << ' ' ; } } } int main ( ) { int arr [ ] = { 2 , 11 , 16 , 12 , 36 , 60 , 71 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; LongestDividingSeq ( arr , N ) ; return 0 ; } |
Count the number of ordered sets not containing consecutive numbers | C ++ program to Count the number of ordered sets not containing consecutive numbers ; Function to calculate the count of ordered set for a given size ; Base cases ; Function returns the count of all ordered sets ; Prestore the factorial value ; Iterate all ordered set sizes and find the count for each one maximum ordered set size will be smaller than N as all elements are distinct and non consecutive ; Multiply ny size ! for all the arrangements because sets are ordered ; Add to total answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountSets ( int x , int pos ) { if ( x <= 0 ) { if ( pos == 0 ) return 1 ; else return 0 ; } if ( pos == 0 ) return 1 ; int answer = CountSets ( x - 1 , pos ) + CountSets ( x - 2 , pos - 1 ) ; return answer ; } int CountOrderedSets ( int n ) { int factorial [ 10000 ] ; factorial [ 0 ] = 1 ; for ( int i = 1 ; i < 10000 ; i ++ ) factorial [ i ] = factorial [ i - 1 ] * i ; int answer = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int sets = CountSets ( n , i ) * factorial [ i ] ; answer = answer + sets ; } return answer ; } int main ( ) { int N = 3 ; cout << CountOrderedSets ( N ) ; return 0 ; } |
Maximum sum such that exactly half of the elements are selected and no two adjacent | C ++ program to find maximum sum possible such that exactly floor ( N / 2 ) elements are selected and no two selected elements are adjacent to each other ; Function return the maximum sum possible under given condition ; Intitialising the dp table ; Base case ; Condition to select the current element ; Condition to not select the current element if possible ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaximumSum ( int a [ ] , int n ) { int dp [ n + 1 ] [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) { for ( int j = 0 ; j < n + 1 ; j ++ ) dp [ i ] [ j ] = INT_MIN ; } for ( int i = 0 ; i < n + 1 ; i ++ ) dp [ i ] [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= i ; j ++ ) { int val = INT_MIN ; if ( ( i - 2 >= 0 && dp [ i - 2 ] [ j - 1 ] != INT_MIN ) i - 2 < 0 ) { val = a [ i - 1 ] + ( i - 2 >= 0 ? dp [ i - 2 ] [ j - 1 ] : 0 ) ; } if ( i - 1 >= j ) { val = max ( val , dp [ i - 1 ] [ j ] ) ; } dp [ i ] [ j ] = val ; } } return dp [ n ] [ n / 2 ] ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << MaximumSum ( A , N ) ; return 0 ; } |
Check if N can be converted to the form K power K by the given operation | C ++ implementation to Check whether a given number N can be converted to the form K power K by the given operation ; Function to check if N can be converted to K power K ; Check if n is of the form k ^ k ; Iterate through each digit of n ; Check if it is possible to obtain number of given form ; Reduce the number each time ; Return the result ; Function to check the above method ; Check if conversion if possible ; Driver code ; Pre store K power K form of numbers Loop till 8 , because 8 ^ 8 > 10 ^ 7 | #include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_set < int > kPowKform ; int func ( int n ) { if ( n <= 0 ) return 0 ; if ( kPowKform . count ( n ) ) return 1 ; int answer = 0 ; int x = n ; while ( x > 0 ) { int d = x % 10 ; if ( d != 0 ) { if ( func ( n - d * d ) ) { answer = 1 ; break ; } } x /= 10 ; } return answer ; } void canBeConverted ( int n ) { if ( func ( n ) ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int N = 90 ; for ( int i = 1 ; i <= 8 ; i ++ ) { int val = 1 ; for ( int j = 1 ; j <= i ; j ++ ) val *= i ; kPowKform . insert ( val ) ; } canBeConverted ( N ) ; return 0 ; } |
Count of subarrays of an Array having all unique digits | C ++ program to find the count of subarrays of an Array having all unique digits ; Function to check whether the subarray has all unique digits ; Storing all digits occurred ; Traversing all the numbers of v ; Storing all digits of v [ i ] ; Checking whether digits of v [ i ] have already occurred ; Inserting digits of v [ i ] in the set ; Function to count the number subarray with all digits unique ; Traverse through all the subarrays ; To store elements of this subarray ; Generate all subarray and store it in vector ; Check whether this subarray has all digits unique ; Increase the count ; Return the count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( vector < int > & v ) { set < int > digits ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { set < int > d ; while ( v [ i ] ) { d . insert ( v [ i ] % 10 ) ; v [ i ] /= 10 ; } for ( auto it : d ) { if ( digits . count ( it ) ) return false ; } for ( auto it : d ) digits . insert ( it ) ; } return true ; } int numberOfSubarrays ( int a [ ] , int n ) { int answer = 0 ; for ( int i = 1 ; i < ( 1 << n ) ; i ++ ) { vector < int > temp ; for ( int j = 0 ; j < n ; j ++ ) { if ( i & ( 1 << j ) ) temp . push_back ( a [ j ] ) ; } if ( check ( temp ) ) answer ++ ; } return answer ; } int main ( ) { int N = 4 ; int A [ ] = { 1 , 12 , 23 , 34 } ; cout << numberOfSubarrays ( A , N ) ; return 0 ; } |
Minimum labelled node to be removed from undirected Graph such that there is no cycle | C ++ implementation to find the minimum labelled node to be removed such that there is no cycle in the undirected graph ; Variables to store if a node V has at - most one back edge and store the depth of the node for the edge ; Function to swap the pairs of the graph ; If the second value is greater than x ; Put the pair in the ascending order internally ; Function to perform the DFS ; Initialise with the large value ; Storing the depth of this vertex ; Mark the vertex as visited ; Iterating through the graph ; If the node is a child node ; If the child node is unvisited ; Move to the child and increase the depth ; increase according to algorithm ; If the node is not having exactly K backedges ; If the child is already visited and in current dfs ( because colour is 1 ) then this is a back edge ; Increase the countAdj values ; Colour this vertex 2 as we are exiting out of dfs for this node ; Function to find the minimum labelled node to be removed such that there is no cycle in the undirected graph ; Construct the graph ; Mark visited as false for each node ; Apply dfs on all unmarked nodes ; If no backedges in the initial graph this means that there is no cycle So , return - 1 ; Iterate through the vertices and return the first node that satisfies the condition ; Check whether the count sum of small [ v ] and count is the same as the total back edges and if the vertex v can be removed ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100005 ; int totBackEdges ; int countAdj [ MAX ] , small [ MAX ] ; int isPossible [ MAX ] , depth [ MAX ] ; vector < int > adj [ MAX ] ; int vis [ MAX ] ; void change ( pair < int , int > & p , int x ) { if ( p . second > x ) p . second = x ; if ( p . first > p . second ) swap ( p . first , p . second ) ; } pair < int , int > dfs ( int v , int p = -1 , int de = 0 ) { pair < int , int > answer ( 100000000 , 100000000 ) ; depth [ v ] = de ; vis [ v ] = 1 ; isPossible [ v ] = 1 ; for ( int u : adj [ v ] ) { if ( u ^ p ) { if ( ! vis [ u ] ) { auto x = dfs ( u , v , de + 1 ) ; small [ v ] += small [ u ] ; change ( answer , x . second ) ; change ( answer , x . first ) ; if ( x . second < de ) isPossible [ v ] = 0 ; } else if ( vis [ u ] == 1 ) { totBackEdges ++ ; countAdj [ v ] ++ ; countAdj [ u ] ++ ; small [ p ] ++ ; small [ u ] -- ; change ( answer , depth [ u ] ) ; } } } vis [ v ] = 2 ; return answer ; } int minNodetoRemove ( int n , vector < pair < int , int > > edges ) { for ( int i = 0 ; i < edges . size ( ) ; i ++ ) { adj [ edges [ i ] . first ] . push_back ( edges [ i ] . second ) ; adj [ edges [ i ] . second ] . push_back ( edges [ i ] . first ) ; } memset ( vis , 0 , sizeof ( vis ) ) ; totBackEdges = 0 ; for ( int v = 1 ; v <= n ; v ++ ) { if ( ! vis [ v ] ) dfs ( v ) ; } if ( totBackEdges == 0 ) return -1 ; int node = -1 ; for ( int v = 1 ; v <= n ; v ++ ) { if ( countAdj [ v ] + small [ v ] == totBackEdges && isPossible [ v ] ) { node = v ; } if ( node != -1 ) break ; } return node ; } int main ( ) { int N = 5 ; vector < pair < int , int > > edges ; edges . push_back ( make_pair ( 5 , 1 ) ) ; edges . push_back ( make_pair ( 5 , 2 ) ) ; edges . push_back ( make_pair ( 1 , 2 ) ) ; edges . push_back ( make_pair ( 2 , 3 ) ) ; edges . push_back ( make_pair ( 2 , 4 ) ) ; cout << minNodetoRemove ( N , edges ) ; } |
Find the row whose product has maximum count of prime factors | C ++ implementation to find the row whose product has maximum number of prime factors ; function for SieveOfEratosthenes ; Create a boolean array " isPrime [ 0 . . N ] " and initialize all entries it as true . A value in isPrime [ i ] will finally be false if i is not a prime , else true . ; check if isPrime [ p ] is not changed ; Update all multiples of p ; Print all isPrime numbers ; function to display the answer ; function to Count the row number of divisors in particular row multiplication ; Find count of occurrences of each prime factor ; Compute count of all divisors ; Update row number if factors of this row is max ; Clearing map to store prime factors for next row ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 3 NEW_LINE #define M 5 NEW_LINE int Large = 1e6 ; vector < int > prime ; void SieveOfEratosthenes ( ) { bool isPrime [ Large + 1 ] ; memset ( isPrime , true , sizeof ( isPrime ) ) ; for ( int p = 2 ; p * p <= Large ; p ++ ) { if ( isPrime [ p ] == true ) { for ( int i = p * 2 ; i <= Large ; i += p ) isPrime [ i ] = false ; } } for ( int p = 2 ; p <= Large ; p ++ ) if ( isPrime [ p ] ) prime . push_back ( p ) ; } void Display ( int arr [ ] [ M ] , int row ) { for ( int i = 0 ; i < M ; i ++ ) cout << arr [ row ] [ i ] << " β " ; } void countDivisorsMult ( int arr [ ] [ M ] ) { unordered_map < int , int > mp ; int row_no = 0 ; long long max_factor = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { int no = arr [ i ] [ j ] ; for ( int k = 0 ; k < prime . size ( ) ; k ++ ) { while ( no > 1 && no % prime [ k ] == 0 ) { no /= prime [ k ] ; mp [ prime [ k ] ] ++ ; } if ( no == 1 ) break ; } } long long int res = 1 ; for ( auto it : mp ) { res *= ( it . second + 1L ) ; } if ( max_factor < res ) { row_no = i ; max_factor = res ; } mp . clear ( ) ; } Display ( arr , row_no ) ; } int main ( ) { int arr [ N ] [ M ] = { { 1 , 2 , 3 , 10 , 23 } , { 4 , 5 , 6 , 7 , 8 } , { 7 , 8 , 9 , 15 , 45 } } ; SieveOfEratosthenes ( ) ; countDivisorsMult ( arr ) ; return 0 ; } |
Smallest N digit number whose sum of square of digits is a Perfect Square | C ++ implementation to find Smallest N digit number whose sum of square of digits is a Perfect Square ; function to check if number is a perfect square ; function to calculate the smallest N digit number ; place digits greater than equal to prev ; check if placing this digit leads to a solution then return it ; else backtrack ; create a string representing the N digit number ; driver code ; initialise N | #include <bits/stdc++.h> NEW_LINE using namespace std ; int isSquare ( int n ) { int k = sqrt ( n ) ; return ( k * k == n ) ; } int calculate ( int pos , int prev , int sum , vector < int > & v ) { if ( pos == v . size ( ) ) return isSquare ( sum ) ; for ( int i = prev ; i <= 9 ; i ++ ) { v [ pos ] = i ; sum += i * i ; if ( calculate ( pos + 1 , i , sum , v ) ) return 1 ; sum -= i * i ; } return 0 ; } string minValue ( int n ) { vector < int > v ( n ) ; if ( calculate ( 0 , 1 , 0 , v ) ) { string answer = " " ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) answer += char ( v [ i ] + '0' ) ; return answer ; } else return " - 1" ; } int main ( ) { int N = 2 ; cout << minValue ( N ) ; return 0 ; } |
Sum of GCD of all possible sequences | C ++ implementation of the above approach ; A recursive function that generates all the sequence and find GCD ; If we reach the sequence of length N g is the GCD of the sequence ; Initialise answer to 0 ; Placing all possible values at this position and recursively find the GCD of the sequence ; Take GCD of GCD calculated uptill now i . e . g with current element ; Take modulo to avoid overflow ; Return the final answer ; Function that finds the sum of GCD of all the subsequence of N length ; Recursive function that generates the sequence and return the GCD ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = ( int ) 1e9 + 7 ; int calculate ( int pos , int g , int n , int k ) { if ( pos == n ) { return g ; } int answer = 0 ; for ( int i = 1 ; i <= k ; i ++ ) { answer = ( answer % MOD + calculate ( pos + 1 , __gcd ( g , i ) , n , k ) % MOD ) ; answer %= MOD ; } return answer ; } int sumofGCD ( int n , int k ) { return calculate ( 0 , 0 , n , k ) ; } int main ( ) { int N = 3 , K = 2 ; cout << sumofGCD ( N , K ) ; return 0 ; } |
Sum of GCD of all possible sequences | C ++ implementation of the above approach ; Function to find a ^ b in log ( b ) ; Function that finds the sum of GCD of all the subsequence of N length ; To stores the number of sequences with gcd i ; Find contribution of each gcd to happen ; To count multiples ; possible sequences with overcounting ; to avoid overflow ; Find extra element which will not form gcd = i ; Find overcounting ; Remove the overcounting ; To store the final answer ; Return Final answer ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = ( int ) 1e9 + 7 ; int fastexpo ( int a , int b ) { int res = 1 ; a %= MOD ; while ( b ) { if ( b & 1 ) res = ( res * a ) % MOD ; a *= a ; a %= MOD ; b >>= 1 ; } return res ; } int sumofGCD ( int n , int k ) { int count [ k + 1 ] = { 0 } ; for ( int g = k ; g >= 1 ; g -- ) { int count_multiples = k / g ; int temp ; temp = fastexpo ( count_multiples , n ) ; temp %= MOD ; int extra = 0 ; for ( int j = g * 2 ; j <= k ; j += g ) { extra = ( extra + count [ j ] ) ; extra %= MOD ; } count [ g ] = ( temp - extra + MOD ) ; count [ g ] %= MOD ; } int sum = 0 ; int add ; for ( int i = 1 ; i <= k ; ++ i ) { add = ( count [ i ] % MOD * i % MOD ) ; add %= MOD ; sum += add ; sum %= MOD ; } return sum ; } int main ( ) { int N = 3 , K = 2 ; cout << sumofGCD ( N , K ) ; return 0 ; } |
Split the given string into Odds : Digit DP | C ++ program to split the given string into odds ; Function to check whether a string is an odd number or not ; A function to find the minimum number of segments the given string can be divided such that every segment is a odd number ; Declare a splitdp [ ] array and initialize to - 1 ; Build the DP table in a bottom - up manner ; Initially Check if the entire prefix is odd ; If the Given Prefix can be split into Odds then for the remaining string from i to j Check if Odd . If yes calculate the minimum split till j ; To check if the substring from i to j is a odd number or not ; If it is an odd number , then update the dp array ; Return the minimum number of splits for the entire string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkOdd ( string number ) { int n = number . length ( ) ; int num = number [ n - 1 ] - '0' ; return ( num & 1 ) ; } int splitIntoOdds ( string number ) { int numLen = number . length ( ) ; int splitDP [ numLen + 1 ] ; memset ( splitDP , -1 , sizeof ( splitDP ) ) ; for ( int i = 1 ; i <= numLen ; i ++ ) { if ( i <= 9 && checkOdd ( number . substr ( 0 , i ) ) ) splitDP [ i ] = 1 ; if ( splitDP [ i ] != -1 ) { for ( int j = 1 ; j <= 9 && i + j <= numLen ; j ++ ) { if ( checkOdd ( number . substr ( i , j ) ) ) { if ( splitDP [ i + j ] == -1 ) splitDP [ i + j ] = 1 + splitDP [ i ] ; else splitDP [ i + j ] = min ( splitDP [ i + j ] , 1 + splitDP [ i ] ) ; } } } } return splitDP [ numLen ] ; } int main ( ) { cout << splitIntoOdds ( "123456789123456789123" ) << " STRNEWLINE " ; return 0 ; } |
Count of numbers in range which are divisible by M and have digit D at odd places | C ++ program to find the count of numbers in the range [ L , R ] which are divisible by M and have digit D at the odd places ; Variables to store M , N , D ; Vector to store the digit number in the form of digits ; Dp table to compute the answer ; Function to add the individual digits into the vector ; Iterating through the number and adding the digits into the vector ; Function to subtract 1 from a number represented in a form of a string ; Iterating through the number ; If the first digit is 1 , then make it 0 and add 9 at the end of the string . ; If we need to subtract 1 from 0 , then make it 9 and subtract 1 from the previous digits ; Else , simply subtract 1 ; Function to find the count of numbers in the range [ L , R ] which are divisible by M and have digit D at the odd places ; Base case ; If we have built N - digit number and the number is divisible by m then we have got one possible answer . ; If the answer has already been computed , then return the answer ; The possible digits which we can place at the pos position . ; Iterating through all the digits ; If we have placed all the digits up to pos - 1 equal to their limit and currently we are placing a digit which is smaller than this position 's limit then we can place 0 to 9 at all the next positions to make the number smaller than R ; Calculating the number upto pos mod m . ; Combinations of numbers as there are 10 digits in the range [ 0 , 9 ] ; Recursively call the function for the next position ; Returning the final answer ; Function to call the function for every query ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll m , n , d ; vector < int > v ; ll const k = 1e9 + 7 ; ll dp [ 2001 ] [ 2001 ] [ 2 ] ; void init ( string s ) { memset ( dp , -1 , sizeof ( dp ) ) ; v . clear ( ) ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { v . push_back ( s [ i ] - '0' ) ; } n = s . size ( ) ; } string number_minus_one ( string a ) { string s = a . substr ( 1 ) ; string s1 = " " ; for ( int i = 0 ; i < s . size ( ) - 1 ; i ++ ) s1 += '0' ; if ( a [ 0 ] == 1 and s == s1 ) { ll l = s . size ( ) ; a = " " ; a += '0' ; for ( int i = 0 ; i < l ; i ++ ) a += '9' ; } else { for ( int i = a . size ( ) - 1 ; i >= 0 ; i -- ) { if ( a [ i ] == '0' ) a [ i ] = '9' ; else { a [ i ] = ( ( ( a [ i ] - '0' ) - 1 ) + '0' ) ; break ; } } } return a ; } ll fun ( ll pos , ll sum , ll f ) { if ( pos == n ) { if ( sum == 0 ) { return 1 ; } return 0 ; } if ( dp [ pos ] [ sum ] [ f ] != -1 ) return dp [ pos ] [ sum ] [ f ] ; ll lmt = 9 ; if ( ! f ) lmt = v [ pos ] ; ll ans = 0 ; for ( ll i = 0 ; i <= lmt ; i ++ ) { if ( i == d and pos % 2 == 1 ) ans += 0 ; else if ( i != d and pos % 2 == 0 ) ans += 0 ; else { ll new_f = f ; if ( f == 0 and i < lmt ) new_f = 1 ; ll new_sum = sum ; new_sum *= 10 ; new_sum += i ; new_sum %= m ; ans += fun ( pos + 1 , new_sum , new_f ) ; ans %= k ; } } return dp [ pos ] [ sum ] [ f ] = ans ; } void operations ( string L , string R ) { init ( R ) ; ll ans = fun ( 0 , 0 , 0 ) ; L = number_minus_one ( L ) ; init ( L ) ; ans -= fun ( 0 , 0 , 0 ) ; if ( ans < 0 ) ans += k ; cout << ans << " STRNEWLINE " ; } int main ( ) { m = 2 , d = 2 ; ll Q = 1 ; string arr [ ] [ 2 ] = { { "20" , "32" } } ; for ( ll i = 0 ; i < Q ; i ++ ) { operations ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) ; } return 0 ; } |
Split the given string into Primes : Digit DP | C ++ implementation of the above approach ; Function to check whether a string is a prime number or not ; A recursive function to find the minimum number of segments the given string can be divided such that every segment is a prime ; If the number is null ; checkPrime function is called to check if the number is a prime or not . ; A very large number denoting maximum ; Consider a minimum of 6 and length since the primes are less than 10 ^ 6 ; Recursively call the function to check for the remaining string ; Evaluating minimum splits into Primes for the suffix ; Checks if no combination found ; Driver code | #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; bool checkPrime ( string number ) { int num = stoi ( number ) ; for ( int i = 2 ; i * i <= num ; i ++ ) if ( ( num % i ) == 0 ) return false ; return true ; } int splitIntoPrimes ( string number ) { if ( number . length ( ) == 0 ) return 0 ; if ( number . length ( ) <= 6 and checkPrime ( number ) ) return 1 ; else { int numLen = number . length ( ) ; int ans = 1000000 ; for ( int i = 1 ; i <= 6 && i <= numLen ; i ++ ) { if ( checkPrime ( number . substr ( 0 , i ) ) ) { int val = splitIntoPrimes ( number . substr ( i ) ) ; if ( val != -1 ) { ans = min ( ans , 1 + val ) ; } } } if ( ans == 1000000 ) return -1 ; return ans ; } } int main ( ) { cout << splitIntoPrimes ( "13499315" ) << " STRNEWLINE " ; cout << splitIntoPrimes ( "43" ) << " STRNEWLINE " ; return 0 ; } |
Find the numbers from 1 to N that contains exactly k non | C ++ implementation of the above approach ; Function to find number less than N having k non - zero digits ; Store the memorised values ; Initialise ; Base ; Calculate all states For every state , from numbers 1 to N , the count of numbers which contain exactly j non zero digits is being computed and updated in the dp array . ; Return the required answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int k_nonzero_numbers ( string s , int n , int k ) { int dp [ n + 1 ] [ 2 ] [ k + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j < 2 ; j ++ ) for ( int x = 0 ; x <= k ; x ++ ) dp [ i ] [ j ] [ x ] = 0 ; dp [ 0 ] [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i < n ; ++ i ) { int sm = 0 ; while ( sm < 2 ) { for ( int j = 0 ; j < k + 1 ; ++ j ) { int x = 0 ; while ( x <= ( sm ? 9 : s [ i ] - '0' ) ) { dp [ i + 1 ] [ sm || x < ( s [ i ] - '0' ) ] [ j + ( x > 0 ) ] += dp [ i ] [ sm ] [ j ] ; ++ x ; } } ++ sm ; } } return dp [ n ] [ 0 ] [ k ] + dp [ n ] [ 1 ] [ k ] ; } int main ( ) { string s = "25" ; int k = 2 ; int n = s . size ( ) ; cout << k_nonzero_numbers ( s , n , k ) ; return 0 ; } |
Count maximum occurrence of subsequence in string such that indices in subsequence is in A . P . | C ++ implementation to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Function to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Frequencies of subsequence ; Loop to find the frequencies of subsequence of length 1 ; Loop to find the frequencies subsequence of length 2 ; Finding maximum frequency ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumOccurrence ( string s ) { int n = s . length ( ) ; map < string , int > freq ; for ( int i = 0 ; i < n ; i ++ ) { string temp = " " ; temp += s [ i ] ; freq [ temp ] ++ ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { string temp = " " ; temp += s [ i ] ; temp += s [ j ] ; freq [ temp ] ++ ; } } int answer = INT_MIN ; for ( auto it : freq ) answer = max ( answer , it . second ) ; return answer ; } int main ( ) { string s = " xxxyy " ; cout << maximumOccurrence ( s ) ; return 0 ; } |
Count ways to partition a string such that both parts have equal distinct characters | C ++ implementation to count the number of ways to partition the string such that each partition have same number of distinct characters in the string ; Function to count the distinct characters in the string ; Frequency of each character ; Loop to count the frequency of each character of the string ; If frequency is greater than 0 then the character occured ; Function to count the number of ways to partition the string such that each partition have same number of distinct character ; Loop to choose the partition index for the string ; Divide in two parts ; Check whether number of distinct characters are equal ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctChars ( string s ) { int freq [ 26 ] = { 0 } ; int count = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) freq [ s [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] > 0 ) count ++ ; } return count ; } int waysToSplit ( string s ) { int n = s . length ( ) ; int answer = 0 ; for ( int i = 1 ; i < n ; i ++ ) { string left = s . substr ( 0 , i ) ; string right = s . substr ( i , n - i ) ; if ( distinctChars ( left ) == distinctChars ( right ) ) answer ++ ; } return answer ; } int main ( ) { string s = " ababa " ; cout << waysToSplit ( s ) ; return 0 ; } |
Count ways to partition a string such that both parts have equal distinct characters | C ++ implementation to count the number of ways to partition the string such that each partition have same number of distinct characters in the string ; Function to count the number of ways to partition the string such that each partition have same number of distinct character ; Prefix and suffix array for distinct character from start and end ; To check whether a character has appeared till ith index ; Calculating prefix array ; Character appears for the first time in string ; Character is visited ; Resetting seen for suffix calculation ; Calculating the suffix array ; Character appears for the first time ; This character has now appeared ; Loop to calculate the number partition points in the string ; Check whether number of distinct characters are equal ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int waysToSplit ( string s ) { int n = s . length ( ) ; int answer = 0 ; int prefix [ n ] = { 0 } ; int suffix [ n ] = { 0 } ; int seen [ 26 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int prev = ( i - 1 >= 0 ? prefix [ i - 1 ] : 0 ) ; if ( seen [ s [ i ] - ' a ' ] == 0 ) { prefix [ i ] += ( prev + 1 ) ; } else prefix [ i ] = prev ; seen [ s [ i ] - ' a ' ] = 1 ; } memset ( seen , 0 , sizeof ( seen ) ) ; suffix [ n - 1 ] = 0 ; for ( int i = n - 1 ; i >= 1 ; i -- ) { int prev = suffix [ i ] ; if ( seen [ s [ i ] - ' a ' ] == 0 ) { suffix [ i - 1 ] += ( prev + 1 ) ; } else suffix [ i - 1 ] = prev ; seen [ s [ i ] - ' a ' ] = 1 ; } for ( int i = 0 ; i < n ; i ++ ) { if ( prefix [ i ] == suffix [ i ] ) answer ++ ; } return answer ; } int main ( ) { string s = " ababa " ; cout << waysToSplit ( s ) ; return 0 ; } |
Counts paths from a point to reach Origin : Memory Optimized | C ++ implementation to count the paths from a points to origin ; Function to count the paths from a point to the origin ; Base Case when the point is already at origin ; Base Case when the point is on the x or y - axis ; Loop to fill all the position as 1 in the array ; Loop to count the number of paths from a point to origin in bottom - up manner ; Driver Code ; Function Call | #include <iostream> NEW_LINE #include <cstring> NEW_LINE using namespace std ; long Count_Paths ( int x , int y ) { if ( x == 0 && y == 0 ) return 0 ; if ( x == 0 y == 0 ) return 1 ; long dp [ max ( x , y ) + 1 ] , p = max ( x , y ) , q = min ( x , y ) ; for ( int i = 0 ; i <= p ; i ++ ) dp [ i ] = 1 ; for ( int i = 1 ; i <= q ; i ++ ) for ( int j = 1 ; j <= p ; j ++ ) dp [ j ] += dp [ j - 1 ] ; return dp [ p ] ; } int main ( ) { int x = 3 , y = 3 ; cout << " Number β of β Paths β " << Count_Paths ( x , y ) ; return 0 ; } |
Find the numbers present at Kth level of a Fibonacci Binary Tree | C ++ program to print the Fibonacci numbers present at K - th level of a Binary Tree ; Initializing the max value ; Array to store all the fibonacci numbers ; Function to generate fibonacci numbers using Dynamic Programming ; 0 th and 1 st number of the series are 0 and 1 ; Add the previous two numbers in the series and store it ; Function to print the Fibonacci numbers present at Kth level of a Binary Tree ; Finding the left and right index ; Iterating and printing the numbers ; Driver code ; Precomputing Fibonacci numbers | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_SIZE 100005 NEW_LINE int fib [ MAX_SIZE + 1 ] ; void fibonacci ( ) { int i ; fib [ 0 ] = 0 ; fib [ 1 ] = 1 ; for ( i = 2 ; i <= MAX_SIZE ; i ++ ) { fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] ; } } void printLevel ( int level ) { int left_index = pow ( 2 , level - 1 ) ; int right_index = pow ( 2 , level ) - 1 ; for ( int i = left_index ; i <= right_index ; i ++ ) { cout << fib [ i - 1 ] << " β " ; } cout << endl ; } int main ( ) { fibonacci ( ) ; int K = 4 ; printLevel ( K ) ; return 0 ; } |
Count the number of ways to divide N in k groups incrementally | C ++ implementation to count the number of ways to divide N in groups such that each group has K number of elements ; Function to count the number of ways to divide the number N in groups such that each group has K number of elements ; Base Case ; if N is divides completely into less than k groups ; put all possible values greater equal to prev ; Function to count the number of ways to divide the number N ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate ( int pos , int prev , int left , int k ) { if ( pos == k ) { if ( left == 0 ) return 1 ; else return 0 ; } if ( left == 0 ) return 0 ; int answer = 0 ; for ( int i = prev ; i <= left ; i ++ ) { answer += calculate ( pos + 1 , i , left - i , k ) ; } return answer ; } int countWaystoDivide ( int n , int k ) { return calculate ( 0 , 1 , n , k ) ; } int main ( ) { int N = 8 ; int K = 4 ; cout << countWaystoDivide ( N , K ) ; return 0 ; } |
Count the number of ways to divide N in k groups incrementally | C ++ implementation to count the number of ways to divide N in groups such that each group has K number of elements ; DP Table ; Function to count the number of ways to divide the number N in groups such that each group has K number of elements ; Base Case ; if N is divides completely into less than k groups ; If the subproblem has been solved , use the value ; put all possible values greater equal to prev ; Function to count the number of ways to divide the number N in groups ; Initialize DP Table as - 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 500 ] [ 500 ] [ 500 ] ; int calculate ( int pos , int prev , int left , int k ) { if ( pos == k ) { if ( left == 0 ) return 1 ; else return 0 ; } if ( left == 0 ) return 0 ; if ( dp [ pos ] [ prev ] [ left ] != -1 ) return dp [ pos ] [ prev ] [ left ] ; int answer = 0 ; for ( int i = prev ; i <= left ; i ++ ) { answer += calculate ( pos + 1 , i , left - i , k ) ; } return dp [ pos ] [ prev ] [ left ] = answer ; } int countWaystoDivide ( int n , int k ) { memset ( dp , -1 , sizeof ( dp ) ) ; return calculate ( 0 , 1 , n , k ) ; } int main ( ) { int N = 8 ; int K = 4 ; cout << countWaystoDivide ( N , K ) ; return 0 ; } |
Maximum score possible after performing given operations on an Array | C ++ program to find the maximum score after given operations ; Function to calculate maximum score recursively ; Base case ; Sum of array in range ( l , r ) ; If the operation is even - numbered the score is decremented ; Exploring all paths , by removing leftmost and rightmost element and selecting the maximum value ; Function to find the max score ; Prefix sum array ; Calculating prefix_sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxScore ( int l , int r , int prefix_sum [ ] , int num ) { if ( l > r ) return 0 ; int current_sum = prefix_sum [ r ] - ( l - 1 >= 0 ? prefix_sum [ l - 1 ] : 0 ) ; if ( num % 2 == 0 ) current_sum *= -1 ; return current_sum + max ( maxScore ( l + 1 , r , prefix_sum , num + 1 ) , maxScore ( l , r - 1 , prefix_sum , num + 1 ) ) ; } int findMaxScore ( int a [ ] , int n ) { int prefix_sum [ n ] = { 0 } ; prefix_sum [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { prefix_sum [ i ] = prefix_sum [ i - 1 ] + a [ i ] ; } return maxScore ( 0 , n - 1 , prefix_sum , 1 ) ; } int main ( ) { int n = 6 ; int A [ n ] = { 1 , 2 , 3 , 4 , 2 , 6 } ; cout << findMaxScore ( A , n ) ; return 0 ; } |
Make all array elements divisible by a number K | C ++ implementation to make the array elements divisible by K ; Function to make array divisible ; For each element of array how much number to be subtracted to make it divisible by k ; For each element of array how much number to be added to make it divisible by K ; Calculate minimum difference ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; pair < int , int > makeDivisble ( int arr [ ] , int n , int k ) { vector < int > b1 ; vector < int > b2 ; int c , suml , sumr , index , rem ; for ( int i = 0 ; i < n ; i ++ ) b1 . push_back ( arr [ i ] % k ) ; for ( int j = 0 ; j < n ; j ++ ) if ( ( arr [ j ] % k ) != 0 ) b2 . push_back ( k - ( arr [ j ] % k ) ) ; else b2 . push_back ( 0 ) ; c = 0 ; float mini = INT_MAX ; suml = 0 ; sumr = 0 ; index = -1 ; for ( int c = 0 ; c < n ; c ++ ) { suml = accumulate ( b1 . begin ( ) , b1 . begin ( ) + c + 1 , 0 ) ; sumr = accumulate ( b2 . begin ( ) + c + 1 , b2 . end ( ) , 0 ) ; if ( suml >= sumr ) { rem = suml - sumr ; if ( rem < mini ) { mini = rem ; index = c ; } } } return make_pair ( index , mini ) ; } int main ( ) { int arr [ ] = { 1 , 14 , 4 , 41 , 1 } ; int k = 7 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pair < int , int > ans ; ans = makeDivisble ( arr , n , k ) ; cout << ans . first << " β " << ans . second ; return 0 ; } |
Finding powers of any number P in N ! | C ++ program to find the power of P in N ! ; Map to store all the prime factors of P ; Function to find the prime factors of N im Map ; Clear map ; Check for factors of 2 ; Find all the prime factors ; If i is a factors then increase the frequency of i ; Function to find the power of prime number P in N ! ; Loop until temp <= N ; Add the number of numbers divisible by N ; Each time multiply temp by P ; Returns ans ; Function that find the powers of any P in N ! ; Find all prime factors of number P ; To store the powers of all prime factors ; Traverse the map ; Prime factor and corres . powers ; Find power of prime factor primeFac ; Divide frequency by facPow ; Store the power of primeFac ^ facPow ; Return the minimum element in Power array ; Driver 's Code ; Function to find power of P in N ! | #include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_map < int , int > Map ; void findPrimeFactors ( int N ) { int i ; Map . clear ( ) ; while ( N % 2 == 0 ) { Map [ 2 ] += 1 ; N /= 2 ; } for ( i = 3 ; i <= sqrt ( N ) ; i += 2 ) { while ( N % i == 0 ) { Map [ i ] += 1 ; N /= i ; } } if ( N > 2 ) { Map [ N ] += 1 ; } } int PowInFactN ( int N , int P ) { int ans = 0 ; int temp = P ; while ( temp <= N ) { ans += N / temp ; temp = temp * P ; } return ans ; } int findPowers ( int N , int P ) { findPrimeFactors ( P ) ; vector < int > Powers ; for ( auto & it : Map ) { int primeFac = it . first ; int facPow = it . second ; int p = PowInFactN ( N , primeFac ) ; p /= facPow ; Powers . push_back ( p ) ; } return * min_element ( Powers . begin ( ) , Powers . end ( ) ) ; } int main ( ) { int N = 24 , P = 4 ; cout << findPowers ( N , P ) ; return 0 ; } |
Longest common subarray in the given two arrays | C ++ program to DP approach to above solution ; Function to find the maximum length of equal subarray ; Auxiliary dp [ ] [ ] array ; Updating the dp [ ] [ ] table in Bottom Up approach ; If A [ i ] is equal to B [ i ] then dp [ j ] [ i ] = dp [ j + 1 ] [ i + 1 ] + 1 ; Find maximum of all the values in dp [ ] [ ] array to get the maximum length ; Update the length ; Return the maximum length ; Driver Code ; Function call to find maximum length of subarray | #include <bits/stdc++.h> NEW_LINE using namespace std ; int FindMaxLength ( int A [ ] , int B [ ] , int n , int m ) { int dp [ n + 1 ] [ m + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= m ; j ++ ) dp [ i ] [ j ] = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { for ( int j = m - 1 ; j >= 0 ; j -- ) { if ( A [ i ] == B [ j ] ) dp [ j ] [ i ] = dp [ j + 1 ] [ i + 1 ] + 1 ; } } int maxm = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { maxm = max ( maxm , dp [ i ] [ j ] ) ; } } return maxm ; } int main ( ) { int A [ ] = { 1 , 2 , 8 , 2 , 1 } ; int B [ ] = { 8 , 2 , 1 , 4 , 7 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int m = sizeof ( B ) / sizeof ( B [ 0 ] ) ; cout << ( FindMaxLength ( A , B , n , m ) ) ; } |
Maximum sum of elements divisible by K from the given array | | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int k = 16 ; vector < int > arr = { 43 , 1 , 17 , 26 , 15 } ; int n = arr . size ( ) ; vector < vector < int > > dp ( n + 2 , vector < int > ( k , 0 ) ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 0 ; j < k ; j ++ ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } dp [ i ] [ arr [ i - 1 ] % k ] = max ( dp [ i ] [ arr [ i - 1 ] % k ] , arr [ i - 1 ] ) ; for ( int j = 0 ; j < k ; j ++ ) { int m = ( j + arr [ i - 1 ] ) % k ; if ( dp [ i - 1 ] [ j ] != 0 ) dp [ i ] [ m ] = max ( dp [ i ] [ m ] , arr [ i - 1 ] + dp [ i - 1 ] [ j ] ) ; } } cout << dp [ n ] [ 0 ] ; return 0 ; } |
Maximum contiguous decreasing sequence obtained by removing any one element | C ++ program to find maximum length of decreasing sequence by removing at most one element ; Function to find the maximum length ; Initialise maximum length to 1 ; Initialise left [ ] to find the length of decreasing sequence from left to right ; Initialise right [ ] to find the length of decreasing sequence from right to left ; Initially store 1 at each index of left and right array ; Iterate over the array arr [ ] to store length of decreasing sequence that can be obtained at every index in the right array ; Store the length of longest continuous decreasing sequence in maximum ; Iterate over the array arr [ ] to store length of decreasing sequence that can be obtained at every index in the left array ; Check if we can obtain a longer decreasing sequence after removal of any element from the array arr [ ] with the help of left [ ] & right [ ] ; Return maximum length of sequence ; Driver code ; Function calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLength ( int * a , int n ) { int maximum = 1 ; int left [ n ] ; int right [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { left [ i ] = 1 ; right [ i ] = 1 ; } for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( a [ i ] > a [ i + 1 ] ) { right [ i ] = right [ i + 1 ] + 1 ; } maximum = max ( maximum , right [ i ] ) ; } for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] < a [ i - 1 ] ) { left [ i ] = left [ i - 1 ] + 1 ; } } if ( n > 2 ) { for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( a [ i - 1 ] > a [ i + 1 ] ) { maximum = max ( maximum , left [ i - 1 ] + right [ i + 1 ] ) ; } } } return maximum ; } int main ( ) { int arr [ 6 ] = { 8 , 7 , 3 , 5 , 2 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxLength ( arr , n ) << endl ; return 0 ; } |
Longest alternating subsequence in terms of positive and negative integers | C ++ program to find the length of longest alternate subsequence ; LAS [ i ] [ pos ] array to find the length of LAS till index i by including or excluding element arr [ i ] on the basis of value of pos ; Base Case ; If current element is positive and pos is true Include the current element and change pos to false ; Recurr for the next iteration ; If current element is negative and pos is false Include the current element and change pos to true ; Recurr for the next iteration ; If current element is excluded , reccur for next iteration ; Driver 's Code ; Print LAS | #include <bits/stdc++.h> NEW_LINE using namespace std ; int LAS [ 1000 ] [ 2 ] = { false } ; int solve ( int arr [ ] , int n , int i , bool pos ) { if ( i == n ) return 0 ; if ( LAS [ i ] [ pos ] ) return LAS [ i ] [ pos ] ; int inc = 0 , exc = 0 ; if ( arr [ i ] > 0 && pos == true ) { pos = false ; inc = 1 + solve ( arr , n , i + 1 , pos ) ; } else if ( arr [ i ] < 0 && pos == false ) { pos = true ; inc = 1 + solve ( arr , n , i + 1 , pos ) ; } exc = solve ( arr , n , i + 1 , pos ) ; LAS [ i ] [ pos ] = max ( inc , exc ) ; return LAS [ i ] [ pos ] ; } int main ( ) { int arr [ ] = { -1 , 2 , 3 , 4 , 5 , -6 , 8 , -99 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << max ( solve ( arr , n , 0 , 0 ) , solve ( arr , n , 0 , 1 ) ) ; } |
Number of subsequences with negative product | C ++ implementation of the approach ; Function to return the count of all the subsequences with negative product ; To store the count of positive elements in the array ; To store the count of negative elements in the array ; If the current element is positive ; If the current element is negative ; For all the positive elements of the array ; For all the negative elements of the array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cntSubSeq ( int arr [ ] , int n ) { int pos_count = 0 ; int neg_count = 0 ; int result ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) pos_count ++ ; if ( arr [ i ] < 0 ) neg_count ++ ; } result = pow ( 2 , pos_count ) ; if ( neg_count > 0 ) result *= pow ( 2 , neg_count - 1 ) ; else result = 0 ; return result ; } int main ( ) { int arr [ ] = { 3 , -4 , -1 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntSubSeq ( arr , n ) ; return 0 ; } |
Find minimum number of steps to reach the end of String | C ++ implementation of the approach ; Function to return the minimum number of steps to reach the end ; If the end can 't be reached ; Already at the end ; If the length is 2 or 3 then the end can be reached in a single step ; For the other cases , solve the problem using dynamic programming ; It requires no move from the end to reach the end ; From the 2 nd last and the 3 rd last index , only a single move is required ; Update the answer for every index ; If the current index is not reachable ; To store the minimum steps required from the current index ; If it is a valid move then update the minimum steps required ; Update the minimum steps required starting from the current index ; Cannot reach the end starting from str [ 0 ] ; Return the minimum steps required ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( string str , int n , int k ) { if ( str [ n - 1 ] == '0' ) return -1 ; if ( n == 1 ) return 0 ; if ( n < 4 ) return 1 ; int dp [ n ] ; dp [ n - 1 ] = 0 ; dp [ n - 2 ] = 1 ; dp [ n - 3 ] = 1 ; for ( int i = n - 4 ; i >= 0 ; i -- ) { if ( str [ i ] == '0' ) continue ; int steps = INT_MAX ; if ( i + k < n && str [ i + k ] == '1' ) steps = min ( steps , dp [ i + k ] ) ; if ( str [ i + 1 ] == '1' ) steps = min ( steps , dp [ i + 1 ] ) ; if ( str [ i + 2 ] == '1' ) steps = min ( steps , dp [ i + 2 ] ) ; dp [ i ] = ( steps == INT_MAX ) ? steps : 1 + steps ; } if ( dp [ 0 ] == INT_MAX ) return -1 ; return dp [ 0 ] ; } int main ( ) { string str = "101000011" ; int n = str . length ( ) ; int k = 5 ; cout << minSteps ( str , n , k ) ; return 0 ; } |
Length of longest Palindromic Subsequence of even length with no two adjacent characters same | C ++ implementation of above approach ; To store the values of subproblems ; Function to find the Longest Palindromic subsequence of even length with no two adjacent characters same ; Base cases If the string length is 1 return 0 ; If the string length is 2 ; Check if the characters match ; If the value with given parameters is previously calculated ; If the first and last character of the string matches with the given character ; Remove the first and last character and call the function for all characters ; If it does not match ; Then find the first and last index of given character in the given string ; Take the substring from i to j and call the function with substring and the given character ; Store the answer for future use ; Driver code ; Check for all starting characters | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define lli long long int NEW_LINE unordered_map < string , lli > dp ; lli solve ( string s , char c ) { if ( s . length ( ) == 1 ) return 0 ; if ( s . length ( ) == 2 ) { if ( s [ 0 ] == s [ 1 ] && s [ 0 ] == c ) return 1 ; else return 0 ; } if ( dp [ s + " β " + c ] ) return dp [ s + " β " + c ] ; lli ans = 0 ; if ( s [ 0 ] == s [ s . length ( ) - 1 ] && s [ 0 ] == c ) { for ( char c1 = ' a ' ; c1 <= ' z ' ; c1 ++ ) if ( c1 != c ) ans = max ( ans , 1 + solve ( s . substr ( 1 , s . length ( ) - 2 ) , c1 ) ) ; } else { for ( lli i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == c ) { for ( lli j = s . length ( ) - 1 ; j > i ; j -- ) if ( s [ j ] == c ) { if ( j == i ) break ; ans = solve ( s . substr ( i , j - i + 1 ) , c ) ; break ; } break ; } } } dp [ s + " β " + c ] = ans ; return dp [ s + " β " + c ] ; } int main ( ) { string s = " abscrcdba " ; lli ma = 0 ; for ( char c1 = ' a ' ; c1 <= ' z ' ; c1 ++ ) ma = max ( ma , solve ( s , c1 ) * 2 ) ; cout << ma << endl ; return 0 ; } |
Eggs dropping puzzle | Set 2 | C ++ implementation of the approach ; Function to return the minimum number of trials needed in the worst case with n eggs and k floors ; Fill all the entries in table using optimal substructure property ; Return the minimum number of moves ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int eggDrop ( int n , int k ) { vector < vector < int > > dp ( k + 1 , vector < int > ( n + 1 , 0 ) ) ; int x = 0 ; while ( dp [ x ] [ n ] < k ) { x ++ ; for ( int i = 1 ; i <= n ; i ++ ) dp [ x ] [ i ] = dp [ x - 1 ] [ i - 1 ] + dp [ x - 1 ] [ i ] + 1 ; } return x ; } int main ( ) { int n = 2 , k = 36 ; cout << eggDrop ( n , k ) ; return 0 ; } |
Maximum length of Strictly Increasing Sub | C ++ implementation of the approach ; Function to return the maximum length of strictly increasing subarray after removing atmost one element ; Create two arrays pre and pos ; Find out the contribution of the current element in array [ 0 , i ] and update pre [ i ] ; Find out the contribution of the current element in array [ N - 1 , i ] and update pos [ i ] ; Calculate the maximum length of the stricly increasing subarray without removing any element ; Calculate the maximum length of the strictly increasing subarray after removing the current element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxIncSubarr ( int a [ ] , int n ) { int pre [ n ] = { 0 } ; int pos [ n ] = { 0 } ; pre [ 0 ] = 1 ; pos [ n - 1 ] = 1 ; int l = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] > a [ i - 1 ] ) pre [ i ] = pre [ i - 1 ] + 1 ; else pre [ i ] = 1 ; } l = 1 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( a [ i ] < a [ i + 1 ] ) pos [ i ] = pos [ i + 1 ] + 1 ; else pos [ i ] = 1 ; } int ans = 0 ; l = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] > a [ i - 1 ] ) l ++ ; else l = 1 ; ans = max ( ans , l ) ; } for ( int i = 1 ; i <= n - 2 ; i ++ ) { if ( a [ i - 1 ] < a [ i + 1 ] ) ans = max ( pre [ i - 1 ] + pos [ i + 1 ] , ans ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << maxIncSubarr ( arr , n ) ; return 0 ; } |
Number of square matrices with all 1 s | C ++ program to return the number of square submatrices with all 1 s ; Function to return the number of square submatrices with all 1 s ; Initialize count variable ; If a [ i ] [ j ] is equal to 0 ; Calculate number of square submatrices ending at ( i , j ) ; Calculate the sum of the array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define n 3 NEW_LINE #define m 3 NEW_LINE int countSquareMatrices ( int a [ ] [ m ] , int N , int M ) { int count = 0 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j < M ; j ++ ) { if ( a [ i ] [ j ] == 0 ) continue ; a [ i ] [ j ] = min ( min ( a [ i - 1 ] [ j ] , a [ i ] [ j - 1 ] ) , a [ i - 1 ] [ j - 1 ] ) + 1 ; } } for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) count += a [ i ] [ j ] ; return count ; } int main ( ) { int arr [ ] [ m ] = { { 1 , 0 , 1 } , { 1 , 1 , 0 } , { 1 , 1 , 0 } } ; cout << countSquareMatrices ( arr , n , m ) ; return 0 ; } |
Count number of increasing sub | C ++ implementation of the approach ; Segment tree array ; Function for point update in segment tree ; Base case ; If l == r == up ; Mid element ; Updating the segment tree ; Function for the range sum - query ; Base case ; Mid element ; Calling for the left and the right subtree ; Function to return the count ; Copying array arr to sort it ; Sorting array brr ; Map to store the rank of each element ; dp array ; To store the final answer ; Updating the dp array ; Rank of the element ; Solving the dp - states using segment tree ; Updating the final answer ; Updating the segment tree ; Returning the final answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 10000 NEW_LINE int seg [ 3 * N ] ; int update ( int in , int l , int r , int up_in , int val ) { if ( r < up_in l > up_in ) return seg [ in ] ; if ( l == up_in and r == up_in ) return seg [ in ] = val ; int m = ( l + r ) / 2 ; return seg [ in ] = update ( 2 * in + 1 , l , m , up_in , val ) + update ( 2 * in + 2 , m + 1 , r , up_in , val ) ; } int query ( int in , int l , int r , int l1 , int r1 ) { if ( l > r ) return 0 ; if ( r < l1 l > r1 ) return 0 ; if ( l1 <= l and r <= r1 ) return seg [ in ] ; int m = ( l + r ) / 2 ; return query ( 2 * in + 1 , l , m , l1 , r1 ) + query ( 2 * in + 2 , m + 1 , r , l1 , r1 ) ; } int findCnt ( int * arr , int n ) { int brr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) brr [ i ] = arr [ i ] ; sort ( brr , brr + n ) ; map < int , int > r ; for ( int i = 0 ; i < n ; i ++ ) r [ brr [ i ] ] = i + 1 ; int dp [ n ] = { 0 } ; int ans = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { int rank = r [ arr [ i ] ] ; dp [ i ] = 1 + query ( 0 , 0 , n - 1 , rank , n - 1 ) ; ans += dp [ i ] ; update ( 0 , 0 , n - 1 , rank - 1 , dp [ i ] + query ( 0 , 0 , n - 1 , rank - 1 , rank - 1 ) ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 10 , 9 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findCnt ( arr , n ) ; return 0 ; } |
Minimum cost to build N blocks from one block | C ++ program to Minimum cost to build N blocks from one block ; Function to calculate min cost to build N blocks ; Initialize base case ; Recurence when i is odd ; Recurence when i is even ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( int n , int x , int y , int z ) { int dp [ n + 1 ] = { 0 } ; dp [ 0 ] = dp [ 1 ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( i % 2 == 1 ) { dp [ i ] = min ( dp [ ( i + 1 ) / 2 ] + x + z , dp [ i - 1 ] + y ) ; } else { dp [ i ] = min ( dp [ i / 2 ] + x , dp [ i - 1 ] + y ) ; } } return dp [ n ] ; } int main ( ) { int n = 5 , x = 2 , y = 1 , z = 3 ; cout << minCost ( n , x , y , z ) << endl ; return 0 ; } |
Size of the largest divisible subset in an Array | C ++ implementation of the above approach ; Function to find the size of the largest divisible subarray ; Mark all elements of the array ; Traverse reverse ; For all multiples of i ; Return the required answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 1000005 NEW_LINE int maximum_set ( int a [ ] , int n ) { int dp [ N ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) dp [ a [ i ] ] = 1 ; int ans = 1 ; for ( int i = N - 1 ; i >= 1 ; i -- ) { if ( dp [ i ] != 0 ) { for ( int j = 2 * i ; j < N ; j += i ) { dp [ i ] = max ( dp [ i ] , 1 + dp [ j ] ) ; ans = max ( ans , dp [ i ] ) ; } } } return ans ; } int main ( ) { int arr [ ] = { 3 , 4 , 6 , 8 , 10 , 18 , 21 , 24 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximum_set ( arr , n ) ; return 0 ; } |
Longest sub | C ++ implementation of the approach ; Function to return the length of the largest sub - string divisible by 3 ; Base - case ; If the state has been solved before then return its value ; Marking the state as solved ; Recurrence relation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100 NEW_LINE int dp [ N ] [ 3 ] ; bool v [ N ] [ 3 ] ; int findLargestString ( string & s , int i , int r ) { if ( i == s . size ( ) ) { if ( r == 0 ) return 0 ; else return INT_MIN ; } if ( v [ i ] [ r ] ) return dp [ i ] [ r ] ; v [ i ] [ r ] = 1 ; dp [ i ] [ r ] = max ( 1 + findLargestString ( s , i + 1 , ( r * 2 + ( s [ i ] - '0' ) ) % 3 ) , findLargestString ( s , i + 1 , r ) ) ; return dp [ i ] [ r ] ; } int main ( ) { string s = "101" ; cout << findLargestString ( s , 0 , 0 ) ; return 0 ; } |
Number of sub | C ++ implementation of th approach ; Function to return the number of sub - sequences divisible by 3 ; Base - cases ; If the state has been solved before then return its value ; Marking the state as solved ; Recurrence relation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100 NEW_LINE int dp [ N ] [ 3 ] ; bool v [ N ] [ 3 ] ; int findCnt ( string & s , int i , int r ) { if ( i == s . size ( ) ) { if ( r == 0 ) return 1 ; else return 0 ; } if ( v [ i ] [ r ] ) return dp [ i ] [ r ] ; v [ i ] [ r ] = 1 ; dp [ i ] [ r ] = findCnt ( s , i + 1 , ( r * 2 + ( s [ i ] - '0' ) ) % 3 ) + findCnt ( s , i + 1 , r ) ; return dp [ i ] [ r ] ; } int main ( ) { string s = "11" ; cout << ( findCnt ( s , 0 , 0 ) - 1 ) ; return 0 ; } |
Remove minimum elements from ends of array so that sum decreases by at least K | O ( N ) | C ++ implementation of the approach ; Function to return the count of minimum elements to be removed from the ends of the array such that the sum of the array decrease by at least K ; To store the final answer ; Maximum possible sum required ; Left point ; Right pointer ; Total current sum ; Two pointer loop ; If the sum fits ; Update the answer ; Update the total sum ; Increment the left pointer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCount ( int * arr , int n , int k ) { int ans = 0 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; sum -= k ; int l = 0 ; int r = 0 ; int tot = 0 ; while ( l < n ) { if ( tot <= sum ) { ans = max ( ans , r - l ) ; if ( r == n ) break ; tot += arr [ r ++ ] ; } else { tot -= arr [ l ++ ] ; } } return ( n - ans ) ; } int main ( ) { int arr [ ] = { 1 , 11 , 5 , 5 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 11 ; cout << minCount ( arr , n , k ) ; return 0 ; } |
Minimum cost to merge all elements of List | C ++ implementation of the approach ; To store the states of DP ; Function to return the minimum merge cost ; Base case ; If the state has been solved before ; Marking the state as solved ; Reference to dp [ i ] [ j ] ; To store the sum of all the elements in the subarray arr [ i ... j ] ; Loop to iterate the recurrence ; Returning the solved value ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 401 NEW_LINE int dp [ N ] [ N ] ; bool v [ N ] [ N ] ; int minMergeCost ( int i , int j , int * arr ) { if ( i == j ) return 0 ; if ( v [ i ] [ j ] ) return dp [ i ] [ j ] ; v [ i ] [ j ] = 1 ; int & x = dp [ i ] [ j ] ; x = INT_MAX ; int tot = 0 ; for ( int k = i ; k <= j ; k ++ ) tot += arr [ k ] ; for ( int k = i + 1 ; k <= j ; k ++ ) { x = min ( x , tot + minMergeCost ( i , k - 1 , arr ) + minMergeCost ( k , j , arr ) ) ; } return x ; } int main ( ) { int arr [ ] = { 1 , 3 , 7 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << minMergeCost ( 0 , n - 1 , arr ) ; return 0 ; } |
Expected number of moves to reach the end of a board | Dynamic programming | C ++ implementation of the approach ; To store the states of dp ; To determine whether a state has been solved before ; Function to return the count ; Base cases ; If a state has been solved before it won 't be evaluated again ; Recurrence relation ; Driver code | #include <bits/stdc++.h> NEW_LINE #define maxSize 50 NEW_LINE using namespace std ; double dp [ maxSize ] ; int v [ maxSize ] ; double expectedSteps ( int x ) { if ( x == 0 ) return 0 ; if ( x <= 5 ) return 6 ; if ( v [ x ] ) return dp [ x ] ; v [ x ] = 1 ; dp [ x ] = 1 + ( expectedSteps ( x - 1 ) + expectedSteps ( x - 2 ) + expectedSteps ( x - 3 ) + expectedSteps ( x - 4 ) + expectedSteps ( x - 5 ) + expectedSteps ( x - 6 ) ) / 6 ; return dp [ x ] ; } int main ( ) { int n = 10 ; cout << expectedSteps ( n - 1 ) ; return 0 ; } |
Number of subsequences in a given binary string divisible by 2 | C ++ implementation of the approach ; Function to return the count of the required subsequences ; To store the final answer ; Multiplier ; Loop to find the answer ; Condition to update the answer ; updating multiplier ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubSeq ( string str , int len ) { int ans = 0 ; int mul = 1 ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == '0' ) ans += mul ; mul *= 2 ; } return ans ; } int main ( ) { string str = "10010" ; int len = str . length ( ) ; cout << countSubSeq ( str , len ) ; return 0 ; } |
Knapsack with large Weights | C ++ implementation of the approach ; To store the states of DP ; Function to solve the recurrence relation ; Base cases ; Marking state as solved ; Recurrence relation ; Function to return the maximum weight ; Iterating through all possible values to find the the largest value that can be represented by the given weights ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define V_SUM_MAX 1000 NEW_LINE #define N_MAX 100 NEW_LINE #define W_MAX 10000000 NEW_LINE int dp [ V_SUM_MAX + 1 ] [ N_MAX ] ; bool v [ V_SUM_MAX + 1 ] [ N_MAX ] ; int solveDp ( int r , int i , int * w , int * val , int n ) { if ( r <= 0 ) return 0 ; if ( i == n ) return W_MAX ; if ( v [ r ] [ i ] ) return dp [ r ] [ i ] ; v [ r ] [ i ] = 1 ; dp [ r ] [ i ] = min ( solveDp ( r , i + 1 , w , val , n ) , w [ i ] + solveDp ( r - val [ i ] , i + 1 , w , val , n ) ) ; return dp [ r ] [ i ] ; } int maxWeight ( int * w , int * val , int n , int c ) { for ( int i = V_SUM_MAX ; i >= 0 ; i -- ) { if ( solveDp ( i , 0 , w , val , n ) <= c ) { return i ; } } return 0 ; } int main ( ) { int w [ ] = { 3 , 4 , 5 } ; int val [ ] = { 30 , 50 , 60 } ; int n = sizeof ( w ) / sizeof ( int ) ; int C = 8 ; cout << maxWeight ( w , val , n , C ) ; return 0 ; } |
Sum of lengths of all paths possible in a given tree | C ++ implementation of the approach ; Number of vertices ; Adjacency list representation of the tree ; Array that stores the subtree size ; Array to mark all the vertices which are visited ; Utility function to create an edge between two vertices ; Add a to b 's list ; Add b to a 's list ; Function to calculate the subtree size ; Mark visited ; For every adjacent node ; If not already visited ; Recursive call for the child ; Function to calculate the contribution of each edge ; Mark current node as visited ; For every adjacent node ; If it is not already visisted ; Function to return the required sum ; First pass of the dfs ; Second pass ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int sz = 1e5 ; int n ; vector < int > tree [ sz ] ; int subtree_size [ sz ] ; int vis [ sz ] ; void addEdge ( int a , int b ) { tree [ a ] . push_back ( b ) ; tree [ b ] . push_back ( a ) ; } int dfs ( int node ) { vis [ node ] = 1 ; subtree_size [ node ] = 1 ; for ( auto child : tree [ node ] ) { if ( ! vis [ child ] ) { subtree_size [ node ] += dfs ( child ) ; } } return subtree_size [ node ] ; } void contribution ( int node , int & ans ) { vis [ node ] = true ; for ( int child : tree [ node ] ) { if ( ! vis [ child ] ) { ans += ( subtree_size [ child ] * ( n - subtree_size [ child ] ) ) ; contribution ( child , ans ) ; } } } int getSum ( ) { memset ( vis , 0 , sizeof ( vis ) ) ; dfs ( 0 ) ; int ans = 0 ; memset ( vis , 0 , sizeof ( vis ) ) ; contribution ( 0 , ans ) ; return ans ; } int main ( ) { n = 5 ; addEdge ( 0 , 1 ) ; addEdge ( 0 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 1 , 4 ) ; cout << getSum ( ) ; return 0 ; } |
Number of cells in a matrix that satisfy the given condition | C ++ implementation of the approach ; Function to return the number of cells in which mirror can be placed ; Update the row array where row [ i ] [ j ] will store whether the current row i contains all 1 s in the columns starting from j ; Update the column array where col [ i ] [ j ] will store whether the current column j contains all 1 s in the rows starting from i ; To store the required result ; For every cell except the last row and the last column ; If the current cell is not blocked and the light can travel from the next row and the next column then the current cell is valid ; For the last column ; For the last row , note that the last column is not taken into consideration as the bottom right element has already been considered in the last column previously ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 3 ; int numberOfCells ( int mat [ ] [ N ] ) { bool row [ N ] [ N ] = { { false } } ; bool col [ N ] [ N ] = { { false } } ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = N - 1 ; j >= 0 ; j -- ) { if ( mat [ i ] [ j ] == 1 ) { row [ i ] [ j ] = ( j + 1 < N ) ? row [ i ] [ j + 1 ] : true ; } else { row [ i ] [ j ] = false ; } } } for ( int j = 0 ; j < N ; j ++ ) { for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( mat [ i ] [ j ] == 1 ) { col [ i ] [ j ] = ( i + 1 < N ) ? col [ i + 1 ] [ j ] : true ; } else { col [ i ] [ j ] = false ; } } } int cnt = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = 0 ; j < N - 1 ; j ++ ) { if ( row [ i ] [ j ] && col [ i ] [ j ] ) { cnt ++ ; } } } for ( int i = 0 ; i < N ; i ++ ) { if ( col [ i ] [ N - 1 ] ) cnt ++ ; } for ( int j = 0 ; j < N - 1 ; j ++ ) { if ( row [ N - 1 ] [ j ] ) cnt ++ ; } return cnt ; } int main ( ) { int mat [ ] [ N ] = { { 0 , 1 , 1 } , { 0 , 1 , 1 } , { 0 , 1 , 1 } } ; cout << numberOfCells ( mat ) ; return 0 ; } |
Maximum sum subarray after altering the array | C ++ implementation of the approach ; Function to return the maximum subarray sum ; Function to reverse the subarray arr [ 0. . . i ] ; Function to return the maximum subarray sum after performing the given operation at most once ; To store the result ; When no operation is performed ; Find the maximum subarray sum after reversing the subarray arr [ 0. . . i ] for all possible values of i ; The complete array is reversed so that the subarray can be processed as arr [ 0. . . i ] instead of arr [ i ... N - 1 ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumSubarray ( vector < int > arr , int size ) { int max_so_far = INT_MIN , max_ending_here = 0 ; for ( int i = 0 ; i < size ; i ++ ) { max_ending_here = max_ending_here + arr [ i ] ; if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; if ( max_ending_here < 0 ) max_ending_here = 0 ; } return max_so_far ; } void getUpdatedArray ( vector < int > & arr , vector < int > & copy , int i ) { for ( int j = 0 ; j <= ( i / 2 ) ; j ++ ) { copy [ j ] = arr [ i - j ] ; copy [ i - j ] = arr [ j ] ; } return ; } int maxSum ( vector < int > arr , int size ) { int resSum = INT_MIN ; resSum = max ( resSum , maxSumSubarray ( arr , size ) ) ; vector < int > copyArr = arr ; for ( int i = 1 ; i < size ; i ++ ) { getUpdatedArray ( arr , copyArr , i ) ; resSum = max ( resSum , maxSumSubarray ( copyArr , size ) ) ; } reverse ( arr . begin ( ) , arr . end ( ) ) ; copyArr = arr ; for ( int i = 1 ; i < size ; i ++ ) { getUpdatedArray ( arr , copyArr , i ) ; resSum = max ( resSum , maxSumSubarray ( copyArr , size ) ) ; } return resSum ; } int main ( ) { vector < int > arr { -9 , 21 , 24 , 24 , -51 , -6 , 17 , -42 , -39 , 33 } ; int size = arr . size ( ) ; cout << maxSum ( arr , size ) ; return 0 ; } |
Maximum possible GCD after replacing at most one element in the given array | C ++ implementation of the approach ; Function to return the maximum possible gcd after replacing a single element ; Prefix and Suffix arrays ; Single state dynamic programming relation for storing gcd of first i elements from the left in Prefix [ i ] ; Initializing Suffix array ; Single state dynamic programming relation for storing gcd of all the elements having index greater than or equal to i in Suffix [ i ] ; If first or last element of the array has to be replaced ; If any other element is replaced ; Return the maximized gcd ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxGCD ( int a [ ] , int n ) { int Prefix [ n + 2 ] ; int Suffix [ n + 2 ] ; Prefix [ 1 ] = a [ 0 ] ; for ( int i = 2 ; i <= n ; i += 1 ) { Prefix [ i ] = __gcd ( Prefix [ i - 1 ] , a [ i - 1 ] ) ; } Suffix [ n ] = a [ n - 1 ] ; for ( int i = n - 1 ; i >= 1 ; i -= 1 ) { Suffix [ i ] = __gcd ( Suffix [ i + 1 ] , a [ i - 1 ] ) ; } int ans = max ( Suffix [ 2 ] , Prefix [ n - 1 ] ) ; for ( int i = 2 ; i < n ; i += 1 ) { ans = max ( ans , __gcd ( Prefix [ i - 1 ] , Suffix [ i + 1 ] ) ) ; } return ans ; } int main ( ) { int a [ ] = { 6 , 7 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << MaxGCD ( a , n ) ; return 0 ; } |
Sum of products of all possible K size subsets of the given array | C ++ implementation of the approach ; Function to return the sum of products of all the possible k size subsets ; Initialising all the values to 0 ; To store the answer for current value of k ; For k = 1 , the answer will simply be the sum of all the elements ; Filling the table in bottom up manner ; To store the elements of the current row so that we will be able to use this sum for subsequent values of k ; We will subtract previously computed value so as to get the sum of elements from j + 1 to n in the ( i - 1 ) th row ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfProduct ( int arr [ ] , int n , int k ) { int dp [ n + 1 ] [ n + 1 ] = { 0 } ; int cur_sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { dp [ 1 ] [ i ] = arr [ i - 1 ] ; cur_sum += arr [ i - 1 ] ; } for ( int i = 2 ; i <= k ; i ++ ) { int temp_sum = 0 ; for ( int j = 1 ; j <= n ; j ++ ) { cur_sum -= dp [ i - 1 ] [ j ] ; dp [ i ] [ j ] = arr [ j - 1 ] * cur_sum ; temp_sum += dp [ i ] [ j ] ; } cur_sum = temp_sum ; } return cur_sum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 2 ; cout << sumOfProduct ( arr , n , k ) ; return 0 ; } |
Find the equal pairs of subsequence of S and subsequence of T | C ++ implementation of the approach ; Function to return the pairs of subsequences from S [ ] and subsequences from T [ ] such that both have the same content ; Create dp array ; Base values ; Base values ; Keep previous dp value ; If both elements are same ; Return the required answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod (int)(1e9 + 7) NEW_LINE int subsequence ( int S [ ] , int T [ ] , int n , int m ) { int dp [ n + 1 ] [ m + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) dp [ i ] [ 0 ] = 1 ; for ( int j = 0 ; j <= m ; j ++ ) dp [ 0 ] [ j ] = 1 ; for ( int i = 1 ; i <= n ; ++ i ) { for ( int j = 1 ; j <= m ; ++ j ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] - dp [ i - 1 ] [ j - 1 ] ; if ( S [ i - 1 ] == T [ j - 1 ] ) dp [ i ] [ j ] += dp [ i - 1 ] [ j - 1 ] ; dp [ i ] [ j ] += mod ; dp [ i ] [ j ] %= mod ; } } return dp [ n ] [ m ] ; } int main ( ) { int S [ ] = { 1 , 1 } ; int n = sizeof ( S ) / sizeof ( S [ 0 ] ) ; int T [ ] = { 1 , 1 } ; int m = sizeof ( T ) / sizeof ( T [ 0 ] ) ; cout << subsequence ( S , T , n , m ) ; return 0 ; } |
Maximum count of elements divisible on the left for any element | C ++ implementation of the approach ; Function to return the maximum count of required elements ; For every element in the array starting from the second element ; Check all the elements on the left of current element which are divisible by the current element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMax ( int arr [ ] , int n ) { int res = 0 ; int i , j ; for ( i = 0 ; i < n ; i ++ ) { int count = 0 ; for ( j = 0 ; j < i ; j ++ ) { if ( arr [ j ] % arr [ i ] == 0 ) count += 1 ; } res = max ( count , res ) ; } return res ; } int main ( ) { int arr [ ] = { 8 , 1 , 28 , 4 , 2 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findMax ( arr , n ) ; return 0 ; } |
Maximum count of elements divisible on the left for any element | C ++ implementation of the approach ; Function to return the maximum count of required elements ; divisible [ i ] will store true if arr [ i ] is divisible by any element on its right ; To store the maximum required count ; For every element of the array ; If the current element is divisible by any element on its right ; Find the count of element on the left which are divisible by the current element ; If arr [ j ] is divisible then set divisible [ j ] to true ; Update the maximum required count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMax ( int arr [ ] , int n ) { bool divisible [ n ] = { false } ; int res = 0 ; for ( int i = n - 1 ; i > 0 ; i -- ) { if ( divisible [ i ] ) continue ; int cnt = 0 ; for ( int j = 0 ; j < i ; j ++ ) { if ( ( arr [ j ] % arr [ i ] ) == 0 ) { divisible [ j ] = true ; cnt ++ ; } } res = max ( res , cnt ) ; } return res ; } int main ( ) { int arr [ ] = { 8 , 1 , 28 , 4 , 2 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findMax ( arr , n ) ; return 0 ; } |
Number of subsets with sum divisible by M | Set 2 | C ++ implementation of the approach ; To store the states of DP ; Function to find the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxN 20 NEW_LINE #define maxM 10 NEW_LINE int dp [ maxN ] [ maxM ] ; bool v [ maxN ] [ maxM ] ; int findCnt ( int * arr , int i , int curr , int n , int m ) { if ( i == n ) { if ( curr == 0 ) return 1 ; else return 0 ; } if ( v [ i ] [ curr ] ) return dp [ i ] [ curr ] ; v [ i ] [ curr ] = 1 ; return dp [ i ] [ curr ] = findCnt ( arr , i + 1 , curr , n , m ) + findCnt ( arr , i + 1 , ( curr + arr [ i ] ) % m , n , m ) ; } int main ( ) { int arr [ ] = { 3 , 3 , 3 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int m = 6 ; cout << findCnt ( arr , 0 , 0 , n , m ) - 1 ; return 0 ; } |
Longest subsequence with a given OR value : Dynamic Programming Approach | C ++ implementation of the approach ; To store the states of DP ; Function to return the required length ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxN 20 NEW_LINE #define maxM 64 NEW_LINE int dp [ maxN ] [ maxM ] ; bool v [ maxN ] [ maxM ] ; int findLen ( int * arr , int i , int curr , int n , int m ) { if ( i == n ) { if ( curr == m ) return 0 ; else return -1 ; } if ( v [ i ] [ curr ] ) return dp [ i ] [ curr ] ; v [ i ] [ curr ] = 1 ; int l = findLen ( arr , i + 1 , curr , n , m ) ; int r = findLen ( arr , i + 1 , curr arr [ i ] , n , m ) ; dp [ i ] [ curr ] = l ; if ( r != -1 ) dp [ i ] [ curr ] = max ( dp [ i ] [ curr ] , r + 1 ) ; return dp [ i ] [ curr ] ; } int main ( ) { int arr [ ] = { 3 , 7 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int m = 3 ; int ans = findLen ( arr , 0 , 0 , n , m ) ; if ( ans == -1 ) cout << 0 ; else cout << ans ; return 0 ; } |
Longest subsequence with a given AND value | C ++ implementation of the approach ; To store the states of DP ; Function to return the required length ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxN 20 NEW_LINE #define maxM 64 NEW_LINE int dp [ maxN ] [ maxM ] ; bool v [ maxN ] [ maxM ] ; int findLen ( int * arr , int i , int curr , int n , int m ) { if ( i == n ) { if ( curr == m ) return 0 ; else return -1 ; } if ( v [ i ] [ curr ] ) return dp [ i ] [ curr ] ; v [ i ] [ curr ] = 1 ; int l = findLen ( arr , i + 1 , curr , n , m ) ; int r = findLen ( arr , i + 1 , curr & arr [ i ] , n , m ) ; dp [ i ] [ curr ] = l ; if ( r != -1 ) dp [ i ] [ curr ] = max ( dp [ i ] [ curr ] , r + 1 ) ; return dp [ i ] [ curr ] ; } int main ( ) { int arr [ ] = { 3 , 7 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int m = 3 ; int ans = findLen ( arr , 0 , ( ( 1 << 8 ) - 1 ) , n , m ) ; if ( ans == -1 ) cout << 0 ; else cout << ans ; return 0 ; } |
Longest subsequence whose sum is divisible by a given number | C ++ implementation of the approach ; To store the states of DP ; Function to return the length of the longest subsequence whose sum is divisible by m ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxN 20 NEW_LINE #define maxM 64 NEW_LINE int dp [ maxN ] [ maxM ] ; bool v [ maxN ] [ maxM ] ; int findLen ( int * arr , int i , int curr , int n , int m ) { if ( i == n ) { if ( ! curr ) return 0 ; else return -1 ; } if ( v [ i ] [ curr ] ) return dp [ i ] [ curr ] ; v [ i ] [ curr ] = 1 ; int l = findLen ( arr , i + 1 , curr , n , m ) ; int r = findLen ( arr , i + 1 , ( curr + arr [ i ] ) % m , n , m ) ; dp [ i ] [ curr ] = l ; if ( r != -1 ) dp [ i ] [ curr ] = max ( dp [ i ] [ curr ] , r + 1 ) ; return dp [ i ] [ curr ] ; } int main ( ) { int arr [ ] = { 3 , 2 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int m = 3 ; cout << findLen ( arr , 0 , 0 , n , m ) ; return 0 ; } |
Count of subsets with sum equal to X | C ++ implementation of the approach ; To store the states of DP ; Function to return the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxN 20 NEW_LINE #define maxSum 50 NEW_LINE #define minSum 50 NEW_LINE #define base 50 NEW_LINE int dp [ maxN ] [ maxSum + minSum ] ; bool v [ maxN ] [ maxSum + minSum ] ; int findCnt ( int * arr , int i , int required_sum , int n ) { if ( i == n ) { if ( required_sum == 0 ) return 1 ; else return 0 ; } if ( v [ i ] [ required_sum + base ] ) return dp [ i ] [ required_sum + base ] ; v [ i ] [ required_sum + base ] = 1 ; dp [ i ] [ required_sum + base ] = findCnt ( arr , i + 1 , required_sum , n ) + findCnt ( arr , i + 1 , required_sum - arr [ i ] , n ) ; return dp [ i ] [ required_sum + base ] ; } int main ( ) { int arr [ ] = { 3 , 3 , 3 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int x = 6 ; cout << findCnt ( arr , 0 , x , n ) ; return 0 ; } |
Number of subsets with a given OR value | C ++ implementation of the approach ; To store states of DP ; Function to return the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxN 20 NEW_LINE #define maxM 64 NEW_LINE int dp [ maxN ] [ maxM ] ; bool v [ maxN ] [ maxM ] ; int findCnt ( int * arr , int i , int curr , int n , int m ) { if ( i == n ) { return ( curr == m ) ; } if ( v [ i ] [ curr ] ) return dp [ i ] [ curr ] ; v [ i ] [ curr ] = 1 ; dp [ i ] [ curr ] = findCnt ( arr , i + 1 , curr , n , m ) + findCnt ( arr , i + 1 , ( curr arr [ i ] ) , n , m ) ; return dp [ i ] [ curr ] ; } int main ( ) { int arr [ ] = { 2 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int m = 3 ; cout << findCnt ( arr , 0 , 0 , n , m ) ; return 0 ; } |
Number of subsets with a given AND value | C ++ implementation of the approach ; To store states of DP ; Function to return the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxN 20 NEW_LINE #define maxM 64 NEW_LINE int dp1 [ maxN ] [ maxM ] ; bool v1 [ maxN ] [ maxM ] ; int findCnt ( int * arr , int i , int curr , int n , int m ) { if ( i == n ) { return ( curr == m ) ; } if ( v1 [ i ] [ curr ] ) return dp1 [ i ] [ curr ] ; v1 [ i ] [ curr ] = 1 ; dp1 [ i ] [ curr ] = findCnt ( arr , i + 1 , curr , n , m ) + findCnt ( arr , i + 1 , ( curr & arr [ i ] ) , n , m ) ; return dp1 [ i ] [ curr ] ; } int main ( ) { int arr [ ] = { 0 , 0 , 0 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int m = 0 ; cout << findCnt ( arr , 0 , ( ( 1 << 6 ) - 1 ) , n , m ) ; return 0 ; } |
Count of integers obtained by replacing ? in the given string that give remainder 5 when divided by 13 | C ++ implementation of the approach ; Function to find the count of integers obtained by replacing ' ? ' in a given string such that formed integer gives remainder 5 when it is divided by 13 ; Initialise ; Place digit j at ? position ; Get the remainder ; Return the required answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD (int)(1e9 + 7) NEW_LINE int modulo_13 ( string s , int n ) { long long dp [ n + 1 ] [ 13 ] = { { 0 } } ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { int nxt = s [ i ] - '0' ; if ( s [ i ] == ' ? ' ) nxt = j ; for ( int k = 0 ; k < 13 ; k ++ ) { int rem = ( 10 * k + nxt ) % 13 ; dp [ i + 1 ] [ rem ] += dp [ i ] [ k ] ; dp [ i + 1 ] [ rem ] %= MOD ; } if ( s [ i ] != ' ? ' ) break ; } } return ( int ) dp [ n ] [ 5 ] ; } int main ( ) { string s = " ? 44" ; int n = s . size ( ) ; cout << modulo_13 ( s , n ) ; return 0 ; } |
Longest Increasing Subsequence using Longest Common Subsequence Algorithm | C ++ implementation of the approach ; Function to return the size of the longest increasing subsequence ; Create an 2D array of integer for tabulation ; Take the second sequence as the sorted sequence of the given sequence ; Classical Dynamic Programming algorithm for Longest Common Subsequence ; Return the ans ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int LISusingLCS ( vector < int > & seq ) { int n = seq . size ( ) ; vector < vector < int > > L ( n + 1 , vector < int > ( n + 1 ) ) ; vector < int > sortedseq ( seq ) ; sort ( sortedseq . begin ( ) , sortedseq . end ( ) ) ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( seq [ i - 1 ] == sortedseq [ j - 1 ] ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; else L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } return L [ n ] [ n ] ; } int main ( ) { vector < int > sequence { 12 , 34 , 1 , 5 , 40 , 80 } ; cout << LISusingLCS ( sequence ) << endl ; return 0 ; } |
Count of N | C ++ implementation of the approach ; Function to return the count of n - digit numbers that satisfy the given conditions ; Base case ; If 0 wasn 't chosen previously ; If 0 wasn 't chosen previously ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count_numbers ( int k , int n , bool flag ) { if ( n == 1 ) { if ( flag ) { return ( k - 1 ) ; } else { return 1 ; } } if ( flag ) return ( k - 1 ) * ( count_numbers ( k , n - 1 , 0 ) + count_numbers ( k , n - 1 , 1 ) ) ; else return count_numbers ( k , n - 1 , 1 ) ; } int main ( ) { int n = 3 ; int k = 10 ; cout << count_numbers ( k , n , true ) ; return 0 ; } |
Count of N | C ++ implementation of the approach ; Function to return the count of n - digit numbers that satisfy the given conditions ; DP array to store the pre - caluclated states ; Base cases ; i - digit numbers ending with 0 can be formed by concatenating 0 in the end of all the ( i - 1 ) - digit number ending at a non - zero digit ; i - digit numbers ending with non - zero can be formed by concatenating any non - zero digit in the end of all the ( i - 1 ) - digit number ending with any digit ; n - digit number ending with and ending with non - zero ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count_numbers ( int k , int n ) { int dp [ n + 1 ] [ 2 ] ; dp [ 1 ] [ 0 ] = 0 ; dp [ 1 ] [ 1 ] = k - 1 ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 1 ] ; dp [ i ] [ 1 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] ) * ( k - 1 ) ; } return dp [ n ] [ 0 ] + dp [ n ] [ 1 ] ; } int main ( ) { int k = 10 ; int n = 3 ; cout << count_numbers ( k , n ) ; return 0 ; } |
Divide an array into K subarray with the given condition | C ++ implementation of the above approach ; Function to divide an array into k parts such that the sum of difference of every element with the maximum element of that part is minimum ; Dp to store the values ; Fill up the dp table ; Intitilize maximum value ; Max element and the sum ; Run a loop from i to n ; Find the maximum number from i to l and the sum from i to l ; Find the sum of difference of every element with the maximum element ; If the array can be divided ; Returns the minimum sum in K parts ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int divideArray ( int arr [ ] , int n , int k ) { int dp [ 500 ] [ 500 ] = { 0 } ; k -= 1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { for ( int j = 0 ; j <= k ; j ++ ) { dp [ i ] [ j ] = INT_MAX ; int max_ = -1 , sum = 0 ; for ( int l = i ; l < n ; l ++ ) { max_ = max ( max_ , arr [ l ] ) ; sum += arr [ l ] ; int diff = ( l - i + 1 ) * max_ - sum ; if ( j > 0 ) dp [ i ] [ j ] = min ( dp [ i ] [ j ] , diff + dp [ l + 1 ] [ j - 1 ] ) ; else dp [ i ] [ j ] = diff ; } } } return dp [ 0 ] [ k ] ; } int main ( ) { int arr [ ] = { 2 , 9 , 5 , 4 , 8 , 3 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 2 ; cout << divideArray ( arr , n , k ) << " STRNEWLINE " ; return 0 ; } |
Count of subsets not containing adjacent elements | C ++ implementation of the approach ; Function to return the count of possible subsets ; Total possible subsets of n sized array is ( 2 ^ n - 1 ) ; To store the required count of subsets ; Run from i 000. .0 to 111. .1 ; If current subset has consecutive elements from the array ; Driver code | #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int cntSubsets ( int * arr , int n ) { unsigned int max = pow ( 2 , n ) ; int result = 0 ; for ( int i = 0 ; i < max ; i ++ ) { int counter = i ; if ( counter & ( counter >> 1 ) ) continue ; result ++ ; } return result ; } int main ( ) { int arr [ ] = { 3 , 5 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntSubsets ( arr , n ) ; return 0 ; } |
Count of subsets not containing adjacent elements | C ++ implementation of the approach ; Function to return the count of possible subsets ; If previous element was 0 then 0 as well as 1 can be appended ; If previous element was 1 then only 0 can be appended ; Store the count of all possible subsets ; Driver code | #include <iostream> NEW_LINE using namespace std ; int cntSubsets ( int * arr , int n ) { int a [ n ] , b [ n ] ; a [ 0 ] = b [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { a [ i ] = a [ i - 1 ] + b [ i - 1 ] ; b [ i ] = a [ i - 1 ] ; } int result = a [ n - 1 ] + b [ n - 1 ] ; return result ; } int main ( ) { int arr [ ] = { 3 , 5 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntSubsets ( arr , n ) ; return 0 ; } |
Maximum perimeter of a square in a 2D grid | C ++ implementation of the approach ; Function to calculate the perfix sum of the rows and the columns of the given matrix ; Number of rows and cols ; First column of the row prefix array ; Update the prefix sum for the rows ; First row of the column prefix array ; Update the prefix sum for the columns ; Function to return the perimeter of the square having top - left corner at ( i , j ) and size k ; i and j represent the top left corner of the square and k is the size ; Get the upper row sum ; Get the left column sum ; At the distance of k in both direction ; The perimeter will be sum of all the values ; Since all the corners are included twice , they need to be subtract from the sum ; Function to return the maximum perimeter of a square in the given matrix ; Number of rows and cols ; Function call to calculate the prefix sum of rows and cols ; To store the maximum perimeter ; Nested loops to choose the top - left corner of the square ; Loop for the size of the square ; Get the perimeter of the current square ; Update the maximum perimeter so far ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void perfix_calculate ( vector < vector < int > > & A , vector < vector < int > > & row , vector < vector < int > > & col ) { int n = ( int ) A . size ( ) ; int m = ( int ) A [ 0 ] . size ( ) ; for ( int i = 0 ; i < n ; ++ i ) { row [ i ] [ 0 ] = A [ i ] [ 0 ] ; } for ( int i = 0 ; i < n ; ++ i ) { for ( int j = 1 ; j < m ; ++ j ) { row [ i ] [ j ] = row [ i ] [ j - 1 ] + A [ i ] [ j ] ; } } for ( int i = 0 ; i < m ; ++ i ) { col [ 0 ] [ i ] = A [ 0 ] [ i ] ; } for ( int i = 0 ; i < m ; ++ i ) { for ( int j = 1 ; j < n ; ++ j ) { col [ j ] [ i ] = A [ j ] [ i ] + col [ j - 1 ] [ i ] ; } } } int perimeter ( int i , int j , int k , vector < vector < int > > & row , vector < vector < int > > & col , vector < vector < int > > & A ) { int row_s , col_s ; if ( j == 0 ) row_s = 0 ; else row_s = row [ i ] [ j - 1 ] ; if ( i == 0 ) col_s = 0 ; else col_s = col [ i - 1 ] [ j ] ; int upper_row = row [ i ] [ j + k ] - row_s ; int left_col = col [ i + k ] [ j ] - col_s ; if ( j == 0 ) row_s = 0 ; else row_s = row [ i + k ] [ j - 1 ] ; if ( i == 0 ) col_s = 0 ; else col_s = col [ i - 1 ] [ j + k ] ; int lower_row = row [ i + k ] [ j + k ] - row_s ; int right_col = col [ i + k ] [ j + k ] - col_s ; int sum = upper_row + lower_row + left_col + right_col ; sum -= ( A [ i ] [ j ] + A [ i + k ] [ j ] + A [ i ] [ j + k ] + A [ i + k ] [ j + k ] ) ; return sum ; } int maxPerimeter ( vector < vector < int > > & A ) { int n = ( int ) A . size ( ) ; int m = ( int ) A [ 0 ] . size ( ) ; vector < vector < int > > row ( n , vector < int > ( m , 0 ) ) ; vector < vector < int > > col ( n , vector < int > ( m , 0 ) ) ; perfix_calculate ( A , row , col ) ; int maxPer = 0 ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = 0 ; j < m ; ++ j ) { for ( int k = 0 ; k < min ( n - i , m - j ) ; ++ k ) { int perimtr = perimeter ( i , j , k , row , col , A ) ; maxPer = max ( maxPer , perimtr ) ; } } } return maxPer ; } int main ( ) { vector < vector < int > > A = { { 1 , 1 , 0 } , { 1 , 1 , 1 } , { 0 , 1 , 1 } } ; cout << maxPerimeter ( A ) ; return 0 ; } |
Optimal Strategy for a Game | Set 3 | C ++ implementation ; Calculates the maximum score possible for P1 If only the bags from beg to ed were available ; Length of the game ; Which turn is being played ; Base case i . e last turn ; if it is P1 's turn ; if P2 's turn ; Player picks money from the left end ; Player picks money from the right end ; if it is player 1 's turn then current picked score added to his total. choose maximum of the two scores as P1 tries to maximize his score. ; if player 2 ' s β turn β don ' t add current picked bag score to total . choose minimum of the two scores as P2 tries to minimize P1 's score. ; Driver Code ; Input array ; Function Calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; pair < int , string > maxScore ( vector < int > money , int beg , int ed ) { int totalTurns = money . size ( ) ; int turnsTillNow = beg + ( ( totalTurns - 1 ) - ed ) ; if ( beg == ed ) { if ( turnsTillNow % 2 == 0 ) return { money [ beg ] , " L " } ; else return { 0 , " L " } ; } pair < int , string > scoreOne = maxScore ( money , beg + 1 , ed ) ; pair < int , string > scoreTwo = maxScore ( money , beg , ed - 1 ) ; if ( turnsTillNow % 2 == 0 ) { if ( money [ beg ] + scoreOne . first > money [ ed ] + scoreTwo . first ) { return { money [ beg ] + scoreOne . first , " L " + scoreOne . second } ; } else return { money [ ed ] + scoreTwo . first , " R " + scoreTwo . second } ; } else { if ( scoreOne . first < scoreTwo . first ) return { scoreOne . first , " L " + scoreOne . second } ; else return { scoreTwo . first , " R " + scoreTwo . second } ; } } int main ( ) { int ar [ ] = { 10 , 80 , 90 , 30 } ; int arraySize = sizeof ( ar ) / sizeof ( int ) ; vector < int > bags ( ar , ar + arraySize ) ; pair < int , string > ans = maxScore ( bags , 0 , bags . size ( ) - 1 ) ; cout << ans . first << " β " << ans . second << endl ; return 0 ; } |
Minimum number of Fibonacci jumps to reach end | A Dynamic Programming based C ++ program to find minimum number of jumps to reach Destination ; Function that returns the min number of jump to reach the destination ; We consider only those Fibonacci numbers which are less than n , where we can consider fib [ 30 ] to be the upper bound as this will cross 10 ^ 5 ; DP [ i ] will be storing the minimum number of jumps required for the position i . So DP [ N + 1 ] will have the result we consider 0 as source and N + 1 as the destination ; Base case ( Steps to reach source is ) ; Initialize all table values as Infinite ; Go through each positions till destination . ; Calculate the minimum of that position if all the Fibonacci numbers are considered ; If the position is safe or the position is the destination then only we calculate the minimum otherwise the cost is MAX as default ; - 1 denotes if there is no path possible ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1e9 NEW_LINE int minJumps ( int arr [ ] , int N ) { int fib [ 30 ] ; fib [ 0 ] = 0 ; fib [ 1 ] = 1 ; for ( int i = 2 ; i < 30 ; i ++ ) fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] ; int DP [ N + 2 ] ; DP [ 0 ] = 0 ; for ( int i = 1 ; i <= N + 1 ; i ++ ) DP [ i ] = MAX ; for ( int i = 1 ; i <= N + 1 ; i ++ ) { for ( int j = 1 ; j < 30 ; j ++ ) { if ( ( arr [ i - 1 ] == 1 i == N + 1 ) && i - fib [ j ] >= 0 ) DP [ i ] = min ( DP [ i ] , 1 + DP [ i - fib [ j ] ] ) ; } } if ( DP [ N + 1 ] != MAX ) return DP [ N + 1 ] ; else return -1 ; } int main ( ) { int arr [ ] = { 0 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 0 , 0 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minJumps ( arr , n ) ; return 0 ; } |
Subsequence X of length K such that gcd ( X [ 0 ] , X [ 1 ] ) + ( X [ 2 ] , X [ 3 ] ) + ... is maximized | C ++ program to find the sum of the addition of all possible subsets ; Recursive function to find the maximum value of the given recurrence ; If we get K elements ; If we have reached the end and K elements are not there ; If the state has been visited ; Iterate for every element as the next possible element and take the element which gives the maximum answer ; If this element is the first element in the individual pair in the subsequence then simply recurrence with the last element as i - th index ; If this element is the second element in the individual pair , the find gcd with the previous element and add to the answer and recur for the next element ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; int recur ( int ind , int cnt , int last , int a [ ] , int n , int k , int dp [ ] [ MAX ] ) { if ( cnt == k ) return 0 ; if ( ind == n ) return -1e9 ; if ( dp [ ind ] [ cnt ] != -1 ) return dp [ ind ] [ cnt ] ; int ans = 0 ; for ( int i = ind ; i < n ; i ++ ) { if ( cnt % 2 == 0 ) ans = max ( ans , recur ( i + 1 , cnt + 1 , i , a , n , k , dp ) ) ; else ans = max ( ans , __gcd ( a [ last ] , a [ i ] ) + recur ( i + 1 , cnt + 1 , 0 , a , n , k , dp ) ) ; } return dp [ ind ] [ cnt ] = ans ; } int main ( ) { int a [ ] = { 4 , 5 , 3 , 7 , 8 , 10 , 9 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 4 ; int dp [ n ] [ MAX ] ; memset ( dp , -1 , sizeof dp ) ; cout << recur ( 0 , 0 , 0 , a , n , k , dp ) ; } |
Maximum number of given operations to remove the entire string | C ++ implementation of the approach ; Function to return the maximum number of given operations required to remove the given string entirely ; If length of the string is zero ; Single operation can delete the entire string ; To store the prefix of the string which is to be deleted ; Prefix s [ 0. . i ] ; To store the substring s [ i + 1. . .2 * i + 1 ] ; If the prefix s [ 0. . . i ] can be deleted ; 1 operation to remove the current prefix and then recursively find the count of operations for the substring s [ i + 1. . . n - 1 ] ; Entire string has to be deleted ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( string s ) { if ( s . length ( ) == 0 ) return 0 ; int c = 1 ; string d = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { d += s [ i ] ; string s2 = s . substr ( i + 1 , d . length ( ) ) ; if ( s2 == d ) { c = 1 + find ( s . substr ( i + 1 ) ) ; break ; } } return c ; } int main ( ) { string s = " abababab " ; cout << find ( s ) ; return 0 ; } |
Sum of the distances from every node to all other nodes is maximum | C ++ program to implement the above approach ; Function to add an edge to the tree ; Function to run DFS and calculate the height of the subtree below it ; Initially initialize with 1 ; Traverse for all nodes connected to node ; If node is not parent then recall dfs ; Add the size of the subtree beneath it ; Function to assign weights to edges to maximize the final sum ; Initialize it which stores the height of the subtree beneath it ; Call the DFS function to ; Sort the given array ; Stores the number of times an edge is part of a path ; Iterate for all edges and find the number of nodes on the left and on the right ; Node 1 ; Node 2 ; If the number of nodes below is less then the other will be n - dp [ node ] ; Second condition ; Sort the number of times an edges occurs in the path ; Find the summation of all those paths and return ; Driver code ; Add an edge 1 - 2 in the tree ; Add an edge 2 - 3 in the tree ; Add an edge 3 - 4 in the tree ; Add an edge 3 - 5 in the tree ; Array which gives the edges weight to be assigned | #include <bits/stdc++.h> NEW_LINE using namespace std ; void addEdge ( vector < pair < int , int > > & edges , list < int > * tree , int x , int y ) { edges . push_back ( { x , y } ) ; tree [ x ] . push_back ( y ) ; tree [ y ] . push_back ( x ) ; } void dfs ( vector < pair < int , int > > & edges , list < int > * tree , int node , int parent , int dp [ ] ) { dp [ node ] = 1 ; for ( auto it : tree [ node ] ) { if ( it != parent ) { dfs ( edges , tree , it , node , dp ) ; dp [ node ] += dp [ it ] ; } } } int maximizeSum ( int a [ ] , vector < pair < int , int > > & edges , list < int > * tree , int n ) { int dp [ n + 1 ] = { 0 } ; dfs ( edges , tree , 1 , 0 , dp ) ; sort ( a , a + ( n - 1 ) ) ; vector < int > ans ; for ( auto it : edges ) { int x = it . first ; int y = it . second ; if ( dp [ x ] < dp [ y ] ) { int fi = dp [ x ] ; int sec = n - dp [ x ] ; ans . push_back ( fi * sec ) ; } else { int fi = dp [ y ] ; int sec = n - dp [ y ] ; ans . push_back ( fi * sec ) ; } } sort ( ans . begin ( ) , ans . end ( ) ) ; int res = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { res += ans [ i ] * a [ i ] ; } return res ; } int main ( ) { int n = 5 ; vector < pair < int , int > > edges ; list < int > * tree = new list < int > [ n + 1 ] ; addEdge ( edges , tree , 1 , 2 ) ; addEdge ( edges , tree , 1 , 3 ) ; addEdge ( edges , tree , 3 , 4 ) ; addEdge ( edges , tree , 3 , 5 ) ; int a [ ] = { 6 , 3 , 1 , 9 , 3 } ; cout << maximizeSum ( a , edges , tree , n ) ; } |
Divide the array in K segments such that the sum of minimums is maximized | C ++ program to find the sum of the minimum of all the segments ; Function to maximize the sum of the minimums ; If k segments have been divided ; If we are at the end ; If we donot reach the end then return a negative number that cannot be the sum ; If at the end but k segments are not formed ; If the state has not been visited yet ; If the state has not been visited ; Get the minimum element in the segment ; Iterate and try to break at every index and create a segment ; Find the minimum element in the segment ; Find the sum of all the segments trying all the possible combinations ; Return the answer by memoizing it ; Driver Code ; Initialize dp array with - 1 | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 10 ; int maximizeSum ( int a [ ] , int n , int ind , int k , int dp [ MAX ] [ MAX ] ) { if ( k == 0 ) { if ( ind == n ) return 0 ; else return -1e9 ; } else if ( ind == n ) return -1e9 ; else if ( dp [ ind ] [ k ] != -1 ) return dp [ ind ] [ k ] ; else { int ans = 0 ; int mini = a [ ind ] ; for ( int i = ind ; i < n ; i ++ ) { mini = min ( mini , a [ i ] ) ; ans = max ( ans , maximizeSum ( a , n , i + 1 , k - 1 , dp ) + mini ) ; } return dp [ ind ] [ k ] = ans ; } } int main ( ) { int a [ ] = { 5 , 7 , 4 , 2 , 8 , 1 , 6 } ; int k = 3 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int dp [ MAX ] [ MAX ] ; memset ( dp , -1 , sizeof dp ) ; cout << maximizeSum ( a , n , 0 , k , dp ) ; return 0 ; } |
Mobile Numeric Keypad Problem | Set 2 | C ++ implementation of the approach ; Function to return the count of numbers possible ; Array of list storing possible direction for each number from 0 to 9 mylist [ i ] stores possible moves from index i ; Initializing list ; Storing values for n = 1 ; To store the values for n = i ; Loop to iterate through each index ; For each move possible from j Increment the value of possible move positions by Arr [ j ] ; Update Arr [ ] for next iteration ; Find the count of numbers possible ; Driver code | #include <iostream> NEW_LINE #include <list> NEW_LINE using namespace std ; #define MAX 10 NEW_LINE int getCount ( int n ) { list < int > mylist [ MAX ] ; mylist [ 0 ] . assign ( { 0 , 8 } ) ; mylist [ 1 ] . assign ( { 1 , 2 , 4 } ) ; mylist [ 2 ] . assign ( { 2 , 1 , 3 , 5 } ) ; mylist [ 3 ] . assign ( { 3 , 6 , 2 } ) ; mylist [ 4 ] . assign ( { 4 , 1 , 7 , 5 } ) ; mylist [ 5 ] . assign ( { 5 , 4 , 6 , 2 , 8 } ) ; mylist [ 6 ] . assign ( { 6 , 3 , 5 , 9 } ) ; mylist [ 7 ] . assign ( { 7 , 4 , 8 } ) ; mylist [ 8 ] . assign ( { 8 , 5 , 0 , 7 , 9 } ) ; mylist [ 9 ] . assign ( { 9 , 6 , 8 } ) ; int Arr [ MAX ] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } ; for ( int i = 2 ; i <= n ; i ++ ) { int Arr2 [ MAX ] = { 0 } ; for ( int j = 0 ; j < MAX ; j ++ ) { for ( int x : mylist [ j ] ) { Arr2 [ x ] += Arr [ j ] ; } } for ( int j = 0 ; j < MAX ; j ++ ) Arr [ j ] = Arr2 [ j ] ; } int sum = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) sum += Arr [ i ] ; return sum ; } int main ( ) { int n = 2 ; cout << getCount ( n ) ; return 0 ; } |
Optimally accommodate 0 s and 1 s from a Binary String into K buckets | C ++ implementation of the approach ; 2 - D dp array saving different states dp [ i ] [ j ] = minimum value of accommodation till i 'th index of the string using j+1 number of buckets. ; Function to find the minimum required sum using dynamic programming ; If both start and bucket reached end then return 0 else that arrangement is not possible so return INT_MAX ; Corner case ; If state if already calculated then return its answer ; Start filling zeroes and ones which to be accommodated in jth bucket then ans for current arrangement will be ones * zeroes + recur ( i + 1 , bucket + 1 ) ; If this arrangement is not possible then don 't calculate further ; Function to initialize the dp and call solveUtil ( ) method to get the answer ; Start with 0 - th index and 1 bucket ; Driver code ; K buckets | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > dp ; int solveUtil ( int start , int bucket , string str , int K ) { int N = str . size ( ) ; if ( start == N ) { if ( bucket == K ) return 0 ; return INT_MAX ; } if ( bucket == K ) return INT_MAX ; if ( dp [ start ] [ bucket ] != -1 ) return dp [ start ] [ bucket ] ; int zeroes = 0 ; int ones = 0 ; int ans = INT_MAX ; for ( int i = start ; i < N ; ++ i ) { if ( str [ i ] == '1' ) ones ++ ; else zeroes ++ ; if ( ones * zeroes > ans ) break ; int temp = solveUtil ( i + 1 , bucket + 1 , str , K ) ; if ( temp != INT_MAX ) { ans = min ( ans , temp + ( ones * zeroes ) ) ; } } return dp [ start ] [ bucket ] = ans ; } int solve ( string str , int K ) { int N = str . size ( ) ; dp . clear ( ) ; dp . resize ( N , vector < int > ( K , -1 ) ) ; int ans = solveUtil ( 0 , 0 , str , K ) ; return ans == INT_MAX ? -1 : ans ; } int main ( ) { string S = "0101" ; int K = 2 ; cout << solve ( S , K ) << endl ; return 0 ; } |
Probability of getting more heads than tails when N biased coins are tossed | C ++ implementation of the above approach ; Function to return the probability when number of heads is greater than the number of tails ; Declaring the DP table ; Base case ; Iterating for every coin ; j represents the numbers of heads ; If number of heads is equal to zero there there is only one possibility ; When the number of heads is greater than ( n + 1 ) / 2 it means that heads are greater than tails as no of tails + no of heads is equal to n for any permutation of heads and tails ; Driver Code ; 1 based indexing ; Number of coins ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; double Probability ( double p [ ] , int n ) { double dp [ n + 1 ] [ n + 1 ] ; memset ( dp , 0.0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = 1.0 ; for ( int i = 1 ; i <= n ; i += 1 ) { for ( int j = 0 ; j <= i ; j += 1 ) { if ( j == 0 ) dp [ i ] [ j ] = dp [ i - 1 ] [ j ] * ( 1.0 - p [ i ] ) ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j ] * ( 1.0 - p [ i ] ) + dp [ i - 1 ] [ j - 1 ] * p [ i ] ; } } double ans = 0.0 ; for ( int i = ( n + 1 ) / 2 ; i <= n ; i += 1 ) ans += dp [ n ] [ i ] ; return ans ; } int main ( ) { double p [ ] = { 0.0 , 0.3 , 0.4 , 0.7 } ; int n = sizeof ( p ) / sizeof ( p [ 0 ] ) - 1 ; cout << Probability ( p , n ) ; return 0 ; } |
Number of ways to get a given sum with n number of m | C ++ function to calculate the number of ways to achieve sum x in n no of throws ; Function to calculate recursively the number of ways to get sum in given throws and [ 1. . m ] values ; Base condition 1 ; Base condition 2 ; If value already calculated dont move into re - computation ; Recursively moving for sum - i in throws - 1 no of throws left ; Inserting present values in dp ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod 1000000007 NEW_LINE int dp [ 55 ] [ 55 ] ; int NoofWays ( int face , int throws , int sum ) { if ( sum == 0 && throws == 0 ) return 1 ; if ( sum < 0 throws == 0 ) return 0 ; if ( dp [ throws ] [ sum ] != -1 ) return dp [ throws ] [ sum ] ; int ans = 0 ; for ( int i = 1 ; i <= face ; i ++ ) { ans += NoofWays ( face , throws - 1 , sum - i ) ; } return dp [ throws ] [ sum ] = ans ; } int main ( ) { int faces = 6 , throws = 3 , sum = 12 ; memset ( dp , -1 , sizeof dp ) ; cout << NoofWays ( faces , throws , sum ) << endl ; return 0 ; } |
Maximize the happiness of the groups on the Trip | C ++ implementation of the approach ; Function to return the maximized happiness ; Two arrays similar to 0 1 knapsack problem ; To store the happiness of the current group ; Current person is a child ; Woman ; Man ; Old person ; Group 's happiness is the sum of happiness of the people in the group multiplied by the number of people ; Solution using 0 1 knapsack ; Driver code ; Number of seats ; Groups | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxHappiness ( int A , int N , vector < string > v ) { string str ; int val [ N ] , wt [ N ] , c = 0 ; for ( int i = 0 ; i < N ; i ++ ) { str = v [ i ] ; c = 0 ; for ( int j = 0 ; str [ j ] ; j ++ ) { if ( str [ j ] == ' c ' ) c += 4 ; else if ( str [ j ] == ' w ' ) c += 3 ; else if ( str [ j ] == ' m ' ) c += 2 ; else c ++ ; } c *= str . length ( ) ; val [ i ] = c ; wt [ i ] = str . length ( ) ; } int k [ N + 1 ] [ A + 1 ] ; for ( int i = 0 ; i <= N ; i ++ ) { for ( int w = 0 ; w <= A ; w ++ ) { if ( i == 0 w == 0 ) k [ i ] [ w ] = 0 ; else if ( wt [ i - 1 ] <= w ) k [ i ] [ w ] = max ( val [ i - 1 ] + k [ i - 1 ] [ w - wt [ i - 1 ] ] , k [ i - 1 ] [ w ] ) ; else k [ i ] [ w ] = k [ i - 1 ] [ w ] ; } } return k [ N ] [ A ] ; } int main ( ) { int A = 5 ; vector < string > v = { " mmo " , " oo " , " cmw " , " cc " , " c " } ; int N = v . size ( ) ; cout << MaxHappiness ( A , N , v ) ; return 0 ; } |
0 | C ++ implementation of the approach ; To store states of DP ; To check if a state has been solved ; Function to compute the states ; Base case ; Check if a state has been solved ; Setting a state as solved ; Returning the solved state ; Function to pre - compute the states dp [ 0 ] [ 0 ] , dp [ 0 ] [ 1 ] , . . , dp [ 0 ] [ C_MAX ] ; Function to answer a query in O ( 1 ) ; Driver code ; Performing required pre - computation ; Perform queries | #include <bits/stdc++.h> NEW_LINE #define C_MAX 30 NEW_LINE #define max_arr_len 10 NEW_LINE using namespace std ; int dp [ max_arr_len ] [ C_MAX + 1 ] ; bool v [ max_arr_len ] [ C_MAX + 1 ] ; int findMax ( int i , int r , int w [ ] , int n ) { if ( r < 0 ) return INT_MIN ; if ( i == n ) return 0 ; if ( v [ i ] [ r ] ) return dp [ i ] [ r ] ; v [ i ] [ r ] = 1 ; dp [ i ] [ r ] = max ( w [ i ] + findMax ( i + 1 , r - w [ i ] , w , n ) , findMax ( i + 1 , r , w , n ) ) ; return dp [ i ] [ r ] ; } void preCompute ( int w [ ] , int n ) { for ( int i = C_MAX ; i >= 0 ; i -- ) findMax ( 0 , i , w , n ) ; } int ansQuery ( int w ) { return dp [ 0 ] [ w ] ; } int main ( ) { int w [ ] = { 3 , 8 , 9 } ; int n = sizeof ( w ) / sizeof ( int ) ; preCompute ( w , n ) ; int queries [ ] = { 11 , 10 , 4 } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) cout << ansQuery ( queries [ i ] ) << endl ; return 0 ; } |
Maximise array sum after taking non | C ++ implementation of the approach ; To store the states of dp ; To check if a given state has been solved ; To store the prefix - sum ; Function to fill the prefix_sum [ ] with the prefix sum of the given array ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Required recurrence relation ; Returning the value ; Driver code ; Finding prefix - sum ; Finding the maximum possible sum | #include <bits/stdc++.h> NEW_LINE #define maxLen 10 NEW_LINE using namespace std ; int dp [ maxLen ] ; bool v [ maxLen ] ; int prefix_sum [ maxLen ] ; void findPrefixSum ( int arr [ ] , int n ) { prefix_sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix_sum [ i ] = arr [ i ] + prefix_sum [ i - 1 ] ; } int maxSum ( int arr [ ] , int i , int n , int k ) { if ( i + k > n ) return 0 ; if ( v [ i ] ) return dp [ i ] ; v [ i ] = 1 ; int x ; if ( i == 0 ) x = prefix_sum [ k - 1 ] ; else x = prefix_sum [ i + k - 1 ] - prefix_sum [ i - 1 ] ; dp [ i ] = max ( maxSum ( arr , i + 1 , n , k ) , x + maxSum ( arr , i + k + 1 , n , k ) ) ; return dp [ i ] ; } int main ( ) { int arr [ ] = { 1 , 3 , 7 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 1 ; findPrefixSum ( arr , n ) ; cout << maxSum ( arr , 0 , n , k ) ; return 0 ; } |
Find maximum path sum in a 2D matrix when exactly two left moves are allowed | C ++ program to find maximum path sum in a 2D matrix when exactly two left moves are allowed ; Function to return the maximum path sum ; Copy last column i . e . starting and ending columns in another array ; Calculate suffix sum in each row ; Select the path we are going to follow ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define N 3 NEW_LINE #define M 3 NEW_LINE using namespace std ; int findMaxSum ( int arr [ ] [ M ] ) { int sum = 0 ; int b [ N ] [ M ] ; for ( int i = 0 ; i < N ; i ++ ) { b [ i ] [ M - 1 ] = arr [ i ] [ M - 1 ] ; } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = M - 2 ; j >= 0 ; j -- ) { b [ i ] [ j ] = arr [ i ] [ j ] + b [ i ] [ j + 1 ] ; } } for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { sum = max ( sum , b [ i ] [ j ] + b [ i - 1 ] [ j ] ) ; b [ i ] [ j ] = max ( b [ i ] [ j ] , b [ i - 1 ] [ j ] + arr [ i ] [ j ] ) ; } } return sum ; } int main ( ) { int arr [ N ] [ M ] = { { 3 , 7 , 4 } , { 1 , 9 , 6 } , { 1 , 7 , 7 } } ; cout << findMaxSum ( arr ) << endl ; return 0 ; } |
Queries to check if string B exists as substring in string A | C ++ implementation of the approach ; Function to return the modular inverse using Fermat 's little theorem ; Function to generate hash ; To store prefix - sum of rolling hash ; Multiplier for different values of i ; Generating hash value for string b ; Generating prefix - sum of hash of a ; Function that returns true if the required sub - string in a is equal to b ; To store hash of required sub - string of A ; If i = 0 then requires hash value ; Required hash if i != 0 ; Comparing hash with hash of B ; Driver code ; Generating hash ; Queries ; Perform queries | #include <bits/stdc++.h> NEW_LINE #define mod 3803 NEW_LINE #define d 26 NEW_LINE using namespace std ; int hash_b ; int * hash_a ; int * mul ; int mi ( int x ) { int p = mod - 2 ; int s = 1 ; while ( p != 1 ) { if ( p % 2 == 1 ) s = ( s * x ) % mod ; x = ( x * x ) % mod ; p /= 2 ; } return ( s * x ) % mod ; } void genHash ( string & a , string & b ) { hash_a = new int [ a . size ( ) ] ; mul = new int [ a . size ( ) ] ; for ( int i = b . size ( ) - 1 ; i >= 0 ; i -- ) hash_b = ( hash_b * d + ( b [ i ] - 97 ) ) % mod ; mul [ 0 ] = 1 ; hash_a [ 0 ] = ( a [ 0 ] - 97 ) % mod ; for ( int i = 1 ; i < a . size ( ) ; i ++ ) { mul [ i ] = ( mul [ i - 1 ] * d ) % mod ; hash_a [ i ] = ( hash_a [ i - 1 ] + mul [ i ] * ( a [ i ] - 97 ) ) % mod ; } } bool checkEqual ( int i , int len_a , int len_b ) { int x ; if ( i == 0 ) x = hash_a [ len_b - 1 ] ; else { x = ( hash_a [ i + len_b - 1 ] - hash_a [ i - 1 ] + 2 * mod ) % mod ; x = ( x * mi ( mul [ i ] ) ) % mod ; } if ( x == hash_b ) return true ; return false ; } int main ( ) { string a = " abababababa " ; string b = " aba " ; genHash ( a , b ) ; int queries [ ] = { 0 , 1 , 2 , 3 } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) { if ( checkEqual ( queries [ i ] , a . size ( ) , b . size ( ) ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; } return 0 ; } |
Number of ways to divide an array into K equal sum sub | C ++ implementation of the approach ; Array to store the states of DP ; Array to check if a state has been solved before ; To store the sum of the array elements ; Function to find the sum of all the array elements ; Function to return the number of ways ; If sum is not divisible by k answer will be zero ; Base case ; To check if a state has been solved before ; Sum of all the numbers from the beginning of the array ; Setting the current state as solved ; Recurrence relation ; Returning solved state ; Driver code ; Function call to find the sum of the array elements ; Print the number of ways | #include <bits/stdc++.h> NEW_LINE #define max_size 20 NEW_LINE #define max_k 20 NEW_LINE using namespace std ; int dp [ max_size ] [ max_k ] ; bool v [ max_size ] [ max_k ] ; int sum = 0 ; void findSum ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; } int cntWays ( int arr [ ] , int i , int ck , int k , int n , int curr_sum ) { if ( sum % k != 0 ) return 0 ; if ( i != n and ck == k + 1 ) return 0 ; if ( i == n ) { if ( ck == k + 1 ) return 1 ; else return 0 ; } if ( v [ i ] [ ck ] ) return dp [ i ] [ ck ] ; curr_sum += arr [ i ] ; v [ i ] [ ck ] = 1 ; dp [ i ] [ ck ] = cntWays ( arr , i + 1 , ck , k , n , curr_sum ) ; if ( curr_sum == ( sum / k ) * ck ) dp [ i ] [ ck ] += cntWays ( arr , i + 1 , ck + 1 , k , n , curr_sum ) ; return dp [ i ] [ ck ] ; } int main ( ) { int arr [ ] = { 1 , -1 , 1 , -1 , 1 , -1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 2 ; findSum ( arr , n ) ; cout << cntWays ( arr , 0 , 1 , k , n , 0 ) ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.