text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Lexicographically Kth | C ++ program for the above approach ; Function to fill dp array ; Initialize all the entries with 0 ; Update dp [ 0 ] [ 0 ] to 1 ; Traverse the dp array ; Update the value of dp [ i ] [ j ] ; Recursive function to find the Kth lexicographical smallest string ; Handle the base cases ; If there are more than or equal to K strings which start with a , then the first character is ' a ' ; Otherwise the first character of the resultant string is ' b ' ; Function to find the Kth lexicographical smallest string ; Function call to fill the dp array ; Print the resultant string ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 30 ; void findNumString ( int X , int Y , int dp [ ] [ MAX ] ) { for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { dp [ i ] [ j ] = 0 ; } } dp [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i <= X ; ++ i ) { for ( int j = 0 ; j <= Y ; ++ j ) { if ( i > 0 ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j ] ; } if ( j > 0 ) { dp [ i ] [ j ] += dp [ i ] [ j - 1 ] ; } } } } string kthString ( int X , int Y , int K , int dp [ ] [ MAX ] ) { if ( X == 0 ) { return string ( Y , ' b ' ) ; } if ( Y == 0 ) { return string ( X , ' a ' ) ; } if ( K <= dp [ X - 1 ] [ Y ] ) { return string ( " a " ) + kthString ( X - 1 , Y , K , dp ) ; } else { return string ( " b " ) + kthString ( X , Y - 1 , K - dp [ X - 1 ] [ Y ] , dp ) ; } } void kthStringUtil ( int X , int Y , int K ) { int dp [ MAX ] [ MAX ] ; findNumString ( X , Y , dp ) ; cout << kthString ( X , Y , K , dp ) << ' ' ; } int main ( ) { int X = 4 ; int Y = 3 ; int K = 4 ; kthStringUtil ( X , Y , K ) ; return 0 ; }
Maximum Tip Calculator | C ++ program for the above approach ; Function that finds the maximum tips from the given arrays as per the given conditions ; Base Condition ; If both have non - zero count then return max element from both array ; Traverse first array , as y count has become 0 ; Traverse 2 nd array , as x count has become 0 ; Drive Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumTip ( vector < int > & arr1 , vector < int > & arr2 , int n , int x , int y ) { if ( n == 0 ) return 0 ; if ( x != 0 and y != 0 ) return max ( arr1 [ n - 1 ] + maximumTip ( arr1 , arr2 , n - 1 , x - 1 , y ) , arr2 [ n - 1 ] + maximumTip ( arr1 , arr2 , n - 1 , x , y - 1 ) ) ; if ( y == 0 ) return arr1 [ n - 1 ] + maximumTip ( arr1 , arr2 , n - 1 , x - 1 , y ) ; else return arr2 [ n - 1 ] + maximumTip ( arr1 , arr2 , n - 1 , x , y - 1 ) ; } int main ( ) { int N = 5 ; int X = 3 ; int Y = 3 ; vector < int > A = { 1 , 2 , 3 , 4 , 5 } ; vector < int > B = { 5 , 4 , 3 , 2 , 1 } ; cout << ( maximumTip ( A , B , N , X , Y ) ) ; }
Number of ways such that only K bars are visible from the left | C ++ program for the above approach ; Function to calculate the number of bars that are visible from the left for a particular arrangement ; If current element is greater than the last greater element , it is visible ; Function to calculate the number of rearrangements where K bars are visiblef from the left ; Vector to store current permutation ; Check for all permutations ; If current permutation meets the conditions , increment answer ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int noOfbarsVisibleFromLeft ( vector < int > v ) { int last = 0 , ans = 0 ; for ( auto u : v ) if ( last < u ) { ans ++ ; last = u ; } return ans ; } int KvisibleFromLeft ( int N , int K ) { vector < int > v ( N ) ; for ( int i = 0 ; i < N ; i ++ ) v [ i ] = i + 1 ; int ans = 0 ; do { if ( noOfbarsVisibleFromLeft ( v ) == K ) ans ++ ; } while ( next_permutation ( v . begin ( ) , v . end ( ) ) ) ; return ans ; } int main ( ) { int N = 5 , K = 2 ; cout << KvisibleFromLeft ( N , K ) << endl ; return 0 ; }
Number of ways such that only K bars are visible from the left | C ++ implementation for the above approach ; Function to calculate the number of permutations of N , where only K bars are visible from the left . ; Only ascending order is possible ; N is placed at the first position The nest N - 1 are arranged in ( N - 1 ) ! ways ; Recursing ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int KvisibleFromLeft ( int N , int K ) { if ( N == K ) return 1 ; if ( K == 1 ) { int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) ans *= i ; return ans ; } return KvisibleFromLeft ( N - 1 , K - 1 ) + ( N - 1 ) * KvisibleFromLeft ( N - 1 , K ) ; } int main ( ) { int N = 5 , K = 2 ; cout << KvisibleFromLeft ( N , K ) << endl ; return 0 ; }
Minimum deletions in Array to make difference of adjacent elements non | C ++ program for the above approach ; Function for finding minimum deletions so that the array becomes non decreasing and the difference between adjacent elements also becomes non decreasing ; initialize answer to a large value ; generating all subsets ; checking the first condition ; checking the second condition ; if both conditions are satisfied consider the answer for minimum ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumDeletions ( int A [ ] , int N ) { int ans = INT_MAX ; for ( int i = 1 ; i < ( 1 << N ) ; i ++ ) { vector < int > temp ; for ( int j = 0 ; j < N ; j ++ ) { if ( ( i & ( 1 << j ) ) != 0 ) { temp . push_back ( A [ j ] ) ; } } int flag = 0 ; for ( int j = 1 ; j < temp . size ( ) ; j ++ ) if ( temp [ j ] < temp [ j - 1 ] ) flag = 1 ; for ( int j = 1 ; j < temp . size ( ) - 1 ; j ++ ) if ( temp [ j ] - temp [ j - 1 ] > temp [ j + 1 ] - temp [ j ] ) flag = 1 ; if ( flag == 0 ) { ans = min ( ans , N - ( int ) temp . size ( ) ) ; } } return ans ; } int main ( ) { int A [ ] = { 1 , 4 , 5 , 7 , 20 , 21 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minimumDeletions ( A , N ) << endl ; return 0 ; }
Minimum deletions in Array to make difference of adjacent elements non | C ++ program for the above approach ; the maximum value of A [ i ] ; Function for finding minimum deletions so that the array becomes non - decreasing and the difference between adjacent elements is also non - decreasing ; initialize the dp table and set all values to 0 pref [ i ] [ j ] will contain min ( dp [ i ] [ 0 ] , dp [ i ] [ 1 ] , ... dp [ i ] [ j ] ) ; find the maximum sized valid set possible and then subtract its size from N to get minimum number of deletions ; when selecting only the current element and deleting all elements from 0 to i - 1 inclusive ; if this is true , moving from index j to i is possible ; we can get min ( dp [ j ] [ 0 ] , . . dp [ j ] ) from pref array ; ; construct the prefix array for this element ; take the max set size from dp [ N - 1 ] [ 0 ] to dp [ N - 1 ] [ MAX ] ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100001 NEW_LINE int minimumDeletions ( int A [ ] , int N ) { int dp [ N ] [ MAX ] ; int pref [ N ] [ MAX ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { dp [ i ] [ j ] = 0 ; pref [ i ] [ j ] = 0 ; } } for ( int i = 0 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = 1 ; for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( A [ i ] >= A [ j ] ) { int diff = A [ i ] - A [ j ] ; dp [ i ] = max ( dp [ i ] , pref [ j ] + 1 ) ; } } pref [ i ] [ 0 ] = dp [ i ] [ 0 ] ; for ( int j = 1 ; j < MAX ; j ++ ) pref [ i ] [ j ] = max ( dp [ i ] [ j ] , pref [ i ] [ j - 1 ] ) ; } int maxSetSize = -1 ; for ( int i = 0 ; i < MAX ; i ++ ) maxSetSize = max ( maxSetSize , dp [ N - 1 ] [ i ] ) ; return N - maxSetSize ; } int main ( ) { int A [ ] = { 1 , 4 , 5 , 7 , 20 , 21 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minimumDeletions ( A , N ) << endl ; return 0 ; }
Find maximum subset | C ++ program for tha above approach ; Function to calculate maximum sum possible by taking at most K elements that is divisibly by D ; variable to store final answer ; Traverse all subsets ; Update ans if necessary conditions are satisfied ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( vector < int > A , int N , int K , int D ) { int ans = 0 ; for ( int i = 0 ; i < ( 1 << N ) ; i ++ ) { int sum = 0 ; int c = 0 ; for ( int j = 0 ; j < N ; j ++ ) { if ( i >> j & 1 ) { sum += A [ j ] ; c ++ ; } } if ( sum % D == 0 && c <= K ) ans = max ( ans , sum ) ; } return ans ; } int main ( ) { int N = 5 , K = 3 , D = 7 ; vector < int > A = { 1 , 11 , 5 , 5 , 18 } ; cout << maximumSum ( A , N , K , D ) << endl ; return 0 ; }
Find the longest subsequence of a string that is a substring of another string | C ++ program for the above approach ; Function to find the longest subsequence that matches with the substring of other string ; Stores the lengths of strings X and Y ; Create a matrix ; Initialize the matrix ; Fill all the remaining rows ; If the characters are equal ; If not equal , then just move to next in subsequence string ; Find maximum length of the longest subsequence matching substring of other string ; Iterate through the last row of matrix ; Store the required string ; Backtrack from the cell ; If equal , then add the character to res string ; Return the required string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string longestSubsequence ( string X , string Y ) { int n = X . size ( ) ; int m = Y . size ( ) ; vector < vector < int > > mat ( n + 1 , vector < int > ( m + 1 ) ) ; for ( int i = 0 ; i < n + 1 ; i ++ ) { for ( int j = 0 ; j < m + 1 ; j ++ ) { if ( i == 0 j == 0 ) mat [ i ] [ j ] = 0 ; } } for ( int i = 1 ; i < n + 1 ; i ++ ) { for ( int j = 1 ; j < m + 1 ; j ++ ) { if ( X [ i - 1 ] == Y [ j - 1 ] ) { mat [ i ] [ j ] = 1 + mat [ i - 1 ] [ j - 1 ] ; } else { mat [ i ] [ j ] = mat [ i - 1 ] [ j ] ; } } } int len = 0 , col = 0 ; for ( int i = 0 ; i < m + 1 ; i ++ ) { if ( mat [ n ] [ i ] > len ) { len = mat [ n ] [ i ] ; col = i ; } } string res = " " ; int i = n ; int j = col ; while ( len > 0 ) { if ( X [ i - 1 ] == Y [ j - 1 ] ) { res = X [ i - 1 ] + res ; i -- ; j -- ; len -- ; } else { i -- ; } } return res ; } int main ( ) { string X = " ABCD " ; string Y = " ACDBDCD " ; cout << ( longestSubsequence ( X , Y ) ) ; return 0 ; }
Divide chocolate bar into pieces , minimizing the area of invalid pieces | C ++ program for the above approach ; Store valid dimensions ; Stores memoization ; Utility function to calculate minimum invalid area for Chocolate piece having dimension ( l , r ) ; Check whether current piece is valid or not If it is , then return zero for current dimension ; Making all possible horizontal cuts , one by one and calculating the sum of minimum invalid area for both the resulting pieces ; Making all possible vertical cuts , one by one and calculating the sum of minimum invalid area for both the resulting pieces ; Store the computed result ; Function to calculate minimum invalid area for Chocolate piece having dimension ( l , r ) ; Total number of valid dimensions ; Storing valid dimensions as for every ( x , y ) both ( x , y ) and ( y , x ) are valid ; Fill dp [ ] [ ] table with - 1 , indicating that results are not computed yet ; Stores minimum area ; Print minArea as the output ; Driver Code ; Given N & M ; Given valid dimensions ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int sz = 1001 ; bool ok [ sz ] [ sz ] = { } ; int dp [ sz ] [ sz ] ; int minInvalidAreaUtil ( int l , int b ) { if ( dp [ l ] [ b ] == -1 ) { if ( ok [ l ] [ b ] ) { return dp [ l ] [ b ] = 0 ; } int ans = l * b ; for ( int i = 1 ; i < b ; i ++ ) { ans = min ( ans , minInvalidAreaUtil ( l , i ) + minInvalidAreaUtil ( l , b - i ) ) ; } for ( int i = 1 ; i < l ; i ++ ) { ans = min ( ans , minInvalidAreaUtil ( i , b ) + minInvalidAreaUtil ( l - i , b ) ) ; } dp [ l ] [ b ] = ans ; } return dp [ l ] [ b ] ; } void minInvalidArea ( int N , int M , vector < pair < int , int > > & dimensions ) { int K = dimensions . size ( ) ; for ( int i = 0 ; i < K ; i ++ ) { ok [ dimensions [ i ] . first ] [ dimensions [ i ] . second ] = 1 ; ok [ dimensions [ i ] . second ] [ dimensions [ i ] . first ] = 1 ; } for ( int i = 0 ; i < sz ; i ++ ) { for ( int j = 0 ; j < sz ; j ++ ) { dp [ i ] [ j ] = -1 ; } } int minArea = minInvalidAreaUtil ( N , M ) ; cout << minArea << endl ; } int main ( ) { int N = 10 , M = 10 ; vector < pair < int , int > > dimensions = { { 3 , 5 } } ; minInvalidArea ( N , M , dimensions ) ; return 0 ; }
Count unordered pairs of equal elements for all subarrays | C ++ program for the above approach ; Function to count all pairs ( i , j ) such that arr [ i ] equals arr [ j ] in all possible subarrays of the array ; Stores the size of the array ; Stores the positions of all the distinct elements ; Append index corresponding to arr [ i ] in the map ; Traverse the map M ; Traverse the array ; Update the value of ans ; Update the value of the sum ; Print the value of ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( vector < int > arr ) { int N = arr . size ( ) ; int ans = 0 ; map < int , vector < int > > M ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { M [ arr [ i ] ] . push_back ( i ) ; } for ( auto it : M ) { vector < int > v = it . second ; int sum = 0 ; for ( int j = 0 ; j < v . size ( ) ; j ++ ) { ans += sum * ( N - v [ j ] ) ; sum += v [ j ] + 1 ; } } cout << ans ; } int main ( ) { vector < int > arr = { 1 , 2 , 1 , 1 } ; countPairs ( arr ) ; return 0 ; }
Number of alternating substrings from a given Binary String | c ++ program for the above approach ; Function to count number of alternating substrings from a given binary string ; Initialize dp array , where dp [ i ] [ j ] stores the number of alternating strings starts with i and having j elements . ; Traverse the string from the end ; If i is equal to N - 1 ; Otherwise , ; Increment count of substrings starting at i and has 0 in the beginning ; Increment count of substrings starting at i and has 1 in the beginning ; Stores the result ; Iterate in the range [ 0 , N - 1 ] ; Update ans ; Return the ans ; Driver code ; Given Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countAlternatingSubstrings ( string S , int N ) { vector < vector < int > > dp ( 2 , vector < int > ( N , 0 ) ) ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( i == N - 1 ) { if ( S [ i ] == '1' ) dp [ 1 ] [ i ] = 1 ; else dp [ 0 ] [ i ] = 1 ; } else { if ( S [ i ] == '0' ) dp [ 0 ] [ i ] = 1 + dp [ 1 ] [ i + 1 ] ; else dp [ 1 ] [ i ] = 1 + dp [ 0 ] [ i + 1 ] ; } } int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { ans += max ( dp [ 0 ] [ i ] , dp [ 1 ] [ i ] ) ; } return ans ; } int main ( ) { string S = "0010" ; int N = S . length ( ) ; cout << countAlternatingSubstrings ( S , N ) ; return 0 ; }
Count ways to place ' + ' and ' | C ++ program for the above approach ; Function to count number of ways ' + ' and ' - ' operators can be placed in front of array elements to make the sum of array elements equal to K ; Stores sum of the array ; Stores count of 0 s in A [ ] ; Traverse the array ; Update sum ; Update count of 0 s ; Conditions where no arrangements are possible which adds up to K ; Required sum ; Dp array ; Base cases ; Fill the dp array ; Return answer ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int A [ ] , int N , int K ) { int sum = 0 ; int c = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; if ( A [ i ] == 0 ) c ++ ; } if ( K > sum || ( sum + K ) % 2 ) return 0 ; sum = ( sum + K ) / 2 ; int dp [ N + 1 ] [ sum + 1 ] ; for ( int i = 0 ; i <= sum ; i ++ ) dp [ 0 ] [ i ] = 0 ; for ( int i = 0 ; i <= N ; i ++ ) dp [ i ] [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= sum ; j ++ ) { if ( A [ i - 1 ] <= j && A [ i - 1 ] ) dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j - A [ i - 1 ] ] ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } } return dp [ N ] [ sum ] + pow ( 2 , c ) ; } int main ( ) { int A [ ] = { 1 , 1 , 2 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int K = 3 ; cout << solve ( A , N , K ) << endl ; return 0 ; }
Rearrange an array to maximize sum of Bitwise AND of same | C ++ program for the above approach ; Function to implement recursive DP ; If i is equal to N ; If dp [ i ] [ mask ] is not equal to - 1 ; Iterate over the array B [ ] ; If current element is not yet selected ; Update dp [ i ] [ mask ] ; Return dp [ i ] [ mask ] ; Function to obtain maximum sum of Bitwise AND of same - indexed elements from the arrays A [ ] and B [ ] ; Stores all dp - states ; Returns the maximum value returned by the function maximizeAnd ( ) ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximizeAnd ( int i , int mask , int * A , int * B , int N , vector < vector < int > > & dp ) { if ( i == N ) return 0 ; if ( dp [ i ] [ mask ] != -1 ) return dp [ i ] [ mask ] ; for ( int j = 0 ; j < N ; ++ j ) { if ( ! ( mask & ( 1 << j ) ) ) { dp [ i ] [ mask ] = max ( dp [ i ] [ mask ] , ( A [ i ] & B [ j ] ) + maximizeAnd ( i + 1 , mask | ( 1 << j ) , A , B , N , dp ) ) ; } } return dp [ i ] [ mask ] ; } int maximizeAndUtil ( int * A , int * B , int N ) { vector < vector < int > > dp ( N , vector < int > ( 1 << N + 1 , -1 ) ) ; return maximizeAnd ( 0 , 0 , A , B , N , dp ) ; } int main ( ) { int A [ ] = { 3 , 5 , 7 , 11 } ; int B [ ] = { 2 , 6 , 10 , 12 } ; int N = sizeof A / sizeof A [ 0 ] ; cout << maximizeAndUtil ( A , B , N ) ; }
Count numbers from a given range whose adjacent digits are not co | ; Function to count numbers whose adjacent digits are not co - prime ; Base Case If the entire string is traversed ; If the subproblem has already been computed ; GCD of current and previous digits is not equal to 1 ; Current position is 0 ; All encountered digits until now are 0 s ; Return the total possible valid numbers ; Function to count numbers whose adjacent digits are not co - prime ; Convert R to string . ; Length of string ; Initialize dp array with - 1 ; Function call with initial values of bound , allZeros , previous as 1 , 1 , 0 ; Subtract 1 from the answer , as 0 is included ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100 ] [ 2 ] [ 10 ] [ 2 ] ; int noncoprimeCount ( int i , int N , string & S , bool bound , int prev , bool allZeros ) { if ( i == N ) return 1 ; int & val = dp [ i ] [ bound ] [ prev ] [ allZeros ] ; if ( val != -1 ) return val ; int cnt = 0 ; for ( int j = 0 ; j <= ( bound ? ( S [ i ] - '0' ) : 9 ) ; ++ j ) { if ( ( __gcd ( j , prev ) != 1 ) || ( i == 0 ) allZeros == 1 ) { cnt += noncoprimeCount ( i + 1 , N , S , bound & ( j == ( S [ i ] - '0' ) ) , j , allZeros & ( j == 0 ) ) ; } } return val = cnt ; } void noncoprimeCountUtil ( int R ) { string S = to_string ( R ) ; int N = S . length ( ) ; memset ( dp , -1 , sizeof dp ) ; int ans = noncoprimeCount ( 0 , N , S , 1 , 0 , 1 ) ; cout << ans - 1 << endl ; } int main ( ) { int N = 10000 ; noncoprimeCountUtil ( N ) ; return 0 ; }
Find the winner of a game of removing at most 3 stones from a pile in each turn | C ++ program for the above approach ; Function to find the maximum score of Player 1 ; Base Case ; If the result is already computed , then return the result ; Variable to store maximum score ; Pick one stone ; Pick 2 stones ; Pick 3 stones ; Return the score of the player ; Function to find the winner of the game ; Create a 1D table , dp of size N ; Store the result ; Player 1 wins ; PLayer 2 wins ; Tie ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumStonesUtil ( int * arr , int n , int i , vector < int > & dp ) { if ( i >= n ) return 0 ; int & ans = dp [ i ] ; if ( ans != -1 ) return ans ; ans = INT_MIN ; ans = max ( ans , arr [ i ] - maximumStonesUtil ( arr , n , i + 1 , dp ) ) ; if ( i + 1 < n ) ans = max ( ans , arr [ i ] + arr [ i + 1 ] - maximumStonesUtil ( arr , n , i + 2 , dp ) ) ; if ( i + 2 < n ) ans = max ( ans , arr [ i ] + arr [ i + 1 ] + arr [ i + 2 ] - maximumStonesUtil ( arr , n , i + 3 , dp ) ) ; return ans ; } string maximumStones ( int * arr , int n ) { vector < int > dp ( n , -1 ) ; int res = maximumStonesUtil ( arr , n , 0 , dp ) ; if ( res > 0 ) return " Player1" ; else if ( res < 0 ) return " Player2" ; else return " Tie " ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumStones ( arr , n ) ; return 0 ; }
Count ways to reach the Nth station | C ++ program for the above approach ; Function to find the number of ways to reach Nth station ; Declares the DP [ ] array ; Initialize dp [ ] [ ] array ; Only 1 way to reach station 1 ; Find the remaining states from the 2 nd station ; If the train A is present at station i - 1 ; If the train B is present at station i - 2 ; If train C is present at station i - 3 ; The total number of ways to reach station i ; Return the total count of ways ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfWays ( int N ) { int DP [ N + 1 ] [ 5 ] ; memset ( DP , 0 , sizeof ( DP ) ) ; DP [ 1 ] [ 1 ] = 1 ; DP [ 1 ] [ 2 ] = 1 ; DP [ 1 ] [ 3 ] = 1 ; DP [ 1 ] [ 4 ] = 1 ; for ( int i = 2 ; i <= N ; i ++ ) { if ( i - 1 > 0 && DP [ i - 1 ] [ 1 ] > 0 ) DP [ i ] [ 1 ] = DP [ i - 1 ] [ 4 ] ; if ( i - 2 > 0 && DP [ i - 2 ] [ 2 ] > 0 ) DP [ i ] [ 2 ] = DP [ i - 2 ] [ 4 ] ; if ( i - 3 > 0 && DP [ i - 3 ] [ 3 ] > 0 ) DP [ i ] [ 3 ] = DP [ i - 3 ] [ 4 ] ; DP [ i ] [ 4 ] = ( DP [ i ] [ 1 ] + DP [ i ] [ 2 ] + DP [ i ] [ 3 ] ) ; } return DP [ N ] [ 4 ] ; } int main ( ) { int N = 15 ; cout << numberOfWays ( N ) ; return 0 ; }
Number of M | C ++ program for the above approach ; Function to find the number of M - length sorted arrays possible using numbers from the range [ 1 , N ] ; If size becomes equal to m , that means an array is found ; Include current element , increase size by 1 and remain on the same element as it can be included again ; Exclude current element ; Return the sum obtained in both the cases ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSortedArrays ( int start , int m , int size , int n ) { if ( size == m ) return 1 ; if ( start > n ) return 0 ; int notTaken = 0 , taken = 0 ; taken = countSortedArrays ( start , m , size + 1 , n ) ; notTaken = countSortedArrays ( start + 1 , m , size , n ) ; return taken + notTaken ; } int main ( ) { int n = 2 , m = 3 ; cout << countSortedArrays ( 1 , m , 0 , n ) ; return 0 ; }
Maximum subarray sum possible after removing at most one subarray | C ++ program for the above approach ; Function to find maximum subarray sum possible after removing at most one subarray ; Calculate the preSum [ ] array ; Update the value of sum ; Update the value of maxSum ; Update the value of preSum [ i ] ; Calculate the postSum [ ] array ; Update the value of sum ; Update the value of maxSum ; Update the value of postSum [ i ] ; Stores the resultant maximum sum of subarray ; Update the value of ans ; Print the resultant sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumSum ( int arr [ ] , int n ) { int preSum [ n ] ; int sum = 0 ; int maxSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = max ( arr [ i ] , sum + arr [ i ] ) ; maxSum = max ( maxSum , sum ) ; preSum [ i ] = maxSum ; } sum = 0 ; maxSum = 0 ; int postSum [ n + 1 ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { sum = max ( arr [ i ] , sum + arr [ i ] ) ; maxSum = max ( maxSum , sum ) ; postSum [ i ] = maxSum ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans = max ( ans , preSum [ i ] + postSum [ i ] ) ; } cout << ( ans ) ; } int main ( ) { int arr [ ] = { 7 , 6 , -1 , -4 , -5 , 7 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumSum ( arr , n ) ; return 0 ; }
Count all unique outcomes possible by performing S flips on N coins | C ++ program for the above approach ; Function to recursively count the number of unique outcomes possible S flips are performed on N coins ; Base Cases ; Recursive Calls ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfUniqueOutcomes ( int N , int S ) { if ( S < N ) return 0 ; if ( N == 1 N == S ) return 1 ; return ( numberOfUniqueOutcomes ( N - 1 , S - 1 ) + numberOfUniqueOutcomes ( N - 1 , S - 2 ) ) ; } int main ( ) { int N = 3 , S = 4 ; cout << numberOfUniqueOutcomes ( N , S ) ; return 0 ; }
Length of longest increasing subsequence in a string | C ++ program for the above approach ; Function to find length of longest increasing subsequence in a string ; Stores at every i - th index , the length of the longest increasing subsequence ending with character i ; Size of string ; Stores the length of LIS ; Iterate over each character of the string ; Store position of the current character ; Stores the length of LIS ending with current character ; Check for all characters less then current character ; Include current character ; Update length of longest increasing subsequence ; Updating LIS for current character ; Return the length of LIS ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lisOtimised ( string s ) { int dp [ 30 ] = { 0 } ; int N = s . size ( ) ; int lis = INT_MIN ; for ( int i = 0 ; i < N ; i ++ ) { int val = s [ i ] - ' a ' ; int curr = 0 ; for ( int j = 0 ; j < val ; j ++ ) { curr = max ( curr , dp [ j ] ) ; } curr ++ ; lis = max ( lis , curr ) ; dp [ val ] = max ( dp [ val ] , curr ) ; } return lis ; } int main ( ) { string s = " fdryutiaghfse " ; cout << lisOtimised ( s ) ; return 0 ; }
Sum of length of two smallest subsets possible from a given array with sum at least K | C ++ program for the above approach ; Function to calculate sum of lengths of two smallest subsets with sum >= K ; Sort the array in ascending order ; Stores suffix sum of the array ; Update the suffix sum array ; Stores all dp - states ; Initialize all dp - states with a maximum possible value ; Base Case ; Traverse the array arr [ ] ; Iterate over the range [ 0 , K ] ; If A [ i ] is equal to at least the required sum j for the current state ; If the next possible state doesn 't exist ; Otherwise , update the current state to the minimum of the next state and state including the current element A [ i ] ; Traverse the suffix sum array ; If suffix [ i ] - dp [ i ] [ K ] >= K ; Sum of lengths of the two smallest subsets is obtained ; Return - 1 , if there doesn 't exist any subset of sum >= K ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1e9 ; int MinimumLength ( int A [ ] , int N , int K ) { sort ( A , A + N ) ; int suffix [ N + 1 ] = { 0 } ; for ( int i = N - 1 ; i >= 0 ; i -- ) suffix [ i ] = suffix [ i + 1 ] + A [ i ] ; int dp [ N + 1 ] [ K + 1 ] ; for ( int i = 0 ; i <= N ; i ++ ) for ( int j = 0 ; j <= K ; j ++ ) dp [ i ] [ j ] = MAX ; dp [ N ] [ 0 ] = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { for ( int j = K ; j >= 0 ; j -- ) { if ( j <= A [ i ] ) { dp [ i ] [ j ] = A [ i ] ; continue ; } if ( dp [ i + 1 ] [ j - A [ i ] ] == MAX ) dp [ i ] [ j ] = MAX ; else dp [ i ] [ j ] = min ( dp [ i + 1 ] [ j ] , dp [ i + 1 ] [ j - A [ i ] ] + A [ i ] ) ; } } for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( suffix [ i ] - dp [ i ] [ K ] >= K ) { return N - i ; } } return -1 ; } int main ( ) { int arr [ ] = { 7 , 4 , 5 , 6 , 8 } ; int K = 13 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << MinimumLength ( arr , N , K ) ; return 0 ; }
Count distinct possible Bitwise XOR values of subsets of an array | C ++ program for the above approach ; Stores the mask of the vector ; Stores the current size of dp [ ] ; Function to store the mask of given integer ; Iterate over the range [ 0 , 20 ] ; If i - th bit 0 ; If dp [ i ] is zero ; Store the position in dp ; Increment the answer ; Return from the loop ; mask = mask XOR dp [ i ] ; Function to find the size of the set having Bitwise XOR of all the subset of the given array ; Traverse the array ; Print the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int const size = 20 ; int dp [ size ] ; int ans ; void insertVector ( int mask ) { for ( int i = 0 ; i < 20 ; i ++ ) { if ( ( mask & 1 << i ) == 0 ) continue ; if ( ! dp [ i ] ) { dp [ i ] = mask ; ++ ans ; return ; } mask ^= dp [ i ] ; } } void maxSizeSet ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { insertVector ( arr [ i ] ) ; } cout << ( 1 << ans ) << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxSizeSet ( arr , N ) ; return 0 ; }
Maximize sum possible from an array by jumps of length i + K * arr [ i ] from any ith index | C ++ program for the above approach ; Function to find the maximum sum possible by jumps of length i + K * arr [ i ] from any i - th index ; Initialize an array dp [ ] ; Stores the maximum sum ; Iterate over the range [ N - 1 , 0 ] ; If length of the jump exceeds N ; Set dp [ i ] as arr [ i ] ; Otherwise , update dp [ i ] as sum of dp [ i + K * arr [ i ] ] and arr [ i ] ; Update the overall maximum sum ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSum ( int arr [ ] , int N , int K ) { int dp [ N + 2 ] = { 0 } ; int maxval = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( ( i + K * arr [ i ] ) >= N ) { dp [ i ] = arr [ i ] ; } else { dp [ i ] = dp [ i + K * arr [ i ] ] + arr [ i ] ; } maxval = max ( maxval , dp [ i ] ) ; } cout << maxval ; } int main ( ) { int arr [ ] = { 2 , 1 , 3 , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; maxSum ( arr , N , K ) ; return 0 ; }
Maximum sum submatrix | C ++ program for the above approach ; Function to find maximum sum submatrix ; Stores the number of rows and columns in the matrix ; Stores maximum submatrix sum ; Take each row as starting row ; Take each column as the starting column ; Take each row as the ending row ; Take each column as the ending column ; Stores the sum of submatrix having topleft index ( i , j ) and bottom right index ( k , l ) ; Iterate the submatrix row - wise and calculate its sum ; Update the maximum sum ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSubmatrixSum ( vector < vector < int > > matrix ) { int r = matrix . size ( ) ; int c = matrix [ 0 ] . size ( ) ; int maxSubmatrix = 0 ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { for ( int k = i ; k < r ; k ++ ) { for ( int l = j ; l < c ; l ++ ) { int sumSubmatrix = 0 ; for ( int m = i ; m <= k ; m ++ ) { for ( int n = j ; n <= l ; n ++ ) { sumSubmatrix += matrix [ m ] [ n ] ; } } maxSubmatrix = max ( maxSubmatrix , sumSubmatrix ) ; } } } } cout << maxSubmatrix ; } int main ( ) { vector < vector < int > > matrix = { { 0 , -2 , -7 , 0 } , { 9 , 2 , -6 , 2 } , { -4 , 1 , -4 , 1 } , { -1 , 8 , 0 , -2 } } ; maxSubmatrixSum ( matrix ) ; return 0 ; }
Maximize sum of subsets from two arrays having no consecutive values | C ++ program for the above approach ; Function to calculate maximum subset sum ; Initialize array to store dp states ; Base Cases ; Pre initializing for dp [ 0 ] & dp [ 1 ] ; Calculating dp [ index ] based on above formula ; Print maximum subset sum ; Driver Code ; Given arrays ; Length of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumSubsetSum ( int arr1 [ ] , int arr2 [ ] , int length ) { int dp [ length + 1 ] ; if ( length == 1 ) { cout << ( max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) ; return ; } if ( length == 2 ) { cout << ( max ( max ( arr1 [ 1 ] , arr2 [ 1 ] ) , max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) ) ; return ; } else { dp [ 0 ] = max ( arr1 [ 0 ] , arr2 [ 0 ] ) ; dp [ 1 ] = max ( max ( arr1 [ 1 ] , arr2 [ 1 ] ) , max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) ; int index = 2 ; while ( index < length ) { dp [ index ] = max ( max ( arr1 [ index ] , arr2 [ index ] ) , max ( max ( arr1 [ index ] + dp [ index - 2 ] , arr2 [ index ] + dp [ index - 2 ] ) , dp [ index - 1 ] ) ) ; ++ index ; } cout << ( dp [ length - 1 ] ) ; } } int main ( ) { int arr1 [ ] = { -1 , -2 , 4 , -4 , 5 } ; int arr2 [ ] = { -1 , -2 , -3 , 4 , 10 } ; int length = 5 ; maximumSubsetSum ( arr1 , arr2 , length ) ; return 0 ; }
Modify array by replacing every array element with minimum possible value of arr [ j ] + | j | C ++ program for the above approach ; Function to find minimum value of arr [ j ] + | j - i | for every array index ; Stores minimum of a [ j ] + | i - j | upto position i ; Stores minimum of a [ j ] + | i - j | upto position i from the end ; Traversing and storing minimum of a [ j ] + | i - j | upto i ; Traversing and storing minimum of a [ j ] + | i - j | upto i from the end ; Traversing from [ 0 , N ] and storing minimum of a [ j ] + | i - j | from starting and end ; Print the required array ; Driver code ; Given array arr [ ] ; Size of the array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minAtEachIndex ( int n , int arr [ ] ) { int dp1 [ n ] ; int dp2 [ n ] ; int i ; dp1 [ 0 ] = arr [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) dp1 [ i ] = min ( arr [ i ] , dp1 [ i - 1 ] + 1 ) ; dp2 [ n - 1 ] = arr [ n - 1 ] ; for ( i = n - 2 ; i >= 0 ; i -- ) dp2 [ i ] = min ( arr [ i ] , dp2 [ i + 1 ] + 1 ) ; vector < int > v ; for ( i = 0 ; i < n ; i ++ ) v . push_back ( min ( dp1 [ i ] , dp2 [ i ] ) ) ; for ( auto x : v ) cout << x << " ▁ " ; } int main ( ) { int arr [ ] = { 1 , 4 , 2 , 5 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minAtEachIndex ( N , arr ) ; return 0 ; }
Count all N | C ++ program for the above approach ; Function to print the count of arrays satisfying given condition ; First element of array is set as 1 ; Since the first element of arr [ ] is 1 , the second element can 't be 1 ; Traverse the remaining indices ; If arr [ i ] = 1 ; If arr [ i ] a 1 ; Since last element needs to be 1 ; Driver Code ; Stores the count of arrays where arr [ 0 ] = arr [ N - 1 ] = 1 ; Since arr [ 0 ] and arr [ N - 1 ] can be any number from 1 to M ; Print answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int totalArrays ( int N , int M ) { int end_with_one [ N + 1 ] ; int end_not_with_one [ N + 1 ] ; end_with_one [ 0 ] = 1 ; end_not_with_one [ 0 ] = 0 ; end_with_one [ 1 ] = 0 ; end_not_with_one [ 1 ] = M - 1 ; for ( int i = 2 ; i < N ; i ++ ) { end_with_one [ i ] = end_not_with_one [ i - 1 ] ; end_not_with_one [ i ] = end_with_one [ i - 1 ] * ( M - 1 ) + end_not_with_one [ i - 1 ] * ( M - 2 ) ; } return end_with_one [ N - 1 ] ; } int main ( ) { int N = 3 , M = 3 ; int temp = totalArrays ( N , M ) ; int ans = M * temp ; cout << ans << " STRNEWLINE " ; return 0 ; }
Count numbers from a given range whose product of digits is K | C ++ program to implement the above approach ; Function to find the product of digits of a number ; Stores product of digits of N ; Update res ; Update N ; Function to count numbers in the range [ 0 , X ] whose product of digit is K ; Stores count of numbers in the range [ L , R ] whose product of digit is K ; Iterate over the range [ L , R ] ; If product of digits of i equal to K ; Update cnt ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int prodOfDigit ( int N ) { int res = 1 ; while ( N ) { res = res * ( N % 10 ) ; N /= 10 ; } return res ; } int cntNumRange ( int L , int R , int K ) { int cnt = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( prodOfDigit ( i ) == K ) { cnt ++ ; } } return cnt ; } int main ( ) { int L = 20 , R = 10000 , K = 14 ; cout << cntNumRange ( L , R , K ) ; }
Median of Bitwise XOR of all submatrices starting from the top left corner | C ++ program to implement the above approach ; Function to find the median of bitwise XOR of all the submatrix whose topmost leftmost corner is ( 0 , 0 ) ; dp [ i ] [ j ] : Stores the bitwise XOR of submatrix having top left corner at ( 0 , 0 ) and bottom right corner at ( i , j ) ; Stores count of submatrix ; Base Case ; Base Case ; Fill dp [ ] [ ] using tabulation ; Fill dp [ i ] [ j ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; double findMedXOR ( int mat [ ] [ 2 ] , int N , int M ) { int dp [ N ] [ M ] ; int med [ N * M ] ; dp [ 0 ] [ 0 ] = mat [ 0 ] [ 0 ] ; med [ 0 ] = dp [ 0 ] [ 0 ] ; int len = 1 ; for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] ^ mat [ i ] [ 0 ] ; med [ len ++ ] = dp [ i ] [ 0 ] ; } for ( int i = 1 ; i < M ; i ++ ) { dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] ^ mat [ 0 ] [ i ] ; med [ len ++ ] = dp [ 0 ] [ i ] ; } 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 ] ^ mat [ i ] [ j ] ; med [ len ++ ] = dp [ i ] [ j ] ; } } sort ( med , med + len ) ; if ( len % 2 == 0 ) { return ( med [ ( len / 2 ) ] + med [ ( len / 2 ) - 1 ] ) / 2.0 ; } return med [ len / 2 ] ; } int main ( ) { int mat [ ] [ 2 ] = { { 1 , 2 } , { 2 , 3 } } ; int N = sizeof ( mat ) / sizeof ( mat [ 0 ] ) ; int M = 2 ; cout << findMedXOR ( mat , N , M ) ; return 0 ; }
Count ways to tile an N | C ++ Program to implement the above approach ; Function to count the ways to tile N * 1 board using 1 * 1 and 2 * 1 tiles ; dp [ i ] : Stores count of ways to tile i * 1 board using given tiles ; Base Case ; Iterate over the range [ 2 , N ] ; Fill dp [ i ] using the recurrence relation ; Driver Code ; Given N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long countWaysToTileBoard ( long N ) { long dp [ N + 1 ] ; dp [ 0 ] = 1 ; dp [ 1 ] = 2 ; for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] = ( 2 * dp [ i - 1 ] + dp [ i - 2 ] ) ; } cout << dp [ N ] ; } int main ( ) { long N = 2 ; countWaysToTileBoard ( N ) ; return 0 ; }
Subsequences generated by including characters or ASCII value of characters of given string | C ++ program to implement the above approach ; Function to print subsequences containing ASCII value of the characters or the the characters of the given string ; Base Case ; If length of the subsequence exceeds 0 ; Print the subsequence ; Stores character present at i - th index of str ; If the i - th character is not included in the subsequence ; Including the i - th character in the subsequence ; Include the ASCII value of the ith character in the subsequence ; Driver Code ; Stores length of str
#include <bits/stdc++.h> NEW_LINE using namespace std ; void FindSub ( string str , string res , int i ) { if ( i == str . length ( ) ) { if ( res . length ( ) > 0 ) { cout << res << " ▁ " ; } return ; } char ch = str [ i ] ; FindSub ( str , res , i + 1 ) ; FindSub ( str , res + ch , i + 1 ) ; FindSub ( str , res + to_string ( int ( ch ) ) , i + 1 ) ; } int main ( ) { string str = " ab " ; string res = " " ; int N = str . length ( ) ; FindSub ( str , res , 0 ) ; }
Minimize given flips required to reduce N to 0 | C ++ program to implement the above approach ; Function to find the minimum count of operations required to Reduce N to 0 ; Stores count of bits in N ; Recurrence relation ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinOp ( int N ) { if ( N <= 1 ) return N ; int bit = log2 ( N ) + 1 ; return ( ( 1 << bit ) - 1 ) - MinOp ( N - ( 1 << ( bit - 1 ) ) ) ; } int main ( ) { int N = 4 ; cout << MinOp ( N ) ; return 0 ; }
Maximum non | C ++ program for the above approach ; Function to find the maximum product from the top left and bottom right cell of the given matrix grid [ ] [ ] ; Store dimension of grid ; Stores maximum product path ; Stores minimum product path ; Traverse the grid and update maxPath and minPath array ; Initialize to inf and - inf ; Base Case ; Calculate for row : ; Update the maximum ; Update the minimum ; Calculate for column : ; Update the maximum ; Update the minimum ; Update maxPath and minPath ; If negative product ; Otherwise ; Driver Code ; Given matrix mat [ ] [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProductPath ( vector < vector < int > > grid ) { int n = grid . size ( ) ; int m = grid [ 0 ] . size ( ) ; vector < vector < int > > maxPath ( n , vector < int > ( m , 0 ) ) ; vector < vector < int > > minPath ( n , vector < int > ( m , 0 ) ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { int mn = INT_MAX ; int mx = INT_MIN ; if ( i == 0 and j == 0 ) { mx = grid [ i ] [ j ] ; mn = grid [ i ] [ j ] ; } if ( i > 0 ) { int tempmx = max ( ( maxPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) , ( minPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) ) ; mx = max ( mx , tempmx ) ; int tempmn = min ( ( maxPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) , ( minPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) ) ; mn = min ( mn , tempmn ) ; } if ( j > 0 ) { int tempmx = max ( ( maxPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) , ( minPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) ) ; mx = max ( mx , tempmx ) ; int tempmn = min ( ( maxPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) , ( minPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) ) ; mn = min ( mn , tempmn ) ; } maxPath [ i ] [ j ] = mx ; minPath [ i ] [ j ] = mn ; } } if ( maxPath [ n - 1 ] [ m - 1 ] < 0 ) return -1 ; else return ( maxPath [ n - 1 ] [ m - 1 ] ) ; } int main ( ) { vector < vector < int > > mat = { { 1 , -2 , 1 } , { 1 , -2 , 1 } , { 3 , -4 , 1 } } ; cout << ( maxProductPath ( mat ) ) ; }
Smallest submatrix required to be removed such that sum of the remaining matrix is divisible by K | C ++ program to implement the above approach ; Function to find the length of the smallest subarray to be removed such that sum of elements is equal to S % K ; Remainder when total_sum is divided by K ; Stores curr_remainder and the most recent index at which curr_remainder has occured ; Stores required answer ; Add current element to curr_sum and take mod ; Update current remainder index ; If mod already exists in map the subarray exists ; Update res ; If not possible ; Return the result ; Function to find the smallest submatrix rqured to be deleted to make the sum of the matrix divisible by K ; Stores the sum of element of the matrix ; Traverse the matrix mat [ ] [ ] ; Update S ; Stores smallest area need to be deleted to get sum divisible by K ; Stores leftmost column of each matrix ; Stores rightmost column of each matrix ; Stores number of coulmns deleted of a matrix ; Store area of the deleted matrix ; prefixRowSum [ i ] : Store sum of sub matrix whose topmost left and bottommost right position is ( 0 , left ) ( i , right ) ; Iterate over all possible values of ( left , right ) ; Initialize all possible values of prefixRowSum [ ] to 0 ; Traverse each row from left to right column ; Update row_sum [ i ] ; ; Update width ; If no submatrix of the length ( right - left + 1 ) found to get the required output ; Update area ; If area is less than min_area ; Update min_area ; Driver Code ; Stores number of rows in the matrix ; Stores number of column in the matrix
#include <bits/stdc++.h> NEW_LINE using namespace std ; int removeSmallestSubarray ( int arr [ ] , int S , int n , int k ) { int target_remainder = S % k ; unordered_map < int , int > map1 ; map1 [ 0 ] = -1 ; int curr_remainder = 0 ; int res = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { curr_remainder = ( curr_remainder + arr [ i ] + k ) % k ; map1 [ curr_remainder ] = i ; int mod = ( curr_remainder - target_remainder + k ) % k ; if ( map1 . find ( mod ) != map1 . end ( ) ) { res = min ( res , i - map1 [ mod ] ) ; } } if ( res == INT_MAX res == n ) { res = -1 ; } return res ; } int smstSubmatDeleted ( vector < vector < int > > & mat , int N , int M , int K ) { int S = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) S += mat [ i ] [ j ] ; } int min_area = N * M ; int left = 0 ; int right = 0 ; int width ; int area ; int prefixRowSum [ N ] ; for ( left = 0 ; left < M ; left ++ ) { memset ( prefixRowSum , 0 , sizeof ( prefixRowSum ) ) ; for ( right = left ; right < M ; right ++ ) { for ( int i = 0 ; i < N ; i ++ ) { prefixRowSum [ i ] += mat [ i ] [ right ] ; } width = removeSmallestSubarray ( prefixRowSum , S , N , K ) ; if ( width != -1 ) { area = ( right - left + 1 ) * ( width ) ; if ( area < min_area ) { min_area = area ; } } } } return min_area ; } int main ( ) { vector < vector < int > > mat = { { 6 , 2 , 6 } , { 3 , 2 , 8 } , { 2 , 5 , 3 } } ; int K = 3 ; int N = mat . size ( ) ; int M = mat [ 0 ] . size ( ) ; cout << smstSubmatDeleted ( mat , N , M , K ) ; return 0 ; }
Count N | C ++ program to illustrate Count of N - length strings consisting only of vowels sorted lexicographically ; to keep the string in lexicographically sorted order use start index to add the vowels starting the from that index ; base case : if string length is 0 add to the count ; if last character in string is ' e ' add vowels starting from ' e ' i . e ' e ' , ' i ' , ' o ' , ' u ' ; decrease the length of string ; char arr [ 5 ] = { ' a ' , ' e ' , ' i ' , ' o ' , ' u ' } ; starting from index 0 add the vowels to strings
#include <iostream> NEW_LINE using namespace std ; int countstrings ( int n , int start ) { if ( n == 0 ) { return 1 ; } int cnt = 0 ; for ( int i = start ; i < 5 ; i ++ ) { cnt += countstrings ( n - 1 , i ) ; } return cnt ; } int countVowelStrings ( int n ) { return countstrings ( n , 0 ) ; } int main ( ) { int n = 2 ; cout << countVowelStrings ( n ) ; return 0 ; }
Count N | C ++ program for the above approach ; Function to count N - length strings consisting of vowels only sorted lexicographically ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumberOfStrings ( int n ) { return ( n + 1 ) * ( n + 2 ) * ( n + 3 ) * ( n + 4 ) / 24 ; } int main ( ) { int N = 2 ; cout << findNumberOfStrings ( N ) ; return 0 ; }
Count unique paths with given sum in an N | C ++ program for the above approach ; Function for counting total no of paths possible with the sum is equal to X ; If the path of the sum from the root to current node is stored in sum ; If already computed ; Count different no of paths using all possible ways ; Return total no of paths ; Driver Code ; Stores the number of ways to obtains sums 0 to X ; Function call
#include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; const int mod = ( int ) 1e9 + 7 ; ll findTotalPath ( int X , int n , vector < int > & dp ) { if ( X == 0 ) { return 1 ; } ll ans = 0 ; if ( dp [ X ] != -1 ) { return dp [ X ] ; } for ( int i = 1 ; i <= min ( X , n ) ; ++ i ) { ans += findTotalPath ( X - i , n , dp ) % mod ; ans %= mod ; } return dp [ X ] = ans ; } int main ( ) { int n = 3 , X = 2 ; vector < int > dp ( X + 1 , -1 ) ; cout << findTotalPath ( X , n , dp ) ; }
Count sequences of positive integers having product X | C ++ program for the above approach ; Function to print the total number of possible sequences with product X ; Precomputation of binomial coefficients ; Max length of a subsequence ; Ways dp array ; Fill i slots using all the primes ; Subtract ways for all slots that exactly fill less than i slots ; Total possible sequences ; Print the resultant count ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int bin [ 3000 ] [ 3000 ] ; void countWays ( const vector < int > & arr ) { int mod = 1e9 + 7 ; bin [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i < 3000 ; i ++ ) { bin [ i ] [ 0 ] = 1 ; for ( int j = 1 ; j <= i ; j ++ ) { bin [ i ] [ j ] = ( bin [ i - 1 ] [ j ] + bin [ i - 1 ] [ j - 1 ] ) % mod ; } } int n = 0 ; for ( auto x : arr ) n += x ; vector < int > ways ( n + 1 ) ; for ( int i = 1 ; i <= n ; i ++ ) { ways [ i ] = 1 ; for ( int j = 0 ; j < ( int ) arr . size ( ) ; j ++ ) { ways [ i ] = ( ways [ i ] * bin [ arr [ j ] + i - 1 ] [ i - 1 ] ) % mod ; } for ( int j = 1 ; j < i ; j ++ ) { ways [ i ] = ( ( ways [ i ] - bin [ i ] [ j ] * ways [ j ] ) % mod + mod ) % mod ; } } int ans = 0 ; for ( auto x : ways ) ans = ( ans + x ) % mod ; cout << ans << endl ; } int main ( ) { vector < int > arr = { 1 , 1 } ; countWays ( arr ) ; return 0 ; }
Maximum subsequence sum obtained by concatenating disjoint subarrays whose lengths are prime | C ++ program for the above approach ; Function to return all prime numbers smaller than N ; Create a boolean array " prime [ 0 . . n ] " ; Initialize all its entries as true ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it ; Stores all prime numbers smaller than MAX ; Store all prime numbers ; If p is prime ; Function to build the auxiliary DP array from the start ; Base Case ; Stores all prime numbers < N ; Stores prefix sum ; Update prefix sum ; Iterate over range ; Update each state i . e . . when current element is excluded ; Find start & end index of subarrays when prime [ i ] is taken ; Check if starting point lies in the array ; Include the elements al al + 1 . . . ar ; Check if element lies before start of selected subarray ; Update value of dp [ i ] ; Function to find the maximum sum subsequence with prime length ; Auxiliary DP array ; Build DP array ; Print the result ; Driver Code ; Given arr [ ] ; Size of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100005 NEW_LINE vector < int > SieveOfEratosthenes ( ) { bool seive [ MAX ] ; memset ( seive , true , sizeof ( seive ) ) ; for ( int p = 2 ; p * p < MAX ; p ++ ) { if ( seive [ p ] == true ) { for ( int i = p * p ; i < MAX ; i += p ) { seive [ i ] = false ; } } } vector < int > v ; for ( int p = 2 ; p < MAX ; p ++ ) { if ( seive [ p ] ) { v . push_back ( p ) ; } } return v ; } void build ( int dp [ ] , int arr [ ] , int N ) { dp [ 0 ] = 0 ; dp [ 1 ] = 0 ; vector < int > prime = SieveOfEratosthenes ( ) ; int pref [ N + 1 ] ; pref [ 0 ] = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { pref [ i ] = pref [ i - 1 ] + arr [ i - 1 ] ; } for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] = dp [ i - 1 ] ; for ( int j = 0 ; j <= prime . size ( ) ; j ++ ) { int r = i - 1 ; int l = r - prime [ j ] + 1 ; if ( l < 0 ) break ; int temp = 0 ; temp = pref [ r + 1 ] - pref [ l ] ; if ( l - 2 >= 0 ) temp += dp [ l - 2 + 1 ] ; dp [ i ] = max ( dp [ i ] , temp ) ; } } } void maxSumSubseq ( int arr [ ] , int N ) { int dp [ N + 1 ] ; build ( dp , arr , N ) ; cout << dp [ N ] ; } int main ( ) { int arr [ ] = { 10 , 10 , 7 , 10 , 10 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxSumSubseq ( arr , N ) ; return 0 ; }
Maximum possible score that can be obtained by constructing a Binary Tree based on given conditions | C ++ program for the above approach ; Function to find the maximum score for one possible tree having N nodes N - 1 Edges ; Number of nodes ; Initialize dp [ ] [ ] ; Score with 0 vertices is 0 ; Traverse the nodes from 1 to N ; Find maximum scores for each sum ; Iterate over degree of new node ; Update the current state ; Return maximum score for N node tree having 2 ( N - 1 ) sum of degree ; Driver Code ; Given array of scores ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxScore ( vector < int > & arr ) { int N = arr . size ( ) ; N ++ ; vector < vector < int > > dp ( N + 1 , vector < int > ( 2 * N , -100000 ) ) ; dp [ 0 ] [ 0 ] = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int s = 1 ; s <= 2 * ( N - 1 ) ; s ++ ) { for ( int j = 1 ; j <= N - 1 and j <= s ; j ++ ) { dp [ i ] [ s ] = max ( dp [ i ] [ s ] , arr [ j - 1 ] + dp [ i - 1 ] [ s - j ] ) ; } } } return dp [ N ] [ 2 * ( N - 1 ) ] ; } int main ( ) { vector < int > arr = { 1 , 3 , 0 } ; cout << maxScore ( arr ) ; return 0 ; }
Minimize cost of choosing and skipping array elements to reach end of the given array | C ++ program for the above approach ; Function to find the minimum cost to reach the end of the array from the first element ; Store the results ; Consider first index cost ; Find answer for each position i ; First Element ; Second Element ; For remaining element ; Consider min cost for skipping ; Last index represents the minimum total cost ; Driver Code ; Given X ; Given array cost [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumCost ( int * cost , int n , int x ) { vector < int > dp ( n + 2 , 0 ) ; dp [ 0 ] = cost [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( i == 1 ) dp [ i ] = cost [ i ] + dp [ i - 1 ] ; if ( i == 2 ) dp [ i ] = cost [ i ] + min ( dp [ i - 1 ] , x + dp [ i - 2 ] ) ; if ( i >= 3 ) dp [ i ] = cost [ i ] + min ( dp [ i - 1 ] , min ( x + dp [ i - 2 ] , 2 * x + dp [ i - 3 ] ) ) ; } cout << dp [ n - 1 ] ; } int main ( ) { int X = 4 ; int cost [ ] = { 6 , 3 , 9 , 2 , 1 , 3 } ; int N = sizeof ( cost ) / sizeof ( cost [ 0 ] ) ; minimumCost ( cost , N , X ) ; return 0 ; }
Maximum possible sum of non | C ++ program for the above approach ; Function to find the maximum sum not exceeding K possible by selecting a subset of non - adjacent elements ; Base Case ; Not selecting current element ; If selecting current element is possible ; Return answer ; Driver Code ; Given array arr [ ] ; Given K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int a [ ] , int n , int k ) { if ( n <= 0 ) return 0 ; int option = maxSum ( a , n - 1 , k ) ; if ( k >= a [ n - 1 ] ) option = max ( option , a [ n - 1 ] + maxSum ( a , n - 2 , k - a [ n - 1 ] ) ) ; return option ; } int main ( ) { int arr [ ] = { 50 , 10 , 20 , 30 , 40 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 100 ; cout << ( maxSum ( arr , N , K ) ) ; }
Count possible binary strings of length N without P consecutive 0 s and Q consecutive 1 s | C ++ program to implement the above approach ; Function to check if a string satisfy the given condition or not ; Stores the length of string ; Stores the previous character of the string ; Stores the count of consecutive equal characters ; Traverse the string ; If current character is equal to the previous character ; If count of consecutive 1 s is more than Q ; If count of consecutive 0 s is more than P ; Reset value of cnt ; If count of consecutive 1 s is more than Q ; If count of consecutive 0 s is more than P ; Function to count all distinct binary strings that satisfy the given condition ; Stores the length of str ; If length of str is N ; If str satisfy the given condition ; If str does not satisfy the given condition ; Append a character '0' at end of str ; Append a character '1' at end of str ; Return total count of binary strings ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkStr ( string str , int P , int Q ) { int N = str . size ( ) ; char prev = str [ 0 ] ; int cnt = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == prev ) { cnt ++ ; } else { if ( prev == '1' && cnt >= Q ) { return false ; } if ( prev == '0' && cnt >= P ) { return false ; } cnt = 1 ; } prev = str [ i ] ; } if ( prev == '1' && cnt >= Q ) { return false ; } if ( prev == '0' && cnt >= P ) { return false ; } return true ; } int cntBinStr ( string str , int N , int P , int Q ) { int len = str . size ( ) ; if ( len == N ) { if ( checkStr ( str , P , Q ) ) return 1 ; return 0 ; } int X = cntBinStr ( str + '0' , N , P , Q ) ; int Y = cntBinStr ( str + '1' , N , P , Q ) ; return X + Y ; } int main ( ) { int N = 5 , P = 2 , Q = 3 ; cout << cntBinStr ( " " , N , P , Q ) ; return 0 ; }
Count possible permutations of given array satisfying the given conditions | C ++ Program to implement the above approach ; Function to get the value of binomial coefficient ; Stores the value of binomial coefficient ; Since C ( N , R ) = C ( N , N - R ) ; Calculate the value of C ( N , R ) ; Function to get the count of permutations of the array that satisfy the condition ; Stores count of permutations of the array that satisfy the given condition ; Stores the value of C ( 2 N , N ) ; Stores the value of catalan number ; Return answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binCoff ( int N , int R ) { int res = 1 ; if ( R > ( N - R ) ) { R = ( N - R ) ; } for ( int i = 0 ; i < R ; i ++ ) { res *= ( N - i ) ; res /= ( i + 1 ) ; } return res ; } int cntPermutation ( int N ) { int cntPerm ; int C_2N_N = binCoff ( 2 * N , N ) ; cntPerm = C_2N_N / ( N + 1 ) ; return cntPerm ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntPermutation ( N / 2 ) ; return 0 ; }
Smallest submatrix with Kth maximum XOR | C ++ program for above approach ; Function to print smallest index of Kth maximum xors value of submatrices ; Dimensions of matrix ; Stores xors values for every index ; Min heap to find the kth maximum xors value ; Stores indices for corresponding xors values ; Traversing matrix to calculate xors values ; Insert calculated value in Min Heap ; If size exceeds k ; Remove the minimum ; Store smallest index containing xors [ i ] [ j ] ; Stores the kth maximum element ; Print the required index ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void smallestPosition ( int m [ ] [ 3 ] , int k , int row ) { int n = row ; int mm = row ; int xors [ n ] [ mm ] ; priority_queue < int , vector < int > , greater < int > > minHeap ; map < int , vector < int > > map ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < mm ; j ++ ) { int a = i - 1 >= 0 ? xors [ i - 1 ] [ j ] : 0 ; int b = j - 1 >= 0 ? xors [ i ] [ j - 1 ] : 0 ; int c = ( i - 1 >= 0 && j - 1 >= 0 ) ? xors [ i - 1 ] [ j - 1 ] : 0 ; xors [ i ] [ j ] = m [ i ] [ j ] ^ a ^ b ^ c ; minHeap . push ( xors [ i ] [ j ] ) ; if ( minHeap . size ( ) > k ) { minHeap . pop ( ) ; } if ( map . find ( xors [ i ] [ j ] ) == map . end ( ) ) map [ xors [ i ] [ j ] ] = { i , j } ; } } int kth_max_e = minHeap . top ( ) ; cout << ( map [ kth_max_e ] [ 0 ] + 1 ) << " ▁ " << ( map [ kth_max_e ] [ 1 ] + 1 ) ; } int main ( ) { int m [ ] [ 3 ] = { { 1 , 2 , 3 } , { 2 , 2 , 1 } , { 2 , 4 , 2 } } ; int k = 1 ; smallestPosition ( m , k , 3 ) ; }
Length of Longest Palindrome Substring | C ++ program for the above approach ; Function to obtain the length of the longest palindromic substring ; Length of given string ; Stores the maximum length ; Iterate over the string ; Iterate over the string ; Check for palindrome ; If string [ i , j - i + 1 ] is palindromic ; Return length of LPS ; Driver Code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestPalSubstr ( string str ) { int n = str . size ( ) ; int maxLength = 1 , start = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { for ( int j = i ; j < str . length ( ) ; j ++ ) { int flag = 1 ; for ( int k = 0 ; k < ( j - i + 1 ) / 2 ; k ++ ) if ( str [ i + k ] != str [ j - k ] ) flag = 0 ; if ( flag && ( j - i + 1 ) > maxLength ) { start = i ; maxLength = j - i + 1 ; } } } return maxLength ; } int main ( ) { string str = " forgeeksskeegfor " ; cout << longestPalSubstr ( str ) ; return 0 ; }
Maximize cost to empty an array by removing contiguous subarrays of equal elements | C ++ program for the above approach ; Initialize dp array ; Function that removes elements from array to maximize the cost ; Base case ; Check if an answer is stored ; Deleting count + 1 i . e . including the first element and starting a new sequence ; Removing [ left + 1 , i - 1 ] elements to continue with previous sequence ; Store the result ; Return answer ; Function to remove the elements ; Function Call ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 101 ] [ 101 ] [ 101 ] ; int helper ( int arr [ ] , int left , int right , int count , int m ) { if ( left > right ) return 0 ; if ( dp [ left ] [ right ] [ count ] != -1 ) { return dp [ left ] [ right ] [ count ] ; } int ans = ( count + 1 ) * m + helper ( arr , left + 1 , right , 0 , m ) ; for ( int i = left + 1 ; i <= right ; ++ i ) { if ( arr [ i ] == arr [ left ] ) { ans = max ( ans , helper ( arr , left + 1 , i - 1 , 0 , m ) + helper ( arr , i , right , count + 1 , m ) ) ; } } dp [ left ] [ right ] [ count ] = ans ; return ans ; } int maxPoints ( int arr [ ] , int n , int m ) { int len = n ; memset ( dp , -1 , sizeof ( dp ) ) ; return helper ( arr , 0 , len - 1 , 0 , m ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 2 , 2 , 3 , 4 , 3 , 1 } ; int M = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxPoints ( arr , N , M ) ; return 0 ; }
Minimum cost to convert M to N by repeated addition of its even divisors | C ++ program for the above approach ; Function to find the value of minimum steps to convert m to n ; Base Case ; If n exceeds m ; Iterate through all possible even divisors of m ; If m is divisible by i , then find the minimum cost ; Add the cost to convert m to m + i and recursively call next state ; Return min_cost ; Driver code ; Function call ; If conversion is not possible ; Print the cost
#include <iostream> NEW_LINE using namespace std ; int inf = 1000000008 ; int minSteps ( int m , int n ) { if ( n == m ) return 0 ; if ( m > n ) return inf ; int min_cost = inf ; for ( int i = 2 ; i < m ; i += 2 ) { if ( m % i == 0 ) { min_cost = min ( min_cost , m / i + minSteps ( m + i , n ) ) ; } } return min_cost ; } int main ( ) { int M = 6 ; int N = 24 ; int minimum_cost = minSteps ( M , N ) ; if ( minimum_cost == inf ) minimum_cost = -1 ; cout << minimum_cost ; return 0 ; }
Represent a number as the sum of positive numbers ending with 9 | C ++ program for the above approach ; Function to find the minimum count of numbers ending with 9 to form N ; Extract last digit of N ; Calculate the last digit ; If the last digit satisfies the condition ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCountOfNumbers ( int N ) { int k = N % 10 ; int z = N - ( 9 * ( 9 - k ) ) ; if ( z >= 9 && z % 10 == 9 ) { return 10 - k ; } else return -1 ; } int main ( ) { int N = 156 ; cout << minCountOfNumbers ( N ) ; return 0 ; }
Binary Matrix after flipping submatrices in given range for Q queries | C ++ program to implement the above approach ; Function to flip a submatrices ; Boundaries of the submatrix ; Iterate over the submatrix ; Check for 1 or 0 and flip accordingly ; Function to perform the queries ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void manipulation ( vector < vector < int > > & matrix , vector < int > & q ) { int x1 = q [ 0 ] , y1 = q [ 1 ] , x2 = q [ 2 ] , y2 = q [ 3 ] ; for ( int i = x1 - 1 ; i < x2 ; i ++ ) { for ( int j = y1 - 1 ; j < y2 ; j ++ ) { if ( matrix [ i ] [ j ] == 1 ) matrix [ i ] [ j ] = 0 ; else matrix [ i ] [ j ] = 1 ; } } } void queries_fxn ( vector < vector < int > > & matrix , vector < vector < int > > & queries ) { for ( auto q : queries ) manipulation ( matrix , q ) ; } int main ( ) { vector < vector < int > > matrix = { { 0 , 1 , 0 } , { 1 , 1 , 0 } } ; vector < vector < int > > queries = { { 1 , 1 , 2 , 3 } , { 1 , 1 , 1 , 1 } , { 1 , 2 , 2 , 3 } } ; queries_fxn ( matrix , queries ) ; cout << " [ " ; for ( int i = 0 ; i < matrix . size ( ) ; i ++ ) { cout << " [ " ; for ( int j = 0 ; j < matrix [ i ] . size ( ) ; j ++ ) cout << matrix [ i ] [ j ] << " ▁ " ; if ( i == matrix . size ( ) - 1 ) cout << " ] " ; else cout << " ] , ▁ " ; } cout << " ] " ; }
Minimum repeated addition of even divisors of N required to convert N to M | C ++ program for the above approach ; INF is the maximum value which indicates Impossible state ; Recursive Function that considers all possible even divisors of cur ; Indicates impossible state ; Return 0 if cur == M ; Initially it is set to INF that means we can 't transform cur to M ; Loop to find even divisors of cur ; if i is divisor of cur ; if i is even ; Finding divisors recursively for cur + i ; Check another divisor ; Find recursively for cur + ( cur / i ) ; Return the answer ; Function that finds the minimum operation to reduce N to M ; INF indicates impossible state ; Driver Code ; Given N and M ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int INF = 1e7 ; int min_op ( int cur , int M ) { if ( cur > M ) return INF ; if ( cur == M ) return 0 ; int op = INF ; for ( int i = 2 ; i * i <= cur ; i ++ ) { if ( cur % i == 0 ) { if ( i % 2 == 0 ) { op = min ( op , 1 + min_op ( cur + i , M ) ) ; } if ( ( cur / i ) != i && ( cur / i ) % 2 == 0 ) { op = min ( op , 1 + min_op ( cur + ( cur / i ) , M ) ) ; } } } return op ; } int min_operations ( int N , int M ) { int op = min_op ( N , M ) ; if ( op >= INF ) cout << " - 1" ; else cout << op << " STRNEWLINE " ; } int main ( ) { int N = 6 , M = 24 ; min_operations ( N , M ) ; return 0 ; }
Minimum length of subsequence having unit GCD | C ++ program for the above approach ; Function that finds the prime factors of a number ; To store the prime factor ; 2 s that divide n ; N must be odd at this point Skip one element ; Update the prime factor ; If n is a prime number greater than 2 ; Function that finds the shortest subsequence ; Check if the prime factor of first number , is also the prime factor of the rest numbers in array ; Set corresponding bit of prime factor to 1 , it means both these numbers have the same prime factor ; If no states encountered so far continue for this combination of bits ; Update this state with minimum ways to reach this state ; Function that print the minimum length of subsequence ; Find the prime factors of the first number ; Initialize the array with maximum steps , size of the array + 1 for instance ; Total number of set bits is equal to the total number of prime factors ; Indicates there is one way to reach the number under consideration ; State 0 corresponds to gcd of 1 ; If not found such subsequence then print " - 1" ; Else print the length ; Driver code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findPrimeFactors ( int n ) { vector < int > primeFactors ( 9 , 0 ) ; int j = 0 ; if ( n % 2 == 0 ) { primeFactors [ j ++ ] = 2 ; while ( n % 2 == 0 ) n >>= 1 ; } for ( int i = 3 ; i * i <= n ; i += 2 ) { if ( n % i == 0 ) { primeFactors [ j ++ ] = i ; while ( n % i == 0 ) n /= i ; } } if ( n > 2 ) primeFactors [ j ++ ] = n ; vector < int > PrimeFactors ( j ) ; for ( int i = 0 ; i < j ; i ++ ) { PrimeFactors [ i ] = primeFactors [ i ] ; } return PrimeFactors ; } void findShortestSubsequence ( vector < int > & dp , vector < int > a , int index , vector < int > primeFactors ) { int n = a . size ( ) ; for ( int j = index ; j < n ; j ++ ) { int bitmask = 0 ; for ( int p = 0 ; p < primeFactors . size ( ) ; p ++ ) { if ( ( a [ j ] % primeFactors [ p ] ) == 0 ) { bitmask ^= ( 1 << p ) ; } } for ( int i = 0 ; i < dp . size ( ) ; i ++ ) { if ( dp [ i ] == n + 1 ) continue ; dp [ bitmask & i ] = min ( dp [ bitmask & i ] , dp [ i ] + 1 ) ; } } } void printMinimumLength ( vector < int > a ) { int Min = a . size ( ) + 1 ; for ( int i = 0 ; i < a . size ( ) - 1 ; i ++ ) { vector < int > primeFactors = findPrimeFactors ( a [ i ] ) ; int n = primeFactors . size ( ) ; vector < int > dp ( 1 << n , a . size ( ) + 1 ) ; int setBits = ( 1 << n ) - 1 ; dp [ setBits ] = 1 ; findShortestSubsequence ( dp , a , i + 1 , primeFactors ) ; Min = min ( dp [ 0 ] , Min ) ; } if ( Min == ( a . size ( ) + 1 ) ) cout << -1 << endl ; else cout << Min << endl ; } int main ( ) { vector < int > arr = { 2 , 6 , 12 , 3 } ; printMinimumLength ( arr ) ; return 0 ; }
Maximum sum of Bitwise XOR of all elements of two equal length subsets | C ++ program for the above approach ; Function that finds the maximum Bitwise XOR sum of the two subset ; Check if the current state is already computed ; Initialize answer to minimum value ; Iterate through all possible pairs ; Check whether ith bit and jth bit of mask is not set then pick the pair ; For all possible pairs find maximum value pick current a [ i ] , a [ j ] and set i , j th bits in mask ; Store the maximum value and return the answer ; Driver Code ; Given array arr [ ] ; Declare Initialize the dp states ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorSum ( int a [ ] , int n , int mask , int dp [ ] ) { if ( dp [ mask ] != -1 ) { return dp [ mask ] ; } int max_value = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( i != j && ( mask & ( 1 << i ) ) == 0 && ( mask & ( 1 << j ) ) == 0 ) { max_value = max ( max_value , ( a [ i ] ^ a [ j ] ) + xorSum ( a , n , ( mask | ( 1 << i ) | ( 1 << j ) ) , dp ) ) ; } } } return dp [ mask ] = max_value ; } int main ( ) { int n = 4 ; int arr [ ] = { 1 , 2 , 3 , 4 } ; int dp [ ( 1 << n ) + 5 ] ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << ( xorSum ( arr , n , 0 , dp ) ) ; }
Count of ways in which N can be represented as sum of Fibonacci numbers without repetition | C ++ program for the above approach ; Function to generate the fibonacci number ; First two number of fibonacci sqequence ; Function to find maximum ways to represent num as the sum of fibonacci number ; Generate the Canonical form of given number ; Reverse the number ; Base condition of dp1 and dp2 ; Iterate from 1 to cnt ; Calculate dp1 [ ] ; Calculate dp2 [ ] ; Return final ans ; Driver Code ; Function call to generate the fibonacci numbers ; Given Number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long fib [ 101 ] , dp1 [ 101 ] ; long long dp2 [ 101 ] , v [ 101 ] ; void fibonacci ( ) { fib [ 1 ] = 1 ; fib [ 2 ] = 2 ; for ( int i = 3 ; i <= 87 ; i ++ ) { fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] ; } } int find ( int num ) { int cnt = 0 ; for ( int i = 87 ; i > 0 ; i -- ) { if ( num >= fib [ i ] ) { v [ cnt ++ ] = i ; num -= fib [ i ] ; } } reverse ( v , v + cnt ) ; dp1 [ 0 ] = 1 ; dp2 [ 0 ] = ( v [ 0 ] - 1 ) / 2 ; for ( int i = 1 ; i < cnt ; i ++ ) { dp1 [ i ] = dp1 [ i - 1 ] + dp2 [ i - 1 ] ; dp2 [ i ] = ( ( v [ i ] - v [ i - 1 ] ) / 2 ) * dp2 [ i - 1 ] + ( ( v [ i ] - v [ i - 1 ] - 1 ) / 2 ) * dp1 [ i - 1 ] ; } return ( dp1 [ cnt - 1 ] + dp2 [ cnt - 1 ] ) ; } int main ( ) { fibonacci ( ) ; int num = 13 ; cout << find ( num ) ; return 0 ; }
Count of N | C ++ program for the above approach ; Function to find count of N - digit numbers with single digit XOR ; Range of numbers ; Calculate XOR of digits ; If XOR <= 9 , then increment count ; Print the count ; Driver Code ; Given number ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countNums ( int N ) { int l = ( int ) pow ( 10 , N - 1 ) ; int r = ( int ) pow ( 10 , N ) - 1 ; int count = 0 ; for ( int i = l ; i <= r ; i ++ ) { int xorr = 0 , temp = i ; while ( temp > 0 ) { xorr = xorr ^ ( temp % 10 ) ; temp /= 10 ; } if ( xorr <= 9 ) count ++ ; } cout << count ; } int main ( ) { int N = 2 ; countNums ( N ) ; }
Maximize length of Non | C ++ program to implement the above approach ; Function to find the maximum length non decreasing subarray by reversing at most one subarray ; dp [ i ] [ j ] be the longest subsequence of a [ 0. . . i ] with first j parts ; Maximum length sub - sequence of ( 0. . ) ; Maximum length sub - sequence of ( 0. . 1. . ) ; Maximum length sub - sequence of ( 0. . 1. .0 . . ) ; Maximum length sub - sequence of ( 0. . 1. .0 . .1 . . ) ; Find the max length subsequence ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void main_fun ( int arr [ ] , int n ) { int dp [ 4 ] [ n ] ; memset ( dp , 0 , sizeof ( dp [ 0 ] [ 0 ] * 4 * n ) ) ; if ( arr [ 0 ] == 0 ) dp [ 0 ] [ 0 ] = 1 ; else dp [ 1 ] [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + 1 ; else dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] ; } for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == 1 ) dp [ 1 ] [ i ] = max ( dp [ 1 ] [ i - 1 ] + 1 , dp [ 0 ] [ i - 1 ] + 1 ) ; else dp [ 1 ] [ i ] = dp [ 1 ] [ i - 1 ] ; } for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) { dp [ 2 ] [ i ] = max ( dp [ 2 ] [ i - 1 ] + 1 , max ( dp [ 1 ] [ i - 1 ] + 1 , dp [ 0 ] [ i - 1 ] + 1 ) ) ; } else dp [ 2 ] [ i ] = dp [ 2 ] [ i - 1 ] ; } for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == 1 ) { dp [ 3 ] [ i ] = max ( dp [ 3 ] [ i - 1 ] + 1 , max ( dp [ 2 ] [ i - 1 ] + 1 , max ( dp [ 1 ] [ i - 1 ] + 1 , dp [ 0 ] [ i - 1 ] + 1 ) ) ) ; } else dp [ 3 ] [ i ] = dp [ 3 ] [ i - 1 ] ; } int ans = max ( dp [ 2 ] [ n - 1 ] , max ( dp [ 1 ] [ n - 1 ] , max ( dp [ 0 ] [ n - 1 ] , dp [ 3 ] [ n - 1 ] ) ) ) ; cout << ( ans ) ; } int main ( ) { int n = 4 ; int arr [ ] = { 0 , 1 , 0 , 1 } ; main_fun ( arr , n ) ; return 0 ; }
Print the Maximum Subarray Sum | C ++ program for the above approach ; Function to print the elements of Subarray with maximum sum ; Initialize currMax and globalMax with first value of nums ; Iterate for all the elemensts of the array ; Update currMax ; Check if currMax is greater than globalMax ; Traverse in left direction to find start Index of subarray ; Decrement the start index ; Printing the elements of subarray with max sum ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void SubarrayWithMaxSum ( vector < int > & nums ) { int endIndex , currMax = nums [ 0 ] ; int globalMax = nums [ 0 ] ; for ( int i = 1 ; i < nums . size ( ) ; ++ i ) { currMax = max ( nums [ i ] , nums [ i ] + currMax ) ; if ( currMax > globalMax ) { globalMax = currMax ; endIndex = i ; } } int startIndex = endIndex ; while ( startIndex >= 0 ) { globalMax -= nums [ startIndex ] ; if ( globalMax == 0 ) break ; startIndex -- ; } for ( int i = startIndex ; i <= endIndex ; ++ i ) { cout << nums [ i ] << " ▁ " ; } } int main ( ) { vector < int > arr = { -2 , -5 , 6 , -2 , -3 , 1 , 5 , -6 } ; SubarrayWithMaxSum ( arr ) ; return 0 ; }
Count of distinct Primonacci Numbers in a given range [ L , R ] | C ++ program to implement the above approach ; Stores list of all primes ; Function to find all primes ; To mark the prime ones ; Initially all indices as prime ; If i is prime ; Set all multiples of i as non - prime ; Adding all primes to a list ; Function to return the count of Primonacci Numbers in the range [ l , r ] ; dp [ i ] contains ith Primonacci Number ; Stores the Primonacci Numbers ; Iterate over all smaller primes ; If Primonacci number lies within the range [ L , R ] ; Count of Primonacci Numbers ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; static vector < int > primes ; int M = 100005 ; void sieve ( ) { bool mark [ M ] ; for ( int i = 0 ; i < M ; i ++ ) mark [ i ] = false ; for ( int i = 2 ; i < M ; i ++ ) mark [ i ] = true ; for ( int i = 2 ; i * i < M ; i ++ ) { if ( mark [ i ] ) { for ( int j = i * i ; j < M ; j += i ) mark [ j ] = false ; } } for ( int i = 2 ; i < M ; i ++ ) if ( mark [ i ] ) primes . push_back ( i ) ; } void countPrimonacci ( int l , int r ) { vector < int > dp ; dp . push_back ( 1 ) ; dp . push_back ( 1 ) ; int i = 2 ; set < int > s ; while ( true ) { int x = 0 ; for ( int j = 0 ; j < primes . size ( ) ; j ++ ) { int p = primes [ j ] ; if ( p >= i ) break ; x += dp [ i - p ] ; } if ( x >= l && x <= r ) s . insert ( x ) ; if ( x > r ) break ; dp . push_back ( x ) ; i ++ ; } cout << s . size ( ) ; } int main ( ) { sieve ( ) ; int L = 1 , R = 10 ; countPrimonacci ( L , R ) ; }
Queries to count distinct Binary Strings of all lengths from N to M satisfying given properties | C ++ Program to implement the above approach ; Function to calculate the count of possible strings ; Initialize dp [ 0 ] ; dp [ i ] represents count of strings of length i ; Add dp [ i - k ] if i >= k ; Update Prefix Sum Array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1e5 + 5 ; const int MOD = 1000000007 ; long int dp [ N ] ; void countStrings ( int K , vector < vector < int > > Q ) { dp [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] = dp [ i - 1 ] ; if ( i >= K ) dp [ i ] = ( dp [ i ] + dp [ i - K ] ) % MOD ; } for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] = ( dp [ i ] + dp [ i - 1 ] ) % MOD ; } for ( int i = 0 ; i < Q . size ( ) ; i ++ ) { long int ans = dp [ Q [ i ] [ 1 ] ] - dp [ Q [ i ] [ 0 ] - 1 ] ; if ( ans < 0 ) ans = ans + MOD ; cout << ans << endl ; } } int main ( ) { int K = 3 ; vector < vector < int > > Q = { { 1 , 4 } , { 3 , 7 } } ; countStrings ( K , Q ) ; return 0 ; }
Minimum possible sum of prices of a Triplet from the given Array | C ++ program to implement the above approach ; Function to minimize the sum of price by taking a triplet ; Initialize a dp [ ] array ; Stores the final result ; Iterate for all values till N ; Check if num [ j ] > num [ i ] ; Update dp [ j ] if it is greater than stored value ; Update the minimum sum as ans ; If there is no minimum sum exist then print - 1 else print the ans ; Driver Code
#include <iostream> NEW_LINE #include <bits/stdc++.h> NEW_LINE using namespace std ; long minSum ( int n , int num [ ] , int price [ ] ) { long dp [ n ] ; for ( int i = 0 ; i < n ; i ++ ) dp [ i ] = INT_MAX ; long ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( num [ j ] > num [ i ] ) { dp [ j ] = ( long ) min ( ( long ) dp [ j ] , ( long ) price [ i ] + ( long ) price [ j ] ) ; ans = min ( ans , ( long ) dp [ i ] + ( long ) price [ j ] ) ; } } } return ans != INT_MAX ? ans : -1 ; } int main ( ) { int num [ ] = { 2 , 4 , 6 , 7 , 8 } ; int price [ ] = { 10 , 20 , 100 , 20 , 40 } ; int n = sizeof ( price ) / sizeof ( price [ 0 ] ) ; cout << ( minSum ( n , num , price ) ) ; }
Count of binary strings of length N having equal count of 0 ' s ▁ and ▁ 1' s and count of 1 ' s ▁ Γ’ ‰ Β₯ ▁ count ▁ of ▁ 0' s in each prefix substring | C ++ Program to implement the above approach ; Function to calculate and returns the value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate the value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Function to return the count of all binary strings having equal count of 0 ' s ▁ and ▁ 1' s and each prefix substring having frequency of 1 ' s ▁ > = ▁ frequencies ▁ of ▁ 0' s ; If N is odd ; No such strings possible ; Otherwise ; Calculate value of 2 nCn ; Return 2 nCn / ( n + 1 ) ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long int binomialCoeff ( unsigned int n , unsigned int k ) { unsigned long int res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } unsigned long int countStrings ( unsigned int N ) { if ( N % 2 == 1 ) return 0 ; else { N /= 2 ; unsigned long int c = binomialCoeff ( 2 * N , N ) ; return c / ( N + 1 ) ; } } int main ( ) { int N = 6 ; cout << countStrings ( N ) << " ▁ " ; return 0 ; }
Number of ways to cut a stick of length N into in even length at most K units long pieces | C ++ 14 program for the above approach ; Recursive Function to count the total number of ways ; Base case if no - solution exist ; Condition if a solution exist ; Check if already calculated ; Initialize counter ; Recursive call ; Store the answer ; Return the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int n , int k , int mod , int dp [ ] ) { if ( n < 0 ) return 0 ; if ( n == 0 ) return 1 ; if ( dp [ n ] != -1 ) return dp [ n ] ; int cnt = 0 ; for ( int i = 2 ; i <= k ; i += 2 ) { cnt = ( cnt % mod + solve ( n - i , k , mod , dp ) % mod ) % mod ; } dp [ n ] = cnt ; return cnt ; } int main ( ) { const int mod = 1e9 + 7 ; int n = 4 , k = 2 ; int dp [ n + 1 ] ; memset ( dp , -1 , sizeof ( dp ) ) ; int ans = solve ( n , k , mod , dp ) ; cout << ans << ' ' ; return 0 ; }
Number of ways to select exactly K even numbers from given Array | C ++ program for the above approach ; Function for calculating factorial ; Factorial of n defined as : n ! = n * ( n - 1 ) * ... * 1 ; Function to find the number of ways to select exactly K even numbers from the given array ; Count even numbers ; Check if the current number is even ; Check if the even numbers to be chosen is greater than n . Then , there is no way to pick it . ; The number of ways will be nCk ; Driver Code ; Given array arr [ ] ; Given count of even elements ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long f [ 12 ] ; void fact ( ) { f [ 0 ] = f [ 1 ] = 1 ; for ( int i = 2 ; i <= 10 ; i ++ ) f [ i ] = i * 1LL * f [ i - 1 ] ; } void solve ( int arr [ ] , int n , int k ) { fact ( ) ; int even = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) even ++ ; } if ( k > even ) cout << 0 << endl ; else { cout << f [ even ] / ( f [ k ] * f [ even - k ] ) ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof arr / sizeof arr [ 0 ] ; int k = 1 ; solve ( arr , n , k ) ; return 0 ; }
Count of binary strings of length N having equal count of 0 ' s ▁ and ▁ 1' s | C ++ Program to implement the above approach ; Function to calculate C ( n , r ) % MOD DP based approach ; Corner case ; Stores the last row of Pascal 's Triangle ; Initialize top row of pascal triangle ; Construct Pascal 's Triangle from top to bottom ; Fill current row with the help of previous row ; C ( n , j ) = C ( n - 1 , j ) + C ( n - 1 , j - 1 ) ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD 1000000007 NEW_LINE int nCrModp ( int n , int r ) { if ( n % 2 == 1 ) { return -1 ; } int C [ r + 1 ] ; memset ( C , 0 , sizeof ( C ) ) ; C [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = min ( i , r ) ; j > 0 ; j -- ) C [ j ] = ( C [ j ] + C [ j - 1 ] ) % MOD ; } return C [ r ] ; } int main ( ) { int N = 6 ; cout << nCrModp ( N , N / 2 ) ; return 0 ; }
Convert 1 into X in min steps by multiplying with 2 or 3 or by adding 1 | C ++ program for the above approach ; Function to print the Minimum number of operations required to convert 1 into X by using three given operations ; Initialize a DP array to store min operations for sub - problems ; Base Condition : No operation required when N is 1 ; Multiply the number by 2 ; Multiply the number by 3 ; Add 1 to the number . ; Print the minimum operations ; Initialize a list to store the sequence ; Backtrack to find the sequence ; If add by 1 ; If multiply by 2 ; If multiply by 3 ; Print the sequence of operation ; Driver code ; Given number X ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMinOperations ( int N ) { int dp [ N + 1 ] ; for ( int i = 0 ; i < N + 1 ; i ++ ) dp [ i ] = N ; dp [ 1 ] = 0 ; for ( int i = 2 ; i < N + 1 ; i ++ ) { if ( i % 2 == 0 && dp [ i ] > dp [ i / 2 ] + 1 ) dp [ i ] = dp [ i / 2 ] + 1 ; if ( i % 3 == 0 && dp [ i ] > dp [ i / 3 ] + 1 ) dp [ i ] = dp [ i / 3 ] + 1 ; if ( dp [ i ] > dp [ i - 1 ] + 1 ) dp [ i ] = dp [ i - 1 ] + 1 ; } cout << dp [ N ] << endl ; vector < int > seq ; while ( N > 1 ) { seq . push_back ( N ) ; if ( dp [ N - 1 ] == dp [ N ] - 1 ) N = N - 1 ; else if ( N % 2 == 0 && dp [ N / 2 ] == dp [ N ] - 1 ) N = N / 2 ; else N = N / 3 ; } seq . push_back ( 1 ) ; for ( int i = seq . size ( ) - 1 ; i >= 0 ; i -- ) cout << seq [ i ] << " ▁ " ; cout << endl ; } int main ( ) { int X = 96234 ; printMinOperations ( X ) ; }
Largest subsequence such that all indices and all values are multiples individually | C ++ program for the above approach ; Function that print maximum length of array ; dp [ ] array to store the maximum length ; Find all divisors of i ; If the current value is greater than the divisor 's value ; If current value is greater than the divisor 's value and s is not equal to current index ; Condition if current value is greater than the divisor 's value ; Computing the greatest value ; Printing maximum length of array ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxLength ( int arr [ ] , int n ) { vector < int > dp ( n , 1 ) ; for ( int i = n - 1 ; i > 1 ; i -- ) { for ( int j = 1 ; j <= sqrt ( i ) ; j ++ ) { if ( i % j == 0 ) { int s = i / j ; if ( s == j ) { if ( arr [ i ] > arr [ s ] ) { dp [ s ] = max ( dp [ i ] + 1 , dp [ s ] ) ; } } else { if ( s != i && arr [ i ] > arr [ s ] ) dp [ s ] = max ( dp [ i ] + 1 , dp [ s ] ) ; if ( arr [ i ] > arr [ j ] ) { dp [ j ] = max ( dp [ i ] + 1 , dp [ j ] ) ; } } } } } int max = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( dp [ i ] > max ) max = dp [ i ] ; } cout << max << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 0 , 1 , 4 , 2 , 3 , 6 , 4 , 9 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxLength ( arr , size ) ; return 0 ; }
Maximum profit by buying and selling a stock at most twice | Set 2 | C ++ implmenetation to find maximum possible profit with at most two transactions ; Function to find the maximum profit with two transactions on a given list of stock prices ; buy1 - Money lent to buy 1 stock profit1 - Profit after selling the 1 st stock buyed . buy2 - Money lent to buy 2 stocks including profit of selling 1 st stock profit2 - Profit after selling 2 stocks ; Set initial buying values to INT_MAX as we want to minimize it ; Set initial selling values to zero as we want to maximize it ; Money lent to buy the stock should be minimum as possible . buy1 tracks the minimum possible stock to buy from 0 to i - 1. ; Profit after selling a stock should be maximum as possible . profit1 tracks maximum possible profit we can make from 0 to i - 1. ; Now for buying the 2 nd stock , we will integrate profit made from selling the 1 st stock ; Profit after selling a 2 stocks should be maximum as possible . profit2 tracks maximum possible profit we can make from 0 to i - 1. ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProfit ( int price [ ] , int n ) { int buy1 , profit1 , buy2 , profit2 ; buy1 = buy2 = INT_MAX ; profit1 = profit2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { buy1 = min ( buy1 , price [ i ] ) ; profit1 = max ( profit1 , price [ i ] - buy1 ) ; buy2 = min ( buy2 , price [ i ] - profit1 ) ; profit2 = max ( profit2 , price [ i ] - buy2 ) ; } return profit2 ; } int main ( ) { int price [ ] = { 2 , 30 , 15 , 10 , 8 , 25 , 80 } ; int n = sizeof ( price ) / sizeof ( price [ 0 ] ) ; cout << " Maximum ▁ Profit ▁ = ▁ " << maxProfit ( price , n ) ; return 0 ; }
Maximum score of deleting an element from an Array based on given condition | C ++ implementation to find the maximum score of the deleting a element from an array ; Function to find the maximum score of the deleting an element from an array ; Creating a map to keep the frequency of numbers ; Loop to iterate over the elements of the array ; Creating a DP array to keep count of max score at ith element and it will be filled in the bottom Up manner ; Loop to choose the elements of the array to delete from the array ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaximumScore ( vector < int > a , int n ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < n ; i ++ ) { freq [ a [ i ] ] ++ ; } vector < int > dp ( * max_element ( a . begin ( ) , a . end ( ) ) + 1 , 0 ) ; dp [ 0 ] = 0 ; dp [ 1 ] = freq [ 1 ] ; for ( int i = 2 ; i < dp . size ( ) ; i ++ ) dp [ i ] = max ( dp [ i - 1 ] , dp [ i - 2 ] + freq [ i ] * i ) ; return dp [ dp . size ( ) - 1 ] ; } int main ( ) { int n ; n = 3 ; vector < int > a { 1 , 2 , 3 } ; cout << findMaximumScore ( a , n ) ; return 0 ; }
Reverse a subarray to maximize sum of even | C ++ program to implement the above approach ; Function to return maximized sum at even indices ; Stores difference with element on the left ; Stores difference with element on the right ; Compute and store left difference ; For first index ; If previous difference is positive ; Otherwise ; For the last index ; Otherwise ; For first index ; If the previous difference is positive ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximizeSum ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i = i + 2 ) sum += arr [ i ] ; int leftDP [ n / 2 ] ; int rightDP [ n / 2 ] ; int c = 0 ; for ( int i = 1 ; i < n ; i = i + 2 ) { int leftDiff = arr [ i ] - arr [ i - 1 ] ; if ( c - 1 < 0 ) leftDP = leftDiff ; else { if ( leftDP > 0 ) leftDP = leftDiff + leftDP ; else leftDP [ i ] = leftDiff ; } int rightDiff ; if ( i + 1 >= n ) rightDiff = 0 ; else rightDiff = arr [ i ] - arr [ i + 1 ] ; if ( c - 1 < 0 ) rightDP = rightDiff ; else { if ( rightDP > 0 ) rightDP = rightDiff + rightDP ; else rightDP = rightDiff ; } c ++ ; } int maxi = 0 ; for ( int i = 0 ; i < n / 2 ; i ++ ) { maxi = max ( maxi , max ( leftDP [ i ] , rightDP [ i ] ) ) ; } return maxi + sum ; } int main ( ) { int arr [ ] = { 7 , 8 , 4 , 5 , 7 , 6 , 8 , 9 , 7 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int ans = maximizeSum ( arr , n ) ; cout << ( ans ) ; }
Count of all subsequences having adjacent elements with different parity | C ++ Program to implement the above approach ; Function to find required subsequences ; dp [ i ] [ 0 ] : Stores the number of subsequences till i - th index ending with even element dp [ i ] [ 1 ] : Stores the number of subsequences till i - th index ending with odd element ; Initialise the dp [ ] [ ] with 0. ; If odd element is encountered ; Considering i - th element will be present in the subsequence ; Appending i - th element to all non - empty subsequences ending with even element till ( i - 1 ) th indexes ; Considering ith element will not be present in the subsequence ; Considering i - th element will be present in the subsequence ; Appending i - th element to all non - empty subsequences ending with odd element till ( i - 1 ) th indexes ; Considering ith element will not be present in the subsequence ; Count of all valid subsequences ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int validsubsequences ( int arr [ ] , int n ) { long long int dp [ n + 1 ] [ 2 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) { dp [ i ] [ 0 ] = 0 ; dp [ i ] [ 1 ] = 0 ; } for ( int i = 1 ; i <= n ; i ++ ) { if ( arr [ i - 1 ] % 2 ) { dp [ i ] [ 1 ] += 1 ; dp [ i ] [ 1 ] += dp [ i - 1 ] [ 0 ] ; dp [ i ] [ 1 ] += dp [ i - 1 ] [ 1 ] ; dp [ i ] [ 0 ] += dp [ i - 1 ] [ 0 ] ; } else { dp [ i ] [ 0 ] += 1 ; dp [ i ] [ 0 ] += dp [ i - 1 ] [ 1 ] ; dp [ i ] [ 0 ] += dp [ i - 1 ] [ 0 ] ; dp [ i ] [ 1 ] += dp [ i - 1 ] [ 1 ] ; } } return dp [ n ] [ 0 ] + dp [ n ] [ 1 ] ; } int main ( ) { int arr [ ] = { 5 , 6 , 9 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << validsubsequences ( arr , n ) ; return 0 ; }
Count of N | C ++ implementation of the above approach ; Function to return count of N - digit numbers with absolute difference of adjacent digits not exceeding K ; For 1 - digit numbers , the count is 10 ; dp [ i ] [ j ] stores the number of such i - digit numbers ending in j ; Initialize count for 1 - digit numbers ; Compute values for count of digits greater than 1 ; Find the range of allowed numbers if last digit is j ; Perform Range update ; Prefix sum to find actual values of i - digit numbers ending in j ; Stores the final answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long getCount ( int n , int k ) { if ( n == 1 ) return 10 ; long long dp [ n + 1 ] [ 11 ] ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j < 11 ; j ++ ) dp [ i ] [ j ] = 0 ; } for ( int i = 1 ; i <= 9 ; i ++ ) dp [ 1 ] [ i ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= 9 ; j ++ ) { int l = max ( 0 , j - k ) ; int r = min ( 9 , j + k ) ; dp [ i ] [ l ] += dp [ i - 1 ] [ j ] ; dp [ i ] [ r + 1 ] -= dp [ i - 1 ] [ j ] ; } for ( int j = 1 ; j <= 9 ; j ++ ) dp [ i ] [ j ] += dp [ i ] [ j - 1 ] ; } long long count = 0 ; for ( int i = 0 ; i <= 9 ; i ++ ) count += dp [ n ] [ i ] ; return count ; } int main ( ) { int N = 2 , K = 1 ; cout << getCount ( N , K ) ; }
Find if there is a path between two vertices in a directed graph | Set 2 | C ++ program to find if there is a path between two vertices in a directed graph using Dynamic Programming ; function to find if there is a path between two vertices in a directed graph ; dp matrix ; set dp [ i ] [ j ] = true if there is edge between i to j ; check for all intermediate vertex ; if vertex is invalid ; if there is a path ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define X 6 NEW_LINE #define Z 2 NEW_LINE bool existPath ( int V , int edges [ X ] [ Z ] , int u , int v ) { bool mat [ V ] [ V ] ; memset ( mat , false , sizeof ( mat ) ) ; for ( int i = 0 ; i < X ; i ++ ) mat [ edges [ i ] [ 0 ] ] [ edges [ i ] [ 1 ] ] = true ; for ( int k = 0 ; k < V ; k ++ ) { for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { mat [ i ] [ j ] = mat [ i ] [ j ] || mat [ i ] [ k ] && mat [ k ] [ j ] ; } } } if ( u >= V v >= V ) { return false ; } if ( mat [ u ] [ v ] ) return true ; return false ; } int main ( ) { int V = 4 ; int edges [ X ] [ Z ] = { { 0 , 2 } , { 0 , 1 } , { 1 , 2 } , { 2 , 3 } , { 2 , 0 } , { 3 , 3 } } ; int u = 1 , v = 3 ; if ( existPath ( V , edges , u , v ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; }
Maximize the numbers of splits in an Array having sum divisible by 3 | C ++ program for the above approach ; Prefix array storing right most index with prefix sums 0 , 1 , 2 ; dp array ; Current prefix sum ; Calculating the prefix sum modulo 3 ; We dont have a left pointer with prefix sum C ; We cannot consider i as a right pointer of any segment ; We have a left pointer pre [ C ] with prefix sum C ; i is the rightmost index of prefix sum C ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate_maximum_splits ( int arr [ ] , int N ) { int pre [ ] = { 0 , -1 , -1 } ; int dp [ N ] ; memset ( dp , 0 , sizeof ( dp ) ) ; int C = 0 ; for ( int i = 0 ; i < N ; i ++ ) { C = C + arr [ i ] ; C = C % 3 ; if ( pre [ C ] == -1 ) { dp [ i ] = dp [ i - 1 ] ; } else { dp [ i ] = max ( dp [ i - 1 ] , dp [ pre [ C ] ] + 1 ) ; } pre [ C ] = i ; } return dp [ N - 1 ] ; } int main ( ) { int arr [ ] = { 2 , 36 , 1 , 9 , 2 , 0 , 1 , 8 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( calculate_maximum_splits ( arr , N ) ) ; }
Count of elements having Euler 's Totient value one less than itself | C ++ program for the above approach ; Seiev of Erotosthenes method to compute all primes ; If current number is marked prime then mark its multiple as non - prime ; Function to count the number of element satisfying the condition ; Compute the number of primes in count prime array ; Print the number of elements satisfying the condition ; Driver Code ; Given array ; Size of the array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long prime [ 1000001 ] = { 0 } ; void seiveOfEratosthenes ( ) { for ( int i = 2 ; i < 1000001 ; i ++ ) { prime [ i ] = 1 ; } for ( int i = 2 ; i * i < 1000001 ; i ++ ) { if ( prime [ i ] == 1 ) { for ( int j = i * i ; j < 1000001 ; j += i ) { prime [ j ] = 0 ; } } } } void CountElements ( int arr [ ] , int n , int L , int R ) { seiveOfEratosthenes ( ) ; long long countPrime [ n + 1 ] = { 0 } ; for ( int i = 1 ; i <= n ; i ++ ) { countPrime [ i ] = countPrime [ i - 1 ] + prime [ arr [ i - 1 ] ] ; } cout << countPrime [ R ] - countPrime [ L - 1 ] << endl ; return ; } int main ( ) { int arr [ ] = { 2 , 4 , 5 , 8 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int L = 1 , R = 3 ; CountElements ( arr , N , L , R ) ; return 0 ; }
Count of elements having odd number of divisors in index range [ L , R ] for Q queries | C ++ program for the above approach ; Function count the number of elements having odd number of divisors ; Initialise dp [ ] array ; Precomputation ; Find the Prefix Sum ; Iterate for each query ; Find the answer for each query ; Driver Code ; Given array arr [ ] ; Given Query ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void OddDivisorsCount ( int n , int q , int a [ ] , vector < pair < int , int > > Query ) { int DP [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int x = sqrt ( a [ i ] ) ; if ( x * x == a [ i ] ) DP [ i ] = 1 ; } for ( int i = 1 ; i < n ; i ++ ) { DP [ i ] = DP [ i - 1 ] + DP [ i ] ; } int l , r ; for ( int i = 0 ; i < q ; i ++ ) { l = Query [ i ] . first ; r = Query [ i ] . second ; if ( l == 0 ) { cout << DP [ r ] << endl ; } else { cout << DP [ r ] - DP [ l - 1 ] << endl ; } } } int main ( ) { int N = 5 ; int Q = 3 ; int arr [ ] = { 2 , 4 , 5 , 6 , 9 } ; vector < pair < int , int > > Query Query = { { 0 , 2 } , { 1 , 3 } , { 1 , 4 } } ; OddDivisorsCount ( N , Q , arr , Query ) ; return 0 ; }
Number of ways to make exactly C components in a 2 * N matrix | C ++ implementation to find the number of ways to make exactly C components in a 2 * N matrix ; row1 and row2 are one when both are same colored ; Function to find the number of ways to make exactly C components in a 2 * N matrix ; if No of components at any stage exceeds the given number then base case ; Condition to check if already visited ; if not visited previously ; At the first column ; color { white , white } or { black , black } ; Color { white , black } or { black , white } ; If previous both rows have same color ; Fill with { same , same } and { white , black } and { black , white } ; Fill with same without increase in component as it has been counted previously ; When previous rows had { white , black } ; When previous rows had { black , white } ; Memoization ; Driver Code ; Initially at first column with 0 components
#include <bits/stdc++.h> NEW_LINE using namespace std ; int n , k ; int dp [ 1024 ] [ 2048 ] [ 2 ] [ 2 ] ; int Ways ( int col , int comp , int row1 , int row2 ) { if ( comp > k ) return 0 ; if ( col > n ) { if ( comp == k ) return 1 ; else return 0 ; } if ( dp [ col ] [ comp ] [ row1 ] [ row2 ] != -1 ) return dp [ col ] [ comp ] [ row1 ] [ row2 ] ; else { int ans = 0 ; if ( col == 1 ) { ans = ( ans + Ways ( col + 1 , comp + 1 , 0 , 0 ) + Ways ( col + 1 , comp + 1 , 1 , 1 ) ) ; ans = ( ans + Ways ( col + 1 , comp + 2 , 0 , 1 ) + Ways ( col + 1 , comp + 2 , 1 , 0 ) ) ; } else { if ( ( row1 && row2 ) || ( ! row1 && ! row2 ) ) { ans = ( ( ( ans + Ways ( col + 1 , comp + 1 , 0 , 0 ) ) + Ways ( col + 1 , comp + 1 , 1 , 0 ) ) + Ways ( col + 1 , comp + 1 , 0 , 1 ) ) ; ans = ( ans + Ways ( col + 1 , comp , 1 , 1 ) ) ; } if ( row1 && ! row2 ) { ans = ( ( ( ans + Ways ( col + 1 , comp , 0 , 0 ) ) + Ways ( col + 1 , comp , 1 , 1 ) ) + Ways ( col + 1 , comp , 1 , 0 ) ) ; ans = ( ans + Ways ( col + 1 , comp + 2 , 0 , 1 ) ) ; } if ( ! row1 && row2 ) { ans = ( ( ( ans + Ways ( col + 1 , comp , 0 , 0 ) ) + Ways ( col + 1 , comp , 1 , 1 ) ) + Ways ( col + 1 , comp , 0 , 1 ) ) ; ans = ( ans + Ways ( col + 1 , comp + 2 , 1 , 0 ) ) ; } } return dp [ col ] [ comp ] [ row1 ] [ row2 ] = ans ; } } signed main ( ) { n = 2 ; k = 1 ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << Ways ( 1 , 0 , 0 , 0 ) ; return 0 ; }
Find all possible ways to Split the given string into Primes | C ++ program to Find all the ways to split the given string into Primes . ; Sieve of Eratosthenes ; Function Convert integer to binary string ; Function print all the all the ways to split the given string into Primes . ; To store all possible strings ; Exponetnital complexity n * ( 2 ^ ( n - 1 ) ) for bit ; Pruning step ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool primes [ 1000000 ] ; const int maxn = 1000000 ; void sieve ( ) { memset ( primes , true , sizeof ( primes ) ) ; primes [ 0 ] = primes [ 1 ] = 0 ; for ( int i = 2 ; i * i <= maxn ; i ++ ) { if ( primes [ i ] ) { for ( int j = i * i ; j <= maxn ; j += i ) primes [ j ] = false ; } } } string toBinary ( int n ) { string r = " " ; while ( n != 0 ) { r = ( n % 2 == 0 ? "0" : "1" ) + r ; n /= 2 ; } return ( r == " " ) ? "0" : r ; } void PrimeSplit ( string str ) { string temp ; int cnt = 0 ; vector < string > ans ; int bt = 1 << ( str . size ( ) - 1 ) ; int n = str . size ( ) ; for ( int i = 0 ; i < bt ; i ++ ) { temp = toBinary ( i ) + "0" ; int j = 0 , x = n - temp . size ( ) , y ; while ( j < x ) { temp = "0" + temp ; j ++ ; } j = 0 ; x = 0 ; y = -1 ; string sp = " " , tp = " " ; bool flag = 0 ; while ( j < n ) { sp += str [ j ] ; if ( temp [ j ] == '1' ) { tp += sp + ' , ' ; y = stoi ( sp ) ; if ( ! primes [ y ] ) { flag = 1 ; break ; } sp = " " ; } j ++ ; } tp += sp ; if ( sp != " " ) { y = stoi ( sp ) ; if ( ! primes [ y ] ) flag = 1 ; } if ( ! flag ) ans . push_back ( tp ) ; } if ( ans . size ( ) == 0 ) { cout << -1 << endl ; } for ( auto i : ans ) { cout << i << endl ; } } int main ( ) { string str = "11373" ; sieve ( ) ; PrimeSplit ( str ) ; return 0 ; }
Count of subsequences of length 4 in form ( x , x , x + 1 , x + 1 ) | Set 2 | C ++ program for the above approach ; Function to count the numbers ; Array that stores the digits from left to right ; Array that stores the digits from right to left ; Initially both array store zero ; Fill the table for count1 array ; Update the count of current character ; Fill the table for count2 array ; Update the count of cuuent character ; Variable that stores the count of the numbers ; Traverse Input string and get the count of digits from count1 and count2 array such that difference b / w digit is 1 & store it int c1 & c2 . And store it in variable c1 and c2 ; Update the ans ; Return the final count ; Driver Code ; Given String ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countStableNum ( string str , int N ) { int count1 [ N ] [ 10 ] ; int count2 [ N ] [ 10 ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < 10 ; j ++ ) count1 [ i ] [ j ] = count2 [ i ] [ j ] = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i != 0 ) { for ( int j = 0 ; j < 10 ; j ++ ) { count1 [ i ] [ j ] += count1 [ i - 1 ] [ j ] ; } } count1 [ i ] [ str [ i ] - '0' ] ++ ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( i != N - 1 ) { for ( int j = 0 ; j < 10 ; j ++ ) { count2 [ i ] [ j ] += count2 [ i + 1 ] [ j ] ; } } count2 [ i ] [ str [ i ] - '0' ] ++ ; } int ans = 0 ; for ( int i = 1 ; i < N - 1 ; i ++ ) { if ( str [ i ] == '9' ) continue ; int c1 = count1 [ i - 1 ] [ str [ i ] - '0' ] ; int c2 = count2 [ i + 1 ] [ str [ i ] - '0' + 1 ] ; if ( c2 == 0 ) continue ; ans = ( ans + ( c1 * ( ( c2 * ( c2 - 1 ) / 2 ) ) ) ) ; } return ans ; } int main ( ) { string str = "224353" ; int N = str . length ( ) ; cout << countStableNum ( str , N ) ; return 0 ; }
Count of subsequences in an array with sum less than or equal to X | C ++ Program to count number of subsequences in an array with sum less than or equal to X ; Utility function to return the count of subsequence in an array with sum less than or equal to X ; Base condition ; Return if the sub - problem is already calculated ; Check if the current element is less than or equal to sum ; Count subsequences excluding the current element ; Count subsequences including the current element ; Exclude current element ; Return the result ; Function to return the count of subsequence in an array with sum less than or equal to X ; Initialize a DP array ; Return the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubsequenceUtil ( int ind , int sum , int * A , int N , vector < vector < int > > & dp ) { if ( ind == N ) return 1 ; if ( dp [ ind ] [ sum ] != -1 ) return dp [ ind ] [ sum ] ; if ( A [ ind ] <= sum ) { dp [ ind ] [ sum ] = countSubsequenceUtil ( ind + 1 , sum , A , N , dp ) + countSubsequenceUtil ( ind + 1 , sum - A [ ind ] , A , N , dp ) ; } else { dp [ ind ] [ sum ] = countSubsequenceUtil ( ind + 1 , sum , A , N , dp ) ; } return dp [ ind ] [ sum ] ; } int countSubsequence ( int * A , int N , int X ) { vector < vector < int > > dp ( N , vector < int > ( X + 1 , -1 ) ) ; return countSubsequenceUtil ( 0 , X , A , N , dp ) - 1 ; } int main ( ) { int arr [ ] = { 25 , 13 , 40 } , X = 50 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSubsequence ( arr , N , X ) ; return 0 ; }
Count possible decodings of a given Digit Sequence | Set 2 | C ++ implementation to count the possible decodings of the given digit sequence ; Function to count the number of ways to decode the given digit sequence ; Array to store the dp states ; Case of empty string ; Condition to check if the first character of string is 0 ; Base case for single length string ; Bottom - up dp for the string ; Previous character ; Current character ; Case to include the Current digit as a single digit for decoding the string ; Case to include the current character as two - digit for decoding the string ; Condition to check if the current character is " * " ; Condition to check if the current character is less than or equal to 26 ; Condition to check if the Previous digit is equal to " * " ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int waysToDecode2 ( string s ) { int n = s . size ( ) ; vector < int > dp ( n + 1 , 0 ) ; dp [ 0 ] = 1 ; if ( s [ 0 ] == '0' ) return 0 ; dp [ 1 ] = ( ( s [ 0 ] == ' * ' ) ? 9 : 1 ) ; for ( int i = 2 ; i <= n ; i ++ ) { char first = s [ i - 2 ] ; char second = s [ i - 1 ] ; if ( second == ' * ' ) { dp [ i ] += 9 * dp [ i - 1 ] ; } else if ( second > '0' ) dp [ i ] += dp [ i - 1 ] ; if ( first == '1' first == '2' ) { if ( second == ' * ' ) { if ( first == '1' ) dp [ i ] += 9 * dp [ i - 2 ] ; else if ( first == '2' ) dp [ i ] += 6 * dp [ i - 2 ] ; } else if ( ( ( first - '0' ) * 10 + ( second - '0' ) ) <= 26 ) dp [ i ] += dp [ i - 2 ] ; } else if ( first == ' * ' ) { if ( second == ' * ' ) { dp [ i ] += 15 * dp [ i - 2 ] ; } else if ( second <= '6' ) dp [ i ] += 2 * dp [ i - 2 ] ; else dp [ i ] += dp [ i - 2 ] ; } } return dp [ n ] ; } int main ( ) { string str = "12*3" ; cout << waysToDecode2 ( str ) << endl ; return 0 ; }
Maximize occurrences of values between L and R on sequential addition of Array elements with modulo H | C ++ implementation of the above approach ; Function that prints the number of times X gets a value between L and R ; Base condition ; Condition if X can be made equal to j after i additions ; Compute value of X after adding arr [ i ] ; Compute value of X after adding arr [ i ] - 1 ; Update dp as the maximum value ; Compute maximum answer from all possible cases ; Printing maximum good occurrence of X ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void goodInteger ( int arr [ ] , int n , int h , int l , int r ) { vector < vector < int > > dp ( n + 1 , vector < int > ( h , -1 ) ) ; dp [ 0 ] [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < h ; j ++ ) { if ( dp [ i ] [ j ] != -1 ) { int h1 = ( j + arr [ i ] ) % h ; int h2 = ( j + arr [ i ] - 1 ) % h ; dp [ i + 1 ] [ h1 ] = max ( dp [ i + 1 ] [ h1 ] , dp [ i ] [ j ] + ( h1 >= l && h1 <= r ) ) ; dp [ i + 1 ] [ h2 ] = max ( dp [ i + 1 ] [ h2 ] , dp [ i ] [ j ] + ( h2 >= l && h2 <= r ) ) ; } } } int ans = 0 ; for ( int i = 0 ; i < h ; i ++ ) { if ( dp [ n ] [ i ] != -1 ) ans = max ( ans , dp [ n ] [ i ] ) ; } cout << ans << " STRNEWLINE " ; } int main ( ) { int A [ ] = { 16 , 17 , 14 , 20 , 20 , 11 , 22 } ; int H = 24 ; int L = 21 ; int R = 23 ; int size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; goodInteger ( A , size , H , L , R ) ; return 0 ; }
Range queries for alternatively addition and subtraction on given Array | C ++ program for the above approach ; Structure to represent a query ; This function fills the Prefix Array ; Initialise the prefix array ; Iterate all the element of arr [ ] and update the prefix array ; If n is even then , add the previous value of prefix array with the current value of arr ; if n is odd , then subtract the previous value of prefix Array from current value ; Function to find the result of alternatively adding and subtracting elements in the range [ L < R ] ; Case 1 : when L is zero ; Case 2 : When L is non zero ; If L is odd means range starts from odd position multiply result by - 1 ; Return the final result ; Function to find the sum of all alternative add and subtract between ranges [ L , R ] ; Declare prefix array ; Function Call to fill prefix arr [ ] ; Iterate for each query ; Driver Code ; Given array ; Given Queries ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Query { int L , R ; } ; void fillPrefixArray ( int arr [ ] , int n , int prefixArray [ ] ) { prefixArray [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { prefixArray [ i ] = prefixArray [ i - 1 ] + arr [ i ] ; } else { prefixArray [ i ] = prefixArray [ i - 1 ] - arr [ i ] ; } } } int findResultUtil ( int prefixArray [ ] , int L , int R ) { int result ; if ( L == 0 ) { result = prefixArray [ R ] ; } else { result = prefixArray [ R ] - prefixArray [ L - 1 ] ; } if ( L & 1 ) { result = result * ( -1 ) ; } return result ; } void findResult ( int arr [ ] , int n , Query q [ ] , int m ) { int prefixArray [ n ] ; fillPrefixArray ( arr , n , prefixArray ) ; for ( int i = 0 ; i < m ; i ++ ) { cout << findResultUtil ( prefixArray , q [ i ] . L , q [ i ] . R ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Query q [ ] = { { 2 , 5 } , { 6 , 8 } , { 1 , 7 } , { 4 , 8 } , { 0 , 5 } } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; findResult ( arr , n , q , m ) ; return 0 ; }
Longest subarray whose elements can be made equal by maximum K increments | C ++ code for the above approach ; Function to find maximum possible length of subarray ; Stores the sum of elements that needs to be added to the sub array ; Stores the index of the current position of subarray ; Stores the maximum length of subarray . ; Maximum element from each subarray length ; Previous index of the current subarray of maximum length ; Deque to store the indices of maximum element of each sub array ; For each array element , find the maximum length of required subarray ; Traverse the deque and update the index of maximum element . ; If it is first element then update maximum and dp [ ] ; Else check if current element exceeds max ; Update max and dp [ ] ; Update the index of the current maximum length subarray ; While current element being added to dp [ ] array exceeds K ; Update index of current position and the previous position ; Remove elements from deque and update the maximum element ; Update the maximum length of the required subarray . ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int validSubArrLength ( int arr [ ] , int N , int K ) { int dp [ N + 1 ] ; int pos = 0 ; int ans = 0 ; int mx = 0 ; int pre = 0 ; deque < int > q ; for ( int i = 0 ; i < N ; i ++ ) { while ( ! q . empty ( ) && arr [ q . back ( ) ] < arr [ i ] ) q . pop_back ( ) ; q . push_back ( i ) ; if ( i == 0 ) { mx = arr [ i ] ; dp [ i ] = arr [ i ] ; } else if ( mx <= arr [ i ] ) { dp [ i ] = dp [ i - 1 ] + arr [ i ] ; mx = arr [ i ] ; } else { dp [ i ] = dp [ i - 1 ] + arr [ i ] ; } if ( pre == 0 ) pos = 0 ; else pos = pre - 1 ; while ( ( i - pre + 1 ) * mx - ( dp [ i ] - dp [ pos ] ) > K && pre < i ) { pos = pre ; pre ++ ; while ( ! q . empty ( ) && q . front ( ) < pre && pre < i ) { q . pop_front ( ) ; mx = arr [ q . front ( ) ] ; } } ans = max ( ans , i - pre + 1 ) ; } return ans ; } int main ( ) { int N = 6 ; int K = 8 ; int arr [ ] = { 2 , 7 , 1 , 3 , 4 , 5 } ; cout << validSubArrLength ( arr , N , K ) ; return 0 ; }
Partition of a set into K subsets with equal sum using BitMask and DP | C ++ program to check if the given array can be partitioned into K subsets with equal sum ; Function to check whether K required partitions are possible or not ; Return true as the entire array is the answer ; If total number of partitions exceeds size of the array ; If the array sum is not divisible by K ; No such partitions are possible ; Required sum of each subset ; Initialize dp array with - 1 ; Sum of empty subset is zero ; Iterate over all subsets / masks ; if current mask is invalid , continue ; Iterate over all array elements ; Check if the current element can be added to the current subset / mask ; transition ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isKPartitionPossible ( int arr [ ] , int N , int K ) { if ( K == 1 ) return true ; if ( N < K ) return false ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; if ( sum % K != 0 ) return false ; int target = sum / K ; int dp [ ( 1 << 15 ) ] ; for ( int i = 0 ; i < ( 1 << N ) ; i ++ ) dp [ i ] = -1 ; dp [ 0 ] = 0 ; for ( int mask = 0 ; mask < ( 1 << N ) ; mask ++ ) { if ( dp [ mask ] == -1 ) continue ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! ( mask & ( 1 << i ) ) && dp [ mask ] + arr [ i ] <= target ) { dp [ mask ( 1 << i ) ] = ( dp [ mask ] + arr [ i ] ) % target ; } } } if ( dp [ ( 1 << N ) - 1 ] == 0 ) return true ; else return false ; } int main ( ) { int arr [ ] = { 2 , 1 , 4 , 5 , 3 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; if ( isKPartitionPossible ( arr , N , K ) ) { cout << " Partitions ▁ into ▁ equal ▁ " ; cout << " sum ▁ is ▁ possible . STRNEWLINE " ; } else { cout << " Partitions ▁ into ▁ equal ▁ " ; cout << " sum ▁ is ▁ not ▁ possible . STRNEWLINE " ; } }
Minimum cost path in a Matrix by moving only on value difference of X | C ++ implementation to find the minimum number of operations required to move from ( 1 , 1 ) to ( N , M ) ; Function to find the minimum operations required to move to bottom - right cell of matrix ; Condition to check if the current cell is the bottom - right cell of the matrix ; Condition to check if the current cell is out of matrix ; Condition to check if the current indices is already computed ; Condition to check that the movement with the current value is not possible ; Recursive call to compute the number of operation required to compute the value ; Function to find the minimum number of operations required to reach the bottom - right cell ; Loop to iterate over every possible cell of the matrix ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const long long MAX = 1e18 ; long long n , m ; vector < long long > v [ 151 ] ; long long dp [ 151 ] [ 151 ] ; long long min_operation ( long long i , long long j , long long val , long long x ) { if ( i == n - 1 && j == m - 1 ) { if ( val > v [ i ] [ j ] ) { return dp [ i ] [ j ] = MAX ; } else { return dp [ i ] [ j ] = v [ i ] [ j ] - val ; } } if ( i == n j == m ) { return dp [ i ] [ j ] = MAX ; } if ( dp [ i ] [ j ] != -1 ) { return dp [ i ] [ j ] ; } if ( val > v [ i ] [ j ] ) { return dp [ i ] [ j ] = MAX ; } long long tmp = v [ i ] [ j ] - val ; tmp += min ( min_operation ( i + 1 , j , val + x , x ) , min_operation ( i , j + 1 , val + x , x ) ) ; return dp [ i ] [ j ] = tmp ; } long long solve ( long long x ) { long long ans = INT64_MAX ; for ( long long i = 0 ; i < n ; i ++ ) { for ( long long j = 0 ; j < m ; j ++ ) { long long val = v [ i ] [ j ] - x * ( i + j ) ; memset ( dp , -1 , sizeof ( dp ) ) ; val = min_operation ( 0 , 0 , val , x ) ; ans = min ( ans , val ) ; } } return ans ; } int main ( ) { n = 2 , m = 2 ; long long x = 3 ; v [ 0 ] = { 15 , 153 } ; v [ 1 ] = { 135 , 17 } ; cout << solve ( x ) << endl ; return 0 ; }
Minimum count of numbers required from given array to represent S | C ++ implementation to find the minimum number of sequence required from array such that their sum is equal to given S ; Function to find the minimum elements required to get the sum of given value S ; Condition if the sequence is found ; Condition when no such sequence found ; Calling for without choosing the current index value ; Calling for after choosing the current index value ; Function for every array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int printAllSubsetsRec ( int arr [ ] , int n , vector < int > v , int sum ) { if ( sum == 0 ) { return ( int ) v . size ( ) ; } if ( sum < 0 ) return INT_MAX ; if ( n == 0 ) return INT_MAX ; int x = printAllSubsetsRec ( arr , n - 1 , v , sum ) ; v . push_back ( arr [ n - 1 ] ) ; int y = printAllSubsetsRec ( arr , n , v , sum - arr [ n - 1 ] ) ; return min ( x , y ) ; } int printAllSubsets ( int arr [ ] , int n , int sum ) { vector < int > v ; return printAllSubsetsRec ( arr , n , v , sum ) ; } int main ( ) { int arr [ ] = { 2 , 1 , 4 , 3 , 5 , 6 } ; int sum = 6 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << printAllSubsets ( arr , n , sum ) << endl ; return 0 ; }
Minimum count of numbers required from given array to represent S | C ++ implementation to find the minimum number of sequence required from array such that their sum is equal to given S ; Function to find the count of minimum length of the sequence ; Loop to initialize the array as infinite in the row 0 ; Loop to find the solution by pre - computation for the sequence ; Minimum possible for the previous minimum value of the sequence ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Count ( int S [ ] , int m , int n ) { vector < vector < int > > table ( m + 1 , vector < int > ( n + 1 , 0 ) ) ; for ( int i = 1 ; i <= n ; i ++ ) { table [ 0 ] [ i ] = INT_MAX - 1 ; } for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( S [ i - 1 ] > j ) { table [ i ] [ j ] = table [ i - 1 ] [ j ] ; } else { table [ i ] [ j ] = min ( table [ i - 1 ] [ j ] , table [ i ] [ j - S [ i - 1 ] ] + 1 ) ; } } } return table [ m ] [ n ] ; } int main ( ) { int arr [ ] = { 9 , 6 , 5 , 1 } ; int m = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << Count ( arr , m , 11 ) ; return 0 ; }
Maximize product of same | C ++ implementation to maximize product of same - indexed elements of same size subsequences ; Utility function to find the maximum ; Utility function to find the maximum scalar product from the equal length sub - sequences taken from the two given array ; Return a very small number if index is invalid ; If the sub - problem is already evaluated , then return it ; Take the maximum of all the recursive cases ; Function to find maximum scalar product from same size sub - sequences taken from the two given array ; Initialize a 2 - D array for memoization ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define INF 10000000 NEW_LINE int maximum ( int A , int B , int C , int D ) { return max ( max ( A , B ) , max ( C , D ) ) ; } int maxProductUtil ( int X , int Y , int * A , int * B , vector < vector < int > > & dp ) { if ( X < 0 or Y < 0 ) return - INF ; if ( dp [ X ] [ Y ] != -1 ) return dp [ X ] [ Y ] ; dp [ X ] [ Y ] = maximum ( A [ X ] * B [ Y ] + maxProductUtil ( X - 1 , Y - 1 , A , B , dp ) , A [ X ] * B [ Y ] , maxProductUtil ( X - 1 , Y , A , B , dp ) , maxProductUtil ( X , Y - 1 , A , B , dp ) ) ; return dp [ X ] [ Y ] ; } int maxProduct ( int A [ ] , int N , int B [ ] , int M ) { vector < vector < int > > dp ( N , vector < int > ( M , -1 ) ) ; return maxProductUtil ( N - 1 , M - 1 , A , B , dp ) ; } int main ( ) { int a [ ] = { -2 , 6 , -2 , -5 } ; int b [ ] = { -3 , 4 , -2 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 0 ] ) ; cout << maxProduct ( a , n , b , m ) ; }
Check if one string can be converted to other using given operation | C ++ implementation of above approach ; Function that prints whether is it possible to make a string equal to T by performing given operations ; Base case , if we put the last character at front of A ; Base case , if we put the last character at back of A ; Condition if current sequence is matchable ; Condition for front move to ( i - 1 ) th character ; Condition for back move to ( i - 1 ) th character ; Condition if it is possible to make string A equal to string T ; Print final answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void twoStringsEquality ( string s , string t ) { int n = s . length ( ) ; vector < vector < int > > dp ( n , vector < int > ( n + 1 , 0 ) ) ; if ( s [ n - 1 ] == t [ 0 ] ) dp [ n - 1 ] [ 1 ] = 1 ; if ( s [ n - 1 ] == t [ n - 1 ] ) dp [ n - 1 ] [ 0 ] = 1 ; for ( int i = n - 1 ; i > 0 ; i -- ) { for ( int j = 0 ; j <= n - i ; j ++ ) { if ( dp [ i ] [ j ] ) { if ( s [ i - 1 ] == t [ j ] ) dp [ i - 1 ] [ j + 1 ] = 1 ; if ( s [ i - 1 ] == t [ i + j - 1 ] ) dp [ i - 1 ] [ j ] = 1 ; } } } bool ans = false ; for ( int i = 0 ; i <= n ; i ++ ) { if ( dp [ 0 ] [ i ] == 1 ) { ans = true ; break ; } } if ( ans == true ) cout << " Yes " << " STRNEWLINE " ; else cout << " No " << " STRNEWLINE " ; } int main ( ) { string S = " abab " ; string T = " baab " ; twoStringsEquality ( S , T ) ; return 0 ; }
Maximize sum of all elements which are not a part of the Longest Increasing Subsequence | C ++ program to find the Maximum sum of all elements which are not a part of longest increasing sub sequence ; Function to find maximum sum ; Find total sum of array ; Maintain a 2D array ; Update the dp array along with sum in the second row ; In case of greater length Update the length along with sum ; In case of equal length find length update length with minimum sum ; Find the sum that need to be subtracted from total sum ; Return the sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int * arr , int n ) { int totalSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { totalSum += arr [ i ] ; } int dp [ 2 ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { dp [ 0 ] [ i ] = 1 ; dp [ 1 ] [ i ] = arr [ i ] ; } for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ i ] > arr [ j ] ) { if ( dp [ 0 ] [ i ] < dp [ 0 ] [ j ] + 1 ) { dp [ 0 ] [ i ] = dp [ 0 ] [ j ] + 1 ; dp [ 1 ] [ i ] = dp [ 1 ] [ j ] + arr [ i ] ; } else if ( dp [ 0 ] [ i ] == dp [ 0 ] [ j ] + 1 ) { dp [ 1 ] [ i ] = min ( dp [ 1 ] [ i ] , dp [ 1 ] [ j ] + arr [ i ] ) ; } } } } int maxm = 0 ; int subtractSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( dp [ 0 ] [ i ] > maxm ) { maxm = dp [ 0 ] [ i ] ; subtractSum = dp [ 1 ] [ i ] ; } else if ( dp [ 0 ] [ i ] == maxm ) { subtractSum = min ( subtractSum , dp [ 1 ] [ i ] ) ; } } return totalSum - subtractSum ; } int main ( ) { int arr [ ] = { 4 , 6 , 1 , 2 , 3 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSum ( arr , n ) ; return 0 ; }
Count of possible permutations of a number represented as a sum of 2 ' s , ▁ 4' s and 6 's only | C ++ code for above implementation ; Returns number of ways to reach score n ; table [ i ] will store count of solutions for value i . ; Initialize all table values as 0 ; Base case ( If given value is 0 , 1 , 2 , or 4 ) ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int n ) { if ( n == 2 ) return 1 ; else if ( n == 4 ) return 2 ; else if ( n == 6 ) return 4 ; int table [ n + 1 ] , i ; for ( i = 0 ; i < n + 1 ; i ++ ) table [ i ] = 0 ; table [ 0 ] = 0 ; table [ 2 ] = 1 ; table [ 4 ] = 2 ; table [ 6 ] = 4 ; for ( i = 8 ; i <= n ; i = i + 2 ) { table [ i ] = table [ i - 2 ] + table [ i - 4 ] + table [ i - 6 ] ; } return table [ n ] ; } int main ( void ) { int n = 8 ; cout << count ( n ) ; return 0 ; }
Count of ways to split a given number into prime segments | C ++ implementation to count total number of ways to split a string to get prime numbers ; Function to check whether a number is a prime number or not ; Function to find the count of ways to split string into prime numbers ; 1 based indexing ; Consider every suffix up to 6 digits ; Number should not have a leading zero and it should be a prime number ; Return the final result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD 1000000007 NEW_LINE bool isPrime ( string number ) { int num = stoi ( number ) ; for ( int i = 2 ; i * i <= num ; i ++ ) if ( ( num % i ) == 0 ) return false ; return num > 1 ? true : false ; } int countPrimeStrings ( string & number , int i ) { if ( i == 0 ) return 1 ; int cnt = 0 ; for ( int j = 1 ; j <= 6 ; j ++ ) { if ( i - j >= 0 && number [ i - j ] != '0' && isPrime ( number . substr ( i - j , j ) ) ) { cnt += countPrimeStrings ( number , i - j ) ; cnt %= MOD ; } } return cnt ; } int main ( ) { string s1 = "3175" ; int l = s1 . length ( ) ; cout << countPrimeStrings ( s1 , l ) ; return 0 ; }
Count of ways to split a given number into prime segments | C ++ implementation to count total number of ways to split a string to get prime numbers ; Function to build sieve ; If p is a prime ; Update all multiples of p as non prime ; Function to check whether a number is a prime number or not ; Function to find the count of ways to split string into prime numbers ; Number should not have a leading zero and it should be a prime number ; Function to count the number of prime strings ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = 1000000007 ; bool sieve [ 1000000 ] ; void buildSieve ( ) { for ( auto & i : sieve ) i = true ; sieve [ 0 ] = false ; sieve [ 1 ] = false ; for ( int p = 2 ; p * p <= 1000000 ; p ++ ) { if ( sieve [ p ] == true ) { for ( int i = p * p ; i <= 1000000 ; i += p ) sieve [ i ] = false ; } } } bool isPrime ( string number ) { int num = stoi ( number ) ; return sieve [ num ] ; } int rec ( string & number , int i , vector < int > & dp ) { if ( dp [ i ] != -1 ) return dp [ i ] ; int cnt = 0 ; for ( int j = 1 ; j <= 6 ; j ++ ) { if ( i - j >= 0 && number [ i - j ] != '0' && isPrime ( number . substr ( i - j , j ) ) ) { cnt += rec ( number , i - j , dp ) ; cnt %= MOD ; } } return dp [ i ] = cnt ; } int countPrimeStrings ( string & number ) { int n = number . length ( ) ; vector < int > dp ( n + 1 , -1 ) ; dp [ 0 ] = 1 ; return rec ( number , n , dp ) ; } int main ( ) { buildSieve ( ) ; string s1 = "3175" ; cout << countPrimeStrings ( s1 ) << " STRNEWLINE " ; return 0 ; }
Check if a matrix contains a square submatrix with 0 as boundary element | C ++ implementation of the above approach ; Function checks if square with all 0 's in boundary exists in the matrix ; r1 is the top row , c1 is the left col r2 is the bottom row , c2 is the right ; Function checks if the boundary of the square consists of 0 's ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool hasSquareOfZeroes ( vector < vector < int > > & matrix , int r1 , int c1 , int r2 , int c2 , unordered_map < string , bool > & cache ) ; bool isSquareOfZeroes ( vector < vector < int > > & matrix , int r1 , int c1 , int r2 , int c2 ) ; bool squareOfZeroes ( vector < vector < int > > matrix ) { int lastIdx = matrix . size ( ) - 1 ; unordered_map < string , bool > cache ; return hasSquareOfZeroes ( matrix , 0 , 0 , lastIdx , lastIdx , cache ) ; } bool hasSquareOfZeroes ( vector < vector < int > > & matrix , int r1 , int c1 , int r2 , int c2 , unordered_map < string , bool > & cache ) { if ( r1 >= r2 c1 >= c2 ) return false ; string key = to_string ( r1 ) + ' - ' + to_string ( c1 ) + ' - ' + to_string ( r2 ) + ' - ' + to_string ( c2 ) ; if ( cache . find ( key ) != cache . end ( ) ) return cache [ key ] ; cache [ key ] = isSquareOfZeroes ( matrix , r1 , c1 , r2 , c2 ) || hasSquareOfZeroes ( matrix , r1 + 1 , c1 + 1 , r2 - 1 , c2 - 1 , cache ) || hasSquareOfZeroes ( matrix , r1 , c1 + 1 , r2 - 1 , c2 , cache ) || hasSquareOfZeroes ( matrix , r1 + 1 , c1 , r2 , c2 - 1 , cache ) || hasSquareOfZeroes ( matrix , r1 + 1 , c1 + 1 , r2 , c2 , cache ) || hasSquareOfZeroes ( matrix , r1 , c1 , r2 - 1 , c2 - 1 , cache ) ; return cache [ key ] ; } bool isSquareOfZeroes ( vector < vector < int > > & matrix , int r1 , int c1 , int r2 , int c2 ) { for ( int row = r1 ; row < r2 + 1 ; row ++ ) { if ( matrix [ row ] [ c1 ] != 0 matrix [ row ] [ c2 ] != 0 ) return false ; } for ( int col = c1 ; col < c2 + 1 ; col ++ ) { if ( matrix [ r1 ] [ col ] != 0 matrix [ r2 ] [ col ] != 0 ) return false ; } return true ; } int main ( ) { vector < vector < int > > matrix { { 1 , 1 , 1 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 , 0 , 1 } , { 0 , 1 , 1 , 1 , 0 , 1 } , { 0 , 0 , 0 , 1 , 0 , 1 } , { 0 , 1 , 1 , 1 , 0 , 1 } , { 0 , 0 , 0 , 0 , 0 , 1 } } ; int ans ; ans = squareOfZeroes ( matrix ) ; if ( ans == 1 ) { cout << " True " << endl ; } else { cout << " False " << endl ; } }
Number of ways to obtain each numbers in range [ 1 , b + c ] by adding any two numbers in range [ a , b ] and [ b , c ] | C ++ program to calculate the number of ways ; Initialising the array with zeros . You can do using memset too . ; Printing the array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CountWays ( int a , int b , int c ) { int x = b + c + 1 ; int arr [ x ] = { 0 } ; for ( int i = a ; i <= b ; i ++ ) { for ( int j = b ; j <= c ; j ++ ) { arr [ i + j ] ++ ; } } for ( int i = 1 ; i < x ; i ++ ) { cout << arr [ i ] << " ▁ " ; } cout << endl ; } int main ( ) { int a = 1 ; int b = 2 ; int c = 2 ; CountWays ( a , b , c ) ; return 0 ; }
Number of ways to obtain each numbers in range [ 1 , b + c ] by adding any two numbers in range [ a , b ] and [ b , c ] | C ++ program to calculate the number of ways ; 2 is added because sometimes we will decrease the value out of bounds . ; Initialising the array with zeros . You can do using memset too . ; Printing the array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CountWays ( int a , int b , int c ) { int x = b + c + 2 ; int arr [ x ] = { 0 } ; for ( int i = 1 ; i <= b ; i ++ ) { arr [ i + b ] ++ ; arr [ i + c + 1 ] -- ; } for ( int i = 1 ; i < x - 1 ; i ++ ) { arr [ i ] += arr [ i - 1 ] ; cout << arr [ i ] << " ▁ " ; } cout << endl ; } int main ( ) { int a = 1 ; int b = 2 ; int c = 2 ; CountWays ( a , b , c ) ; return 0 ; }
Count of distinct possible strings after performing given operations | C ++ implementation of the above approach ; Function that prints the number of different strings that can be formed ; Computing the length of the given string ; Base case ; Traverse the given string ; If two consecutive 1 ' s ▁ ▁ or ▁ 2' s are present ; Otherwise take the previous value ; Driver Code
#include using namespace std ; void differentStrings ( string s ) { int n = s . length ( ) ; vector dp ( n + 1 ) ; dp [ 0 ] = dp [ 1 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] && ( s [ i ] == '1' s [ i ] == '2' ) ) dp [ i + 1 ] = dp [ i ] + dp [ i - 1 ] ; else dp [ i + 1 ] = dp [ i ] ; } cout << dp [ n ] << " STRNEWLINE " ; } int main ( ) { string S = "0111022110" ; differentStrings ( S ) ; return 0 ; }
Sum of cost of all paths to reach a given cell in a Matrix | C ++ implementation to find the sum of cost of all paths to reach ( M , N ) ; Function for computing combination ; Function to find the factorial of N ; Loop to find the factorial of a given number ; Function for coumputing the sum of all path cost ; Loop to find the contribution of each ( i , j ) in the all possible ways ; Count number of times ( i , j ) visited ; Add the contribution of grid [ i ] [ j ] in the result ; Driver Code ; Function Call
#include <iostream> NEW_LINE using namespace std ; const int Col = 3 ; int fact ( int n ) ; int nCr ( int n , int r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } int fact ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } int sumPathCost ( int grid [ ] [ Col ] , int m , int n ) { int sum = 0 , count ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { count = nCr ( i + j , i ) * nCr ( m + n - i - j , m - i ) ; sum += count * grid [ i ] [ j ] ; } } return sum ; } int main ( ) { int m = 2 ; int n = 2 ; int grid [ ] [ Col ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; cout << sumPathCost ( grid , m , n ) ; return 0 ; }
Count numbers in a range with digit sum divisible by K having first and last digit different | C ++ Program to count numbers in a range with digit sum divisible by K having first and last digit different ; For calculating the upper bound of the sequence . ; checking whether the sum of digits = 0 or not and the corner case as number equal to 1 ; If the state is visited then return the answer of this state directly . ; for checking whether digit to be placed is up to upper bound at the position pos or upto 9 ; calculating new digit sum modulo k ; check if there is a prefix of 0 s and current digit != 0 ; Then current digit will be the starting digit ; Update the boolean flag that the starting digit has been found ; At n - 1 , check if current digit and starting digit are the same then no need to calculate this answer . ; Else find the answer ; Function to find the required count ; Setting up the upper bound ; calculating F ( R ) ; Setting up the upper bound ; calculating F ( L - 1 ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll K ; ll N ; vector < int > v ; ll dp [ 20 ] [ 1000 ] [ 10 ] [ 2 ] [ 2 ] ; void init ( ll x ) { memset ( dp , -1 , sizeof ( dp ) ) ; v . clear ( ) ; while ( x > 0 ) { v . push_back ( x % 10 ) ; x /= 10 ; } reverse ( v . begin ( ) , v . end ( ) ) ; N = v . size ( ) ; } ll fun ( ll pos , ll sum , ll st , ll check , ll f ) { if ( pos == N ) { return ( sum == 0 and check == 1 ) ; } if ( dp [ pos ] [ sum ] [ st ] [ check ] [ f ] != -1 ) return dp [ pos ] [ sum ] [ st ] [ check ] [ f ] ; ll lmt = 9 ; if ( ! f ) lmt = v [ pos ] ; ll ans = 0 ; for ( int digit = 0 ; digit <= lmt ; digit ++ ) { ll nf = f ; ll new_sum = ( sum + digit ) % K ; ll new_check = check ; ll new_st = st ; if ( f == 0 and digit < lmt ) nf = 1 ; if ( check == 0 and digit != 0 ) { new_st = digit ; new_check = 1 ; } if ( pos == N - 1 and new_st == digit ) continue ; ans += fun ( pos + 1 , new_sum , new_st , new_check , nf ) ; } return dp [ pos ] [ sum ] [ st ] [ check ] [ f ] = ans ; } void findCount ( int L , int R , int K ) { init ( R ) ; ll r_ans = fun ( 0 , 0 , 0 , 0 , 0 ) ; init ( L - 1 ) ; ll l_ans = fun ( 0 , 0 , 0 , 0 , 0 ) ; cout << r_ans - l_ans ; } int main ( ) { ll L = 10 ; ll R = 20 ; K = 2 ; findCount ( L , R , K ) ; return 0 ; }
Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1 | C ++ Program to split a given string into K segments such that the sum of product of occurence of characters in them is minimized ; Function to return the minimum sum of products of occurences of 0 and 1 in each segments ; Store the length of the string ; Not possible to generate subsets greater than the length of string ; If the number of subsets equals the length ; Precompute the sum of products for all index ; Calculate the minimum sum of products for K subsets ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSumProd ( string S , int K ) { int len = S . length ( ) ; if ( K > len ) return -1 ; if ( K == len ) return 0 ; vector < int > dp ( len ) ; int count_zero = 0 , count_one = 0 ; for ( int j = 0 ; j < len ; j ++ ) { ( S [ j ] == '0' ) ? count_zero ++ : count_one ++ ; dp [ j ] = count_zero * count_one ; } for ( int i = 1 ; i < K ; i ++ ) { for ( int j = len ; j >= i ; j -- ) { count_zero = 0 , count_one = 0 ; dp [ j ] = INT_MAX ; for ( int k = j ; k >= i ; k -- ) { ( S [ k ] == '0' ) ? count_zero ++ : count_one ++ ; dp [ j ] = min ( dp [ j ] , count_zero * count_one + dp [ k - 1 ] ) ; } } } return dp [ len - 1 ] ; } int main ( ) { string S = "1011000110110100" ; int K = 5 ; cout << minSumProd ( S , K ) << ' ' ; return 0 ; }