text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Maximum sum in an array such that every element has exactly one adjacent element to it | C ++ implementation of the approach ; To store the states of dp ; Function to return the maximized sum ; Base case ; Checks if a state is already solved ; Recurrence relation ; Return the result ; Driver code | #include <bits/stdc++.h> NEW_LINE #define arrSize 51 NEW_LINE using namespace std ; int dp [ arrSize ] ; bool v [ arrSize ] ; int sumMax ( int i , int arr [ ] , int n ) { if ( i >= n - 1 ) return 0 ; if ( v [ i ] ) return dp [ i ] ; v [ i ] = true ; dp [ i ] = max ( arr [ i ] + arr [ i + 1 ] + sumMax ( i + 3 , arr , n ) , sumMax ( i + 1 , arr , n ) ) ; return dp [ i ] ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << sumMax ( 0 , arr , n ) ; return 0 ; } |
Maximum Sum Subsequence of length k | C ++ program to calculate the maximum sum of increasing subsequence of length k ; In the implementation dp [ n ] [ k ] represents maximum sum subsequence of length k and the subsequence is ending at index n . ; Initializing whole multidimensional dp array with value - 1 ; For each ith position increasing subsequence of length 1 is equal to that array ith value so initializing dp [ i ] [ 1 ] with that array value ; Starting from 1 st index as we have calculated for 0 th index . Computing optimized dp values in bottom - up manner ; check for increasing subsequence ; Proceed if value is pre calculated ; Check for all the subsequences ending at any j < i and try including element at index i in them for some length l . Update the maximum value for every length . ; The final result would be the maximum value of dp [ i ] [ k ] for all different i . ; When no subsequence of length k is possible sum would be considered zero ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxIncreasingSub ( int arr [ ] , int n , int k ) { int dp [ n ] [ k + 1 ] , ans = -1 ; memset ( dp , -1 , sizeof ( dp ) ) ; for ( int i = 0 ; i < n ; i ++ ) { dp [ i ] [ 1 ] = arr [ i ] ; } for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ j ] < arr [ i ] ) { for ( int l = 1 ; l <= k - 1 ; l ++ ) { if ( dp [ j ] [ l ] != -1 ) { dp [ i ] [ l + 1 ] = max ( dp [ i ] [ l + 1 ] , dp [ j ] [ l ] + arr [ i ] ) ; } } } } } for ( int i = 0 ; i < n ; i ++ ) { if ( ans < dp [ i ] [ k ] ) ans = dp [ i ] [ k ] ; } return ( ans == -1 ) ? 0 : ans ; } int main ( ) { int n = 8 , k = 3 ; int arr [ n ] = { 8 , 5 , 9 , 10 , 5 , 6 , 21 , 8 } ; int ans = MaxIncreasingSub ( arr , n , k ) ; cout << ans << " STRNEWLINE " ; return 0 ; } |
Generate all unique partitions of an integer | Set 2 | C ++ implementation of the approach ; Array to store the numbers used to form the required sum ; Function to print the array which contains the unique partitions which are used to form the required sum ; Function to find all the unique partitions remSum = remaining sum to form maxVal is the maximum number that can be used to make the partition ; If remSum == 0 that means the sum is achieved so print the array ; i will begin from maxVal which is the maximum value which can be used to form the sum ; Store the number used in forming sum gradually in the array ; Since i used the rest of partition cant have any number greater than i hence second parameter is i ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 200 ] ; int count = 0 ; void print ( int idx ) { for ( int i = 1 ; i < idx ; i ++ ) { cout << dp [ i ] << " β " ; } cout << endl ; } void solve ( int remSum , int maxVal , int idx , int & count ) { if ( remSum == 0 ) { print ( idx ) ; count ++ ; return ; } for ( int i = maxVal ; i >= 1 ; i -- ) { if ( i > remSum ) { continue ; } else if ( i <= remSum ) { dp [ idx ] = i ; solve ( remSum - i , i , idx + 1 , count ) ; } } } int main ( ) { int n = 4 , count = 0 ; solve ( n , n , 1 , count ) ; return 0 ; } |
Queries for bitwise OR in the given matrix | C ++ implementation of the approach ; Array to store bit - wise prefix count ; Function to find the prefix sum ; Loop for each bit ; Loop to find prefix - count for each row ; Finding column - wise prefix count ; Function to return the result for a query ; To store the answer ; Loop for each bit ; To store the number of variables with ith bit set ; If count of variables with ith bit set is greater than 0 ; Driver code | #include <bits/stdc++.h> NEW_LINE #define bitscount 32 NEW_LINE #define n 3 NEW_LINE using namespace std ; int prefix_count [ bitscount ] [ n ] [ n ] ; void findPrefixCount ( int arr [ ] [ n ] ) { for ( int i = 0 ; i < bitscount ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { prefix_count [ i ] [ j ] [ 0 ] = ( ( arr [ j ] [ 0 ] >> i ) & 1 ) ; for ( int k = 1 ; k < n ; k ++ ) { prefix_count [ i ] [ j ] [ k ] = ( ( arr [ j ] [ k ] >> i ) & 1 ) ; prefix_count [ i ] [ j ] [ k ] += prefix_count [ i ] [ j ] [ k - 1 ] ; } } } for ( int i = 0 ; i < bitscount ; i ++ ) for ( int j = 1 ; j < n ; j ++ ) for ( int k = 0 ; k < n ; k ++ ) prefix_count [ i ] [ j ] [ k ] += prefix_count [ i ] [ j - 1 ] [ k ] ; } int rangeOr ( int x1 , int y1 , int x2 , int y2 ) { int ans = 0 ; for ( int i = 0 ; i < bitscount ; i ++ ) { int p ; if ( x1 == 0 and y1 == 0 ) p = prefix_count [ i ] [ x2 ] [ y2 ] ; else if ( x1 == 0 ) p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x2 ] [ y1 - 1 ] ; else if ( y1 == 0 ) p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x1 - 1 ] [ y2 ] ; else p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x1 - 1 ] [ y2 ] - prefix_count [ i ] [ x2 ] [ y1 - 1 ] + prefix_count [ i ] [ x1 - 1 ] [ y1 - 1 ] ; if ( p != 0 ) ans = ( ans | ( 1 << i ) ) ; } return ans ; } int main ( ) { int arr [ ] [ n ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; findPrefixCount ( arr ) ; int queries [ ] [ 4 ] = { { 1 , 1 , 1 , 1 } , { 1 , 2 , 2 , 2 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) cout << rangeOr ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , queries [ i ] [ 2 ] , queries [ i ] [ 3 ] ) << endl ; return 0 ; } |
Queries for bitwise AND in the given matrix | C ++ implementation of the approach ; Array to store bit - wise prefix count ; Function to find the prefix sum ; Loop for each bit ; Loop to find prefix - count for each row ; Finding column - wise prefix count ; Function to return the result for a query ; To store the answer ; Loop for each bit ; To store the number of variables with ith bit set ; If count of variables whose ith bit is set equals to the total elements in the sub - matrix ; Driver code | #include <bits/stdc++.h> NEW_LINE #define bitscount 32 NEW_LINE #define n 3 NEW_LINE using namespace std ; int prefix_count [ bitscount ] [ n ] [ n ] ; void findPrefixCount ( int arr [ ] [ n ] ) { for ( int i = 0 ; i < bitscount ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { prefix_count [ i ] [ j ] [ 0 ] = ( ( arr [ j ] [ 0 ] >> i ) & 1 ) ; for ( int k = 1 ; k < n ; k ++ ) { prefix_count [ i ] [ j ] [ k ] = ( ( arr [ j ] [ k ] >> i ) & 1 ) ; prefix_count [ i ] [ j ] [ k ] += prefix_count [ i ] [ j ] [ k - 1 ] ; } } } for ( int i = 0 ; i < bitscount ; i ++ ) for ( int j = 1 ; j < n ; j ++ ) for ( int k = 0 ; k < n ; k ++ ) prefix_count [ i ] [ j ] [ k ] += prefix_count [ i ] [ j - 1 ] [ k ] ; } int rangeAnd ( int x1 , int y1 , int x2 , int y2 ) { int ans = 0 ; for ( int i = 0 ; i < bitscount ; i ++ ) { int p ; if ( x1 == 0 and y1 == 0 ) p = prefix_count [ i ] [ x2 ] [ y2 ] ; else if ( x1 == 0 ) p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x2 ] [ y1 - 1 ] ; else if ( y1 == 0 ) p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x1 - 1 ] [ y2 ] ; else p = prefix_count [ i ] [ x2 ] [ y2 ] - prefix_count [ i ] [ x1 - 1 ] [ y2 ] - prefix_count [ i ] [ x2 ] [ y1 - 1 ] + prefix_count [ i ] [ x1 - 1 ] [ y1 - 1 ] ; if ( p == ( x2 - x1 + 1 ) * ( y2 - y1 + 1 ) ) ans = ( ans | ( 1 << i ) ) ; } return ans ; } int main ( ) { int arr [ ] [ n ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; findPrefixCount ( arr ) ; int queries [ ] [ 4 ] = { { 1 , 1 , 1 , 1 } , { 1 , 2 , 2 , 2 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) cout << rangeAnd ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , queries [ i ] [ 2 ] , queries [ i ] [ 3 ] ) << endl ; return 0 ; } |
Maximum sum such that no two elements are adjacent | Set 2 | C ++ program to implement above approach ; variable to store states of dp ; variable to check if a given state has been solved ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Required recurrence relation ; Returning the value ; Driver code | #include <bits/stdc++.h> NEW_LINE #define maxLen 10 NEW_LINE using namespace std ; int dp [ maxLen ] ; bool v [ maxLen ] ; int maxSum ( int arr [ ] , int i , int n ) { if ( i >= n ) return 0 ; if ( v [ i ] ) return dp [ i ] ; v [ i ] = 1 ; dp [ i ] = max ( maxSum ( arr , i + 1 , n ) , arr [ i ] + maxSum ( arr , i + 2 , n ) ) ; return dp [ i ] ; } int main ( ) { int arr [ ] = { 12 , 9 , 7 , 33 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << maxSum ( arr , 0 , n ) ; return 0 ; } |
Optimal Strategy for a Game | Set 2 | C ++ program to find out maximum value from a given sequence of coins ; For both of your choices , the opponent gives you total sum minus maximum of his value ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Compute sum of elements ; Initialize memoization table ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; int memo [ MAX ] [ MAX ] ; int oSRec ( int arr [ ] , int i , int j , int sum ) { if ( j == i + 1 ) return max ( arr [ i ] , arr [ j ] ) ; if ( memo [ i ] [ j ] != -1 ) return memo [ i ] [ j ] ; memo [ i ] [ j ] = max ( ( sum - oSRec ( arr , i + 1 , j , sum - arr [ i ] ) ) , ( sum - oSRec ( arr , i , j - 1 , sum - arr [ j ] ) ) ) ; return memo [ i ] [ j ] ; } int optimalStrategyOfGame ( int * arr , int n ) { int sum = 0 ; sum = accumulate ( arr , arr + n , sum ) ; memset ( memo , -1 , sizeof ( memo ) ) ; return oSRec ( arr , 0 , n - 1 , sum ) ; } int main ( ) { int arr1 [ ] = { 8 , 15 , 3 , 7 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; printf ( " % d STRNEWLINE " , optimalStrategyOfGame ( arr1 , n ) ) ; int arr2 [ ] = { 2 , 2 , 2 , 2 } ; n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; printf ( " % d STRNEWLINE " , optimalStrategyOfGame ( arr2 , n ) ) ; int arr3 [ ] = { 20 , 30 , 2 , 2 , 2 , 10 } ; n = sizeof ( arr3 ) / sizeof ( arr3 [ 0 ] ) ; printf ( " % d STRNEWLINE " , optimalStrategyOfGame ( arr3 , n ) ) ; return 0 ; } |
Minimum cost to select K strictly increasing elements | C ++ program for the above approach ; Function to calculate min cost to choose k increasing elements ; If k elements are counted return 0 ; If all elements of array has been traversed then return MAX_VALUE ; To check if this is already calculated ; When i 'th elements is not considered ; When the ith element is greater than previous element check if adding its cost makes total cost minimum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1005 ; const int K = 20 ; int n , k ; int dp [ N + 1 ] [ N + 1 ] [ K + 1 ] ; int minCost ( int i , int prev , int cnt , int ele [ ] , int cost [ ] ) { if ( cnt == k + 1 ) { return 0 ; } if ( i == n + 1 ) { return 1e5 ; } int & ans = dp [ i ] [ prev ] [ cnt ] ; if ( ans != -1 ) { return ans ; } ans = minCost ( i + 1 , prev , cnt , ele , cost ) ; if ( ele [ i ] > ele [ prev ] ) { ans = min ( ans , cost [ i ] + minCost ( i + 1 , i , cnt + 1 , ele , cost ) ) ; } return ans ; } int main ( ) { memset ( dp , -1 , sizeof ( dp ) ) ; n = 4 ; k = 2 ; int ele [ n + 1 ] = { 0 , 2 , 6 , 4 , 8 } ; int cost [ n + 1 ] = { 0 , 40 , 20 , 30 , 10 } ; int ans = minCost ( 1 , 0 , 1 , ele , cost ) ; if ( ans == 1e5 ) { ans = -1 ; } cout << ans << endl ; return 0 ; } |
Maximize the subarray sum after multiplying all elements of any subarray with X | C ++ implementation of the approach ; Function to return the maximum sum ; Base case ; If already calculated ; If no elements have been chosen ; Do not choose any element and use Kadane 's algorithm by taking max ; Choose the sub - array and multiply x ; Choose the sub - array and multiply x ; End the sub - array multiplication ; No more multiplication ; Memoize and return the answer ; Function to get the maximum sum ; Initialize dp with - 1 ; Iterate from every position and find the maximum sum which is possible ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 5 NEW_LINE int func ( int idx , int cur , int a [ ] , int dp [ N ] [ 3 ] , int n , int x ) { if ( idx == n ) return 0 ; if ( dp [ idx ] [ cur ] != -1 ) return dp [ idx ] [ cur ] ; int ans = 0 ; if ( cur == 0 ) { ans = max ( ans , a [ idx ] + func ( idx + 1 , 0 , a , dp , n , x ) ) ; ans = max ( ans , x * a [ idx ] + func ( idx + 1 , 1 , a , dp , n , x ) ) ; } else if ( cur == 1 ) { ans = max ( ans , x * a [ idx ] + func ( idx + 1 , 1 , a , dp , n , x ) ) ; ans = max ( ans , a [ idx ] + func ( idx + 1 , 2 , a , dp , n , x ) ) ; } else ans = max ( ans , a [ idx ] + func ( idx + 1 , 2 , a , dp , n , x ) ) ; return dp [ idx ] [ cur ] = ans ; } int getMaximumSum ( int a [ ] , int n , int x ) { int dp [ n ] [ 3 ] ; memset ( dp , -1 , sizeof dp ) ; int maxi = 0 ; for ( int i = 0 ; i < n ; i ++ ) maxi = max ( maxi , func ( i , 0 , a , dp , n , x ) ) ; return maxi ; } int main ( ) { int a [ ] = { -3 , 8 , -2 , 1 , -6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int x = -1 ; cout << getMaximumSum ( a , n , x ) ; return 0 ; } |
Count pairs of non | C ++ implementation of the approach ; Pre - processing function ; Get the size of the string ; Initially mark every position as false ; For the length ; Iterate for every index with length j ; If the length is less than 2 ; If characters are equal ; Check for equal ; Function to return the number of pairs ; Create the dp table initially ; Declare the left array ; Declare the right array ; Initially left [ 0 ] is 1 ; Count the number of palindrome pairs to the left ; Initially right most as 1 ; Count the number of palindrome pairs to the right ; Count the number of pairs ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100 NEW_LINE void pre_process ( bool dp [ N ] [ N ] , string s ) { int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) dp [ i ] [ j ] = false ; } for ( int j = 1 ; j <= n ; j ++ ) { for ( int i = 0 ; i <= n - j ; i ++ ) { if ( j <= 2 ) { if ( s [ i ] == s [ i + j - 1 ] ) dp [ i ] [ i + j - 1 ] = true ; } else if ( s [ i ] == s [ i + j - 1 ] ) dp [ i ] [ i + j - 1 ] = dp [ i + 1 ] [ i + j - 2 ] ; } } } int countPairs ( string s ) { bool dp [ N ] [ N ] ; pre_process ( dp , s ) ; int n = s . length ( ) ; int left [ n ] ; memset ( left , 0 , sizeof left ) ; int right [ n ] ; memset ( right , 0 , sizeof right ) ; left [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { if ( dp [ j ] [ i ] == 1 ) left [ i ] ++ ; } } right [ n - 1 ] = 1 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { right [ i ] = right [ i + 1 ] ; for ( int j = n - 1 ; j >= i ; j -- ) { if ( dp [ i ] [ j ] == 1 ) right [ i ] ++ ; } } int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) ans += left [ i ] * right [ i + 1 ] ; return ans ; } int main ( ) { string s = " abacaba " ; cout << countPairs ( s ) ; return 0 ; } |
Queries to check if substring [ L ... R ] is palindrome or not | C ++ implementation of the approach ; Pre - processing function ; Get the size of the string ; Initially mark every position as false ; For the length ; Iterate for every index with length j ; If the length is less than 2 ; If characters are equal ; Check for equal ; Function to answer every query in O ( 1 ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100 NEW_LINE void pre_process ( bool dp [ N ] [ N ] , string s ) { int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) dp [ i ] [ j ] = false ; } for ( int j = 1 ; j <= n ; j ++ ) { for ( int i = 0 ; i <= n - j ; i ++ ) { if ( j <= 2 ) { if ( s [ i ] == s [ i + j - 1 ] ) dp [ i ] [ i + j - 1 ] = true ; } else if ( s [ i ] == s [ i + j - 1 ] ) dp [ i ] [ i + j - 1 ] = dp [ i + 1 ] [ i + j - 2 ] ; } } } void answerQuery ( int l , int r , bool dp [ N ] [ N ] ) { if ( dp [ l ] [ r ] ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; } int main ( ) { string s = " abaaab " ; bool dp [ N ] [ N ] ; pre_process ( dp , s ) ; int queries [ ] [ 2 ] = { { 0 , 1 } , { 1 , 5 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) answerQuery ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , dp ) ; return 0 ; } |
Length of the longest increasing subsequence such that no two adjacent elements are coprime | CPP program to find the length of the longest increasing sub sequence from the given array such that no two adjacent elements are co prime ; Function to find the length of the longest increasing sub sequence from the given array such that no two adjacent elements are co prime ; To store dp and d value ; To store required answer ; For all elements in the array ; Initially answer is one ; For all it 's divisors ; Update the dp value ; Update the divisor value ; Check for required answer ; Update divisor of a [ i ] ; Return required answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100005 NEW_LINE int LIS ( int a [ ] , int n ) { int dp [ N ] , d [ N ] ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { dp [ a [ i ] ] = 1 ; for ( int j = 2 ; j * j <= a [ i ] ; j ++ ) { if ( a [ i ] % j == 0 ) { dp [ a [ i ] ] = max ( dp [ a [ i ] ] , dp [ d [ j ] ] + 1 ) ; dp [ a [ i ] ] = max ( dp [ a [ i ] ] , dp [ d [ a [ i ] / j ] ] + 1 ) ; d [ j ] = a [ i ] ; d [ a [ i ] / j ] = a [ i ] ; } } ans = max ( ans , dp [ a [ i ] ] ) ; d [ a [ i ] ] = a [ i ] ; } return ans ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << LIS ( a , n ) ; return 0 ; } |
Find the number of binary strings of length N with at least 3 consecutive 1 s | C ++ implementation of the approach ; Function that returns true if s contains three consecutive 1 's ; Function to return the count of required strings ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string & s ) { int n = s . length ( ) ; for ( int i = 2 ; i < n ; i ++ ) { if ( s [ i ] == '1' && s [ i - 1 ] == '1' && s [ i - 2 ] == '1' ) return 1 ; } return 0 ; } int countStr ( int i , string & s ) { if ( i < 0 ) { if ( check ( s ) ) return 1 ; return 0 ; } s [ i ] = '0' ; int ans = countStr ( i - 1 , s ) ; s [ i ] = '1' ; ans += countStr ( i - 1 , s ) ; s [ i ] = '0' ; return ans ; } int main ( ) { int N = 4 ; string s ( N , '0' ) ; cout << countStr ( N - 1 , s ) ; return 0 ; } |
Find the number of binary strings of length N with at least 3 consecutive 1 s | C ++ implementation of the approach ; Function to return the count of required strings ; '0' at ith position ; '1' at ith position ; Driver code ; Base condition : 2 ^ ( i + 1 ) because of 0 indexing | #include <bits/stdc++.h> NEW_LINE using namespace std ; int n ; int solve ( int i , int x , int dp [ ] [ 4 ] ) { if ( i < 0 ) return x == 3 ; if ( dp [ i ] [ x ] != -1 ) return dp [ i ] [ x ] ; dp [ i ] [ x ] = solve ( i - 1 , 0 , dp ) ; dp [ i ] [ x ] += solve ( i - 1 , x + 1 , dp ) ; return dp [ i ] [ x ] ; } int main ( ) { n = 4 ; int dp [ n ] [ 4 ] ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < 4 ; j ++ ) dp [ i ] [ j ] = -1 ; for ( int i = 0 ; i < n ; i ++ ) { dp [ i ] [ 3 ] = ( 1 << ( i + 1 ) ) ; } cout << solve ( n - 1 , 0 , dp ) ; return 0 ; } |
Find the sum of the diagonal elements of the given N X N spiral matrix | C ++ implementation of the approach ; Function to return the sum of both the diagonal elements of the required matrix ; Array to store sum of diagonal elements ; Base cases ; Computing the value of dp ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int n ) { int dp [ n + 1 ] ; dp [ 1 ] = 1 ; dp [ 0 ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ i ] = ( 4 * ( i * i ) ) - 6 * ( i - 1 ) + dp [ i - 2 ] ; } return dp [ n ] ; } int main ( ) { int n = 4 ; cout << findSum ( n ) ; return 0 ; } |
Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming | C ++ program to find maximum sum of a subset of nodes that are not adjacent ; Function to find the diameter of the tree using Dynamic Programming ; Traverse for all children of node ; Call DFS function again ; Include the current node then donot include the children ; Donot include current node , then include children or not include them ; Recurrence value ; Driver program to test above functions ; Constructed tree is 1 / \ 2 3 / \ 4 5 ; create undirected edges ; Numbers to node ; Find maximum sum by calling function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( int node , int parent , int dp1 [ ] , int dp2 [ ] , list < int > * adj , int tree [ ] ) { int sum1 = 0 , sum2 = 0 ; for ( auto i = adj [ node ] . begin ( ) ; i != adj [ node ] . end ( ) ; ++ i ) { if ( * i == parent ) continue ; dfs ( * i , node , dp1 , dp2 , adj , tree ) ; sum1 += dp2 [ * i ] ; sum2 += max ( dp1 [ * i ] , dp2 [ * i ] ) ; } dp1 [ node ] = tree [ node ] + sum1 ; dp2 [ node ] = sum2 ; } int main ( ) { int n = 5 ; list < int > * adj = new list < int > [ n + 1 ] ; adj [ 1 ] . push_back ( 2 ) ; adj [ 2 ] . push_back ( 1 ) ; adj [ 1 ] . push_back ( 3 ) ; adj [ 3 ] . push_back ( 1 ) ; adj [ 2 ] . push_back ( 4 ) ; adj [ 4 ] . push_back ( 2 ) ; adj [ 2 ] . push_back ( 5 ) ; adj [ 5 ] . push_back ( 2 ) ; int tree [ n + 1 ] ; tree [ 1 ] = 10 ; tree [ 2 ] = 5 ; tree [ 3 ] = 11 ; tree [ 4 ] = 6 ; tree [ 5 ] = 8 ; int dp1 [ n + 1 ] , dp2 [ n + 1 ] ; memset ( dp1 , 0 , sizeof dp1 ) ; memset ( dp2 , 0 , sizeof dp2 ) ; dfs ( 1 , 1 , dp1 , dp2 , adj , tree ) ; cout << " Maximum β sum : β " << max ( dp1 [ 1 ] , dp2 [ 1 ] ) << endl ; return 0 ; } |
Count number of ways to reach a given score in a Matrix | C ++ implementation of the approach ; To store the states of dp ; To check whether a particular state of dp has been solved ; Function to find the ways using memoization ; Base cases ; If required score becomes negative ; If current state has been reached before ; Set current state to visited ; Driver code | #include <iostream> NEW_LINE using namespace std ; #define n 3 NEW_LINE #define MAX 30 NEW_LINE int dp [ n ] [ n ] [ MAX ] ; bool v [ n ] [ n ] [ MAX ] ; int findCount ( int mat [ ] [ n ] , int i , int j , int m ) { if ( i == 0 && j == 0 ) { if ( m == mat [ 0 ] [ 0 ] ) return 1 ; else return 0 ; } if ( m < 0 ) return 0 ; if ( i < 0 j < 0 ) return 0 ; if ( v [ i ] [ j ] [ m ] ) return dp [ i ] [ j ] [ m ] ; v [ i ] [ j ] [ m ] = true ; dp [ i ] [ j ] [ m ] = findCount ( mat , i - 1 , j , m - mat [ i ] [ j ] ) + findCount ( mat , i , j - 1 , m - mat [ i ] [ j ] ) ; return dp [ i ] [ j ] [ m ] ; } int main ( ) { int mat [ n ] [ n ] = { { 1 , 1 , 1 } , { 1 , 1 , 1 } , { 1 , 1 , 1 } } ; int m = 5 ; cout << findCount ( mat , n - 1 , n - 1 , m ) ; return 0 ; } |
Number of ways of scoring R runs in B balls with at most W wickets | C ++ implementation of the approach ; Function to return the number of ways to score R runs in B balls with at most W wickets ; If the wickets lost are more ; If runs scored are more ; If condition is met ; If no run got scored ; Already visited state ; If scored 0 run ; If scored 1 run ; If scored 2 runs ; If scored 3 runs ; If scored 4 runs ; If scored 6 runs ; If scored no run and lost a wicket ; Memoize and return ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod 1000000007 NEW_LINE #define RUNMAX 300 NEW_LINE #define BALLMAX 50 NEW_LINE #define WICKETMAX 10 NEW_LINE int CountWays ( int r , int b , int l , int R , int B , int W , int dp [ RUNMAX ] [ BALLMAX ] [ WICKETMAX ] ) { if ( l > W ) return 0 ; if ( r > R ) return 0 ; if ( b == B && r == R ) return 1 ; if ( b == B ) return 0 ; if ( dp [ r ] [ b ] [ l ] != -1 ) return dp [ r ] [ b ] [ l ] ; int ans = 0 ; ans += CountWays ( r , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r + 1 , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r + 2 , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r + 3 , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r + 4 , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r + 6 , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r , b + 1 , l + 1 , R , B , W , dp ) ; ans = ans % mod ; return dp [ r ] [ b ] [ l ] = ans ; } int main ( ) { int R = 40 , B = 10 , W = 4 ; int dp [ RUNMAX ] [ BALLMAX ] [ WICKETMAX ] ; memset ( dp , -1 , sizeof dp ) ; cout << CountWays ( 0 , 0 , 0 , R , B , W , dp ) ; return 0 ; } |
Minimum steps to delete a string by deleting substring comprising of same characters | C ++ implementation of the approach ; Function to return the minimum number of delete operations ; When a single character is deleted ; When a group of consecutive characters are deleted if any of them matches ; When both the characters are same then delete the letters in between them ; Memoize ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 10 ; int findMinimumDeletion ( int l , int r , int dp [ N ] [ N ] , string s ) { if ( l > r ) return 0 ; if ( l == r ) return 1 ; if ( dp [ l ] [ r ] != -1 ) return dp [ l ] [ r ] ; int res = 1 + findMinimumDeletion ( l + 1 , r , dp , s ) ; for ( int i = l + 1 ; i <= r ; ++ i ) { if ( s [ l ] == s [ i ] ) res = min ( res , findMinimumDeletion ( l + 1 , i - 1 , dp , s ) + findMinimumDeletion ( i , r , dp , s ) ) ; } return dp [ l ] [ r ] = res ; } int main ( ) { string s = " abcddcba " ; int n = s . length ( ) ; int dp [ N ] [ N ] ; memset ( dp , -1 , sizeof dp ) ; cout << findMinimumDeletion ( 0 , n - 1 , dp , s ) ; return 0 ; } |
Minimal product subsequence where adjacent elements are separated by a maximum distance of K | C ++ implementation of the above approach . ; Function to get the minimum product of subsequence such that adjacent elements are separated by a max distance of K ; multiset will hold pairs pair = ( log value of product , dp [ j ] value ) dp [ j ] = minimum product % mod multiset will be sorted according to log values Therefore , corresponding to the minimum log value dp [ j ] value can be obtained . ; For the first k - sized window . ; Update log value by adding previous minimum log value ; Update dp [ i ] ; Insert it again into the multiset since it is within the k - size window ; Eliminate previous value which falls out of the k - sized window ; Insert newest value to enter in the k - sized window . ; dp [ n - 1 ] will have minimum product % mod such that adjacent elements are separated by a max distance K ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define mp make_pair NEW_LINE #define ll long long NEW_LINE using namespace std ; const int mod = 1000000007 ; const int MAX = 100005 ; int minimumProductSubsequence ( int * arr , int n , int k ) { multiset < pair < double , int > > s ; ll dp [ MAX ] ; double p [ MAX ] ; dp [ 0 ] = arr [ 0 ] ; p [ 0 ] = log ( arr [ 0 ] ) ; s . insert ( mp ( p [ 0 ] , dp [ 0 ] ) ) ; for ( int i = 1 ; i < k ; i ++ ) { double l = ( s . begin ( ) ) -> first ; ll min = ( s . begin ( ) ) -> second ; p [ i ] = log ( arr [ i ] ) + l ; dp [ i ] = ( arr [ i ] * min ) % mod ; s . insert ( mp ( p [ i ] , dp [ i ] ) ) ; } for ( int i = k ; i < n ; i ++ ) { double l = ( s . begin ( ) ) -> first ; ll min = ( s . begin ( ) ) -> second ; p [ i ] = log ( arr [ i ] ) + l ; dp [ i ] = ( arr [ i ] * min ) % mod ; multiset < pair < double , int > > :: iterator it ; it = s . find ( mp ( p [ i - k ] , dp [ i - k ] ) ) ; s . erase ( it ) ; s . insert ( mp ( p [ i ] , dp [ i ] ) ) ; } return dp [ n - 1 ] ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << minimumProductSubsequence ( arr , n , k ) ; return 0 ; } |
Ways to form a group from three groups with given constraints | C ++ program to find the number of ways to form the group of peopls ; Function to pre - compute the Combination using DP ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; return C [ n ] [ k ] ; ; Function to find the number of ways ; Function to pre - compute ; Sum the Zci ; Iterate for second position ; Iterate for first position ; Multiply the common Combination value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int C [ 1000 ] [ 1000 ] ; void binomialCoeff ( int n ) { int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= i ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } } int numberOfWays ( int x , int y , int z ) { binomialCoeff ( max ( x , max ( y , z ) ) ) ; int sum = 0 ; for ( int i = 1 ; i <= z ; i ++ ) { sum = ( sum + C [ z ] [ i ] ) ; } int sum1 = 0 ; for ( int i = 1 ; i <= y ; i ++ ) { for ( int j = i + 1 ; j <= x ; j ++ ) { sum1 = ( sum1 + ( C [ y ] [ i ] * C [ x ] [ j ] ) ) ; } } sum1 = ( sum * sum1 ) ; return sum1 ; } int main ( ) { int x = 3 ; int y = 2 ; int z = 1 ; cout << numberOfWays ( x , y , z ) ; return 0 ; } |
Minimum cost to make a string free of a subsequence | C ++ implementation of the approach ; Function to return the minimum cost ; Traverse the string ; Min Cost to remove ' c ' ; Min Cost to remove subsequence " co " ; Min Cost to remove subsequence " cod " ; Min Cost to remove subsequence " code " ; Return the minimum cost ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findCost ( string str , int arr [ ] , int n ) { long long costofC = 0 , costofO = 0 , costofD = 0 , costofE = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' c ' ) costofC += arr [ i ] ; else if ( str [ i ] == ' o ' ) costofO = min ( costofC , costofO + arr [ i ] ) ; else if ( str [ i ] == ' d ' ) costofD = min ( costofO , costofD + arr [ i ] ) ; else if ( str [ i ] == ' e ' ) costofE = min ( costofD , costofE + arr [ i ] ) ; } return costofE ; } int main ( ) { string str = " geekcodergeeks " ; int arr [ ] = { 1 , 2 , 1 , 3 , 4 , 2 , 6 , 4 , 6 , 2 , 3 , 3 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findCost ( str , arr , n ) ; return 0 ; } |
Longest subsequence such that adjacent elements have at least one common digit | C ++ program to find maximum length subsequence such that adjacent elements have at least one common digit ; Returns length of maximum length subsequence ; To store the length of the maximum length subsequence ; To store current element arr [ i ] ; To store the length of the sub - sequence ending at index i and having common digit d ; To store digits present in current element ; To store length of maximum length subsequence ending at index i ; For first element maximum length is 1 for each digit ; Find digits of each element , then find length of subsequence for each digit and then find local maximum ; Find digits in current element ; For each digit present find length of subsequence and find local maximum ; Update value of dp [ i ] [ d ] for each digit present in current element to local maximum found . ; Update maximum length with local maximum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSubsequence ( int arr [ ] , int n ) { int len = 1 ; int tmp ; int i , j , d ; int dp [ n ] [ 10 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; int cnt [ 10 ] ; int locMax ; tmp = arr [ 0 ] ; while ( tmp > 0 ) { dp [ 0 ] [ tmp % 10 ] = 1 ; tmp /= 10 ; } for ( i = 1 ; i < n ; i ++ ) { tmp = arr [ i ] ; locMax = 1 ; memset ( cnt , 0 , sizeof ( cnt ) ) ; while ( tmp > 0 ) { cnt [ tmp % 10 ] = 1 ; tmp /= 10 ; } for ( d = 0 ; d <= 9 ; d ++ ) { if ( cnt [ d ] ) { dp [ i ] [ d ] = 1 ; for ( j = 0 ; j < i ; j ++ ) { dp [ i ] [ d ] = max ( dp [ i ] [ d ] , dp [ j ] [ d ] + 1 ) ; locMax = max ( dp [ i ] [ d ] , locMax ) ; } } } for ( d = 0 ; d <= 9 ; d ++ ) { if ( cnt [ d ] ) { dp [ i ] [ d ] = locMax ; } } len = max ( len , locMax ) ; } return len ; } int main ( ) { int arr [ ] = { 1 , 12 , 44 , 29 , 33 , 96 , 89 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSubsequence ( arr , n ) ; return 0 ; } |
Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime | C ++ implementation of the above approach ; Prime numbers upto 100 ; Function to return the count of required numbers from 0 to num ; Base Case ; check if the difference is equal to any prime number ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current position is odd add it to currOdd , otherwise to currEven ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 18 ; int a , b , dp [ M ] [ 90 ] [ 90 ] [ 2 ] ; int prime [ ] = { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 } ; int count ( int pos , int even , int odd , int tight , vector < int > num ) { if ( pos == num . size ( ) ) { if ( num . size ( ) & 1 ) swap ( odd , even ) ; int d = even - odd ; for ( int i = 0 ; i < 24 ; i ++ ) if ( d == prime [ i ] ) return 1 ; return 0 ; } if ( dp [ pos ] [ even ] [ odd ] [ tight ] != -1 ) return dp [ pos ] [ even ] [ odd ] [ tight ] ; int ans = 0 ; int limit = ( tight ? 9 : num [ pos ] ) ; for ( int d = 0 ; d <= limit ; d ++ ) { int currF = tight , currEven = even ; int currOdd = odd ; if ( d < num [ pos ] ) currF = 1 ; if ( pos & 1 ) currOdd += d ; else currEven += d ; ans += count ( pos + 1 , currEven , currOdd , currF , num ) ; } return dp [ pos ] [ even ] [ odd ] [ tight ] = ans ; } int solve ( int x ) { vector < int > num ; while ( x ) { num . push_back ( x % 10 ) ; x /= 10 ; } reverse ( num . begin ( ) , num . end ( ) ) ; memset ( dp , -1 , sizeof ( dp ) ) ; return count ( 0 , 0 , 0 , 0 , num ) ; } int main ( ) { int L = 1 , R = 50 ; cout << solve ( R ) - solve ( L - 1 ) << endl ; L = 50 , R = 100 ; cout << solve ( R ) - solve ( L - 1 ) << endl ; return 0 ; } |
Find the number of distinct pairs of vertices which have a distance of exactly k in a tree | C ++ implementation of the approach ; To store vertices and value of k ; To store number vertices at a level i ; To store the final answer ; Function to add an edge between two nodes ; Function to find the number of distinct pairs of the vertices which have a distance of exactly k in a tree ; At level zero vertex itself is counted ; Count the pair of vertices at distance k ; For all levels count vertices ; Driver code ; Add edges ; Function call ; Required answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 5005 NEW_LINE int n , k ; vector < int > gr [ N ] ; int d [ N ] [ 505 ] ; int ans = 0 ; void Add_edge ( int x , int y ) { gr [ x ] . push_back ( y ) ; gr [ y ] . push_back ( x ) ; } void dfs ( int v , int par ) { d [ v ] [ 0 ] = 1 ; for ( auto i : gr [ v ] ) { if ( i != par ) { dfs ( i , v ) ; for ( int j = 1 ; j <= k ; j ++ ) ans += d [ i ] [ j - 1 ] * d [ v ] [ k - j ] ; for ( int j = 1 ; j <= k ; j ++ ) d [ v ] [ j ] += d [ i ] [ j - 1 ] ; } } } int main ( ) { n = 5 , k = 2 ; Add_edge ( 1 , 2 ) ; Add_edge ( 2 , 3 ) ; Add_edge ( 3 , 4 ) ; Add_edge ( 2 , 5 ) ; dfs ( 1 , 0 ) ; cout << ans ; return 0 ; } |
Sum of XOR of all subarrays | C ++ program to find the sum of XOR of all subarray of the array ; Function to calculate the sum of XOR of all subarrays ; variable to store the final sum ; multiplier ; variable to store number of sub - arrays with odd number of elements with ith bits starting from the first element to the end of the array ; variable to check the status of the odd - even count while calculating c_odd ; loop to calculate initial value of c_odd ; loop to iterate through all the elements of the array and update sum ; updating the multiplier ; returning the sum ; Driver Code | #include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; int findXorSum ( int arr [ ] , int n ) { int sum = 0 ; int mul = 1 ; for ( int i = 0 ; i < 30 ; i ++ ) { int c_odd = 0 ; bool odd = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) odd = ( ! odd ) ; if ( odd ) c_odd ++ ; } for ( int j = 0 ; j < n ; j ++ ) { sum += ( mul * c_odd ) ; if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) c_odd = ( n - j - c_odd ) ; } mul *= 2 ; } return sum ; } int main ( ) { int arr [ ] = { 3 , 8 , 13 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findXorSum ( arr , n ) ; return 0 ; } |
Minimum replacements to make adjacent characters unequal in a ternary string | Set | C ++ program to count the minimal replacements such that adjacent characters are unequal ; function to return integer value of i - th character in the string ; Function to count the number of minimal replacements ; If the string has reached the end ; If the state has been visited previously ; Get the current value of character ; If it is equal then change it ; All possible changes ; Change done ; else If same no change ; Driver Code ; Length of string ; Create a DP array ; First character ; Function to find minimal replacements | #include <bits/stdc++.h> NEW_LINE using namespace std ; int charVal ( string s , int i ) { if ( s [ i ] == '0' ) return 0 ; else if ( s [ i ] == '1' ) return 1 ; else return 2 ; } int countMinimalReplacements ( string s , int i , int prev , int dp [ ] [ 3 ] , int n ) { if ( i == n ) { return 0 ; } if ( dp [ i ] [ prev ] != -1 ) return dp [ i ] [ prev ] ; int val = charVal ( s , i ) ; int ans = INT_MAX ; if ( val == prev ) { int val = 0 ; for ( int cur = 0 ; cur <= 2 ; cur ++ ) { if ( cur == prev ) continue ; val = 1 + countMinimalReplacements ( s , i + 1 , cur , dp , n ) ; ans = min ( ans , val ) ; } } ans = countMinimalReplacements ( s , i + 1 , val , dp , n ) ; return dp [ i ] [ val ] = ans ; } int main ( ) { string s = "201220211" ; int n = s . length ( ) ; int dp [ n ] [ 3 ] ; memset ( dp , -1 , sizeof dp ) ; int val = charVal ( s , 0 ) ; cout << countMinimalReplacements ( s , 1 , val , dp , n ) ; return 0 ; } |
A variation of Rat in a Maze : multiple steps or jumps allowed | C ++ implementation of the approach ; Function to check whether the path exists ; Declaring and initializing CRF ( can reach from ) matrix ; Using the DP to fill CRF matrix in correct order ; If it is possible to get to a valid location from cell maze [ k ] [ j ] ; If it is possible to get to a valid location from cell maze [ j ] [ k ] ; If CRF [ 0 ] [ 0 ] is false it means we cannot reach the end of the maze at all ; Filling the solution matrix using CRF ; Get to a valid location from the current cell ; Utility function to print the contents of a 2 - D array ; Driver code ; If path exists ; Print the path | #include <iostream> NEW_LINE using namespace std ; #define MAX 50 NEW_LINE bool hasPath ( int maze [ ] [ MAX ] , int sol [ ] [ MAX ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) sol [ i ] [ j ] = 0 ; bool * * CRF = new bool * [ N ] ; for ( int i = 0 ; i < N ; i ++ ) CRF [ i ] = new bool [ N ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) CRF [ i ] [ j ] = false ; CRF [ N - 1 ] [ N - 1 ] = true ; for ( int k = N - 1 ; k >= 0 ; k -- ) { for ( int j = k ; j >= 0 ; j -- ) { if ( ! ( k == N - 1 && j == N - 1 ) ) { for ( int a = 0 ; a <= maze [ k ] [ j ] ; a ++ ) { if ( ( j + a < N && CRF [ k ] [ j + a ] == true ) || ( k + a < N && CRF [ k + a ] [ j ] == true ) ) { CRF [ k ] [ j ] = true ; break ; } } for ( int a = 0 ; a <= maze [ j ] [ k ] ; a ++ ) { if ( ( k + a < N && CRF [ j ] [ k + a ] == true ) || ( j + a < N && CRF [ j + a ] [ k ] == true ) ) { CRF [ j ] [ k ] = true ; break ; } } } } } if ( CRF [ 0 ] [ 0 ] == false ) return false ; int i = 0 , j = 0 ; while ( ! ( i == N - 1 && j == N - 1 ) ) { sol [ i ] [ j ] = 1 ; if ( maze [ i ] [ j ] > 0 ) for ( int a = 1 ; a <= maze [ i ] [ j ] ; a ++ ) { if ( ( j + a < N && CRF [ i ] [ j + a ] == true ) ) { j = j + a ; break ; } else if ( ( i + a < N && CRF [ i + a ] [ j ] == true ) ) { i = i + a ; break ; } } } sol [ N - 1 ] [ N - 1 ] = 1 ; return true ; } void printMatrix ( int sol [ ] [ MAX ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) cout << sol [ i ] [ j ] << " β " ; cout << " STRNEWLINE " ; } } int main ( ) { int maze [ ] [ MAX ] = { { 2 , 2 , 1 , 1 , 0 } , { 0 , 0 , 3 , 0 , 0 } , { 1 , 0 , 0 , 0 , 0 } , { 0 , 0 , 2 , 0 , 1 } , { 0 , 0 , 3 , 0 , 0 } } ; int N = sizeof ( maze ) / sizeof ( maze [ 0 ] ) ; int sol [ N ] [ MAX ] ; if ( hasPath ( maze , sol , N ) ) printMatrix ( sol , N ) ; else cout << " No β path β exists " ; return 0 ; } |
Check if it is possible to get back to 12 '0 clock only by adding or subtracting given seconds | C ++ program to check if we come back to zero or not in a clock ; Function to check all combinations ; Generate all power sets ; Check for every combination ; Store sum for all combinations ; Check if jth bit in the counter is set If set then print jth element from set ; sum += a [ j ] ; if set then consider as ' + ' ; sum -= a [ j ] ; else consider as ' - ' ; If we can get back to 0 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkCombinations ( int a [ ] , int n ) { int pow_set_size = pow ( 2 , n ) ; int counter , j ; for ( counter = 0 ; counter < pow_set_size ; counter ++ ) { int sum = 0 ; for ( j = 0 ; j < n ; j ++ ) { if ( counter & ( 1 << j ) ) else } if ( sum % ( 24 * 60 ) == 0 ) return true ; } return false ; } int main ( ) { int a [ ] = { 60 , 60 , 120 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( checkCombinations ( a , n ) ) cout << " YES " ; else cout << " NO " ; return 0 ; } |
Find probability of selecting element from kth column after N iterations | C ++ implementation of the above approach ; Function to calculate probability ; declare dp [ ] [ ] and sum [ ] ; precalculate the first row ; calculate the probability for each element and update dp table ; return result ; Driver code | #include <bits/stdc++.h> NEW_LINE #define n 4 NEW_LINE #define m 4 NEW_LINE using namespace std ; float calcProbability ( int M [ ] [ m ] , int k ) { float dp [ m ] [ n ] , sum [ n ] ; for ( int j = 0 ; j < n ; j ++ ) { dp [ 0 ] [ j ] = M [ 0 ] [ j ] ; sum [ 0 ] += dp [ 0 ] [ j ] ; } for ( int i = 1 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j ] / sum [ i - 1 ] + M [ i ] [ j ] ; sum [ i ] += dp [ i ] [ j ] ; } } return dp [ n - 1 ] [ k - 1 ] / sum [ n - 1 ] ; } int main ( ) { int M [ m ] [ n ] = { { 1 , 1 , 0 , 3 } , { 2 , 3 , 2 , 3 } , { 9 , 3 , 0 , 2 } , { 2 , 3 , 2 , 2 } } ; int k = 3 ; cout << calcProbability ( M , k ) ; return 0 ; } |
Possible cuts of a number such that maximum parts are divisible by 3 | CPP program to find the maximum number of numbers divisible by 3 in a large number ; Function to find the maximum number of numbers divisible by 3 in a large number ; store size of the string ; Stores last index of a remainder ; last visited place of remainder zero is at 0. ; To store result from 0 to i ; get the remainder ; Get maximum res [ i ] value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaximumNumbers ( string s ) { int n = s . length ( ) ; vector < int > remIndex ( 3 , -1 ) ; remIndex [ 0 ] = 0 ; vector < int > res ( n + 1 ) ; int r = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { r = ( r + s [ i - 1 ] - '0' ) % 3 ; res [ i ] = res [ i - 1 ] ; if ( remIndex [ r ] != -1 ) res [ i ] = max ( res [ i ] , res [ remIndex [ r ] ] + 1 ) ; remIndex [ r ] = i + 1 ; } return res [ n ] ; } int main ( ) { string s = "12345" ; cout << MaximumNumbers ( s ) ; return 0 ; } |
Minimum steps required to convert X to Y where a binary matrix represents the possible conversions | C ++ implementation of the above approach ; dist [ ] [ ] will be the output matrix that will finally have the shortest distances between every pair of numbers ; Initially same as mat ; Add all numbers one by one to the set of intermediate numbers . Before start of an iteration , we have shortest distances between all pairs of numbers such that the shortest distances consider only the numbers in set { 0 , 1 , 2 , . . k - 1 } as intermediate numbers . After the end of an iteration , vertex no . k is added to the set of intermediate numbers and the set becomes { 0 , 1 , 2 , . . k } ; Pick all numbers as source one by one ; Pick all numbers as destination for the above picked source ; If number k is on the shortest path from i to j , then update the value of dist [ i ] [ j ] ; If no path ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define INF 99999 NEW_LINE #define size 10 NEW_LINE int findMinimumSteps ( int mat [ size ] [ size ] , int x , int y , int n ) { int dist [ n ] [ n ] , i , j , k ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { if ( mat [ i ] [ j ] == 0 ) dist [ i ] [ j ] = INF ; else dist [ i ] [ j ] = 1 ; if ( i == j ) dist [ i ] [ j ] = 1 ; } } for ( k = 0 ; k < n ; k ++ ) { for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { if ( dist [ i ] [ k ] + dist [ k ] [ j ] < dist [ i ] [ j ] ) dist [ i ] [ j ] = dist [ i ] [ k ] + dist [ k ] [ j ] ; } } } if ( dist [ x ] [ y ] < INF ) return dist [ x ] [ y ] ; else return -1 ; } int main ( ) { int mat [ size ] [ size ] = { { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 } , { 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 } } ; int x = 2 , y = 3 ; cout << findMinimumSteps ( mat , x , y , size ) ; } |
Count number of paths whose weight is exactly X and has at | C ++ program to count the number of paths ; Function to find the number of paths ; If the summation is more than X ; If exactly X weights have reached ; Already visited ; Count paths ; Traverse in all paths ; If the edge weight is M ; else Edge 's weight is not M ; Driver Code ; Initialized the DP array with - 1 ; Function to count paths | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define max 4 NEW_LINE #define c 2 NEW_LINE int countPaths ( int sum , int get , int m , int n , int dp [ ] ) { if ( sum < 0 ) return 0 ; if ( sum == 0 ) return get ; if ( dp [ sum ] [ get ] != -1 ) return dp [ sum ] [ get ] ; int res = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i == m ) res += countPaths ( sum - i , 1 , m , n , dp ) ; res += countPaths ( sum - i , get , m , n , dp ) ; } dp [ sum ] [ get ] = res ; return dp [ sum ] [ get ] ; } int main ( ) { int n = 3 , m = 2 , x = 3 ; int dp [ max + 1 ] ; for ( int i = 0 ; i <= max ; i ++ ) for ( int j = 0 ; j < 2 ; j ++ ) dp [ i ] [ j ] = -1 ; cout << countPaths ( x , 0 , m , n , dp ) ; } |
Minimum Operations to make value of all vertices of the tree Zero | CPP program to find the Minimum Operations to modify values of all tree vertices to zero ; A utility function to add an edge in an undirected graph ; A utility function to print the adjacency list representation of graph ; Utility Function for findMinOperation ( ) ; Base Case for current node ; iterate over the adjacency list for src ; calculate DP table for each child V ; Number of Increase Type operations for node src is equal to maximum of number of increase operations required by each of its child ; Number of Decrease Type operations for node src is equal to maximum of number of decrease operations required by each of its child ; After performing operations for subtree rooted at src A [ src ] changes by the net difference of increase and decrease type operations ; for negative value of node src ; Returns the minimum operations required to make value of all vertices equal to zero , uses findMinOperationUtil ( ) ; Initialise DP table ; find dp [ 1 ] [ 0 ] and dp [ 1 ] [ 1 ] ; Driver code ; Build the Graph / Tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; void addEdge ( vector < int > adj [ ] , int u , int v ) { adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } void printGraph ( vector < int > adj [ ] , int V ) { for ( int v = 0 ; v < V ; ++ v ) { cout << " Adjacency list of vertex " << v < < " head " for ( auto x : adj [ v ] ) cout << " - > β " << x ; printf ( " STRNEWLINE " ) ; } } void findMinOperationUtil ( int dp [ ] [ 2 ] , vector < int > adj [ ] , int A [ ] , int src , int parent ) { dp [ src ] [ 0 ] = dp [ src ] [ 1 ] = 0 ; for ( auto V : adj [ src ] ) { if ( V == parent ) continue ; findMinOperationUtil ( dp , adj , A , V , src ) ; dp [ src ] [ 0 ] = max ( dp [ src ] [ 0 ] , dp [ V ] [ 0 ] ) ; dp [ src ] [ 1 ] = max ( dp [ src ] [ 1 ] , dp [ V ] [ 1 ] ) ; } A [ src - 1 ] += dp [ src ] [ 0 ] - dp [ src ] [ 1 ] ; if ( A [ src - 1 ] > 0 ) { dp [ src ] [ 1 ] += A [ src - 1 ] ; } else { dp [ src ] [ 0 ] += abs ( A [ src - 1 ] ) ; } } int findMinOperation ( vector < int > adj [ ] , int A [ ] , int V ) { int dp [ V + 1 ] [ 2 ] ; memset ( dp , 0 , sizeof dp ) ; findMinOperationUtil ( dp , adj , A , 1 , 0 ) ; int minOperations = dp [ 1 ] [ 0 ] + dp [ 1 ] [ 1 ] ; return minOperations ; } int main ( ) { int V = 5 ; vector < int > adj [ V + 1 ] ; addEdge ( adj , 1 , 2 ) ; addEdge ( adj , 1 , 3 ) ; int A [ ] = { 1 , -1 , 1 } ; int minOperations = findMinOperation ( adj , A , V ) ; cout << minOperations ; return 0 ; } |
Sum of kth powers of first n natural numbers | C ++ program to find sum pf k - th powers of first n natural numbers . ; A global array to store factorials ; Function to calculate the factorials of all the numbers upto k ; Function to return the binomial coefficient ; nCr = ( n ! * ( n - r ) ! ) / r ! ; Function to return the sum of kth powers of n natural numbers ; When j is unity ; Calculating sum ( n ^ 1 ) of unity powers of n ; storing sum ( n ^ 1 ) for sum ( n ^ 2 ) ; If k = 1 then temp is the result ; For finding sum ( n ^ k ) removing 1 and n * kCk from ( n + 1 ) ^ k ; Removing all kC2 * sum ( n ^ ( k - 2 ) ) + ... + kCk - 1 * ( sum ( n ^ ( k - ( k - 1 ) ) ; Storing the result for next sum of next powers of k ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_K = 15 ; long long unsigned int fac [ MAX_K ] ; void factorial ( int k ) { fac [ 0 ] = 1 ; for ( int i = 1 ; i <= k + 1 ; i ++ ) { fac [ i ] = ( i * fac [ i - 1 ] ) ; } } long long unsigned int bin ( int a , int b ) { long long unsigned int ans = ( ( fac [ a ] ) / ( fac [ a - b ] * fac [ b ] ) ) ; return ans ; } long int sumofn ( int n , int k ) { int p = 0 ; long long unsigned int num1 , temp , arr [ 1000 ] ; for ( int j = 1 ; j <= k ; j ++ ) { if ( j == 1 ) { num1 = ( n * ( n + 1 ) ) / 2 ; arr [ p ++ ] = num1 ; temp = num1 ; } else { temp = ( pow ( n + 1 , j + 1 ) - 1 - n ) ; for ( int s = 1 ; s < j ; s ++ ) { temp = temp - ( arr [ j - s - 1 ] * bin ( j + 1 , s + 1 ) ) ; } temp = temp / ( j + 1 ) ; arr [ p ++ ] = temp ; } } temp = arr [ p - 1 ] ; return temp ; } int main ( ) { int n = 5 , k = 2 ; factorial ( k ) ; cout << sumofn ( n , k ) << " STRNEWLINE " ; return 0 ; } |
Ways to fill N positions using M colors such that there are exactly K pairs of adjacent different colors | C ++ implementation of the approach ; Recursive function to find the required number of ways ; When all positions are filled ; If adjacent pairs are exactly K ; If already calculated ; Next position filled with same color ; Next position filled with different color So there can be m - 1 different colors ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define max 4 NEW_LINE int countWays ( int index , int cnt , int dp [ ] [ max ] , int n , int m , int k ) { if ( index == n ) { if ( cnt == k ) return 1 ; else return 0 ; } if ( dp [ index ] [ cnt ] != -1 ) return dp [ index ] [ cnt ] ; int ans = 0 ; ans += countWays ( index + 1 , cnt , dp , n , m , k ) ; ans += ( m - 1 ) * countWays ( index + 1 , cnt + 1 , dp , n , m , k ) ; return dp [ index ] [ cnt ] = ans ; } int main ( ) { int n = 3 , m = 3 , k = 2 ; int dp [ n + 1 ] [ max ] ; memset ( dp , -1 , sizeof dp ) ; cout << m * countWays ( 1 , 0 , dp , n , m , k ) ; } |
Number of balanced bracket expressions that can be formed from a string | C ++ program to find number of balanced bracket expressions possible ; Max string length ; Function to check whether index start and end can form a bracket pair or not ; Check for brackets ( ) ; Check for brackets [ ] ; Check for brackets { } ; Function to find number of proper bracket expressions ; If starting index is greater than ending index ; If dp [ start ] [ end ] has already been computed ; Search for the bracket in from next index ; If bracket pair is formed , add number of combination ; If ? comes then all three bracket expressions are possible ; Return answer ; If n is odd , string cannot be balanced ; Driving function | #include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long int lli ; const int MAX = 300 ; int checkFunc ( int i , int j , string st ) { if ( st [ i ] == ' ( ' && st [ j ] == ' ) ' ) return 1 ; if ( st [ i ] == ' ( ' && st [ j ] == ' ? ' ) return 1 ; if ( st [ i ] == ' ? ' && st [ j ] == ' ) ' ) return 1 ; if ( st [ i ] == ' [ ' && st [ j ] == ' ] ' ) return 1 ; if ( st [ i ] == ' [ ' && st [ j ] == ' ? ' ) return 1 ; if ( st [ i ] == ' ? ' && st [ j ] == ' ] ' ) return 1 ; if ( st [ i ] == ' { ' && st [ j ] == ' } ' ) return 1 ; if ( st [ i ] == ' { ' && st [ j ] == ' ? ' ) return 1 ; if ( st [ i ] == ' ? ' && st [ j ] == ' } ' ) return 1 ; return 0 ; } int countRec ( int start , int end , int dp [ ] [ MAX ] , string st ) { int sum = 0 ; if ( start > end ) return 1 ; if ( dp [ start ] [ end ] != -1 ) return dp [ start ] [ end ] ; lli i , r = 0 ; for ( i = start + 1 ; i <= end ; i += 2 ) { if ( checkFunc ( start , i , st ) ) { sum = sum + countRec ( start + 1 , i - 1 , dp , st ) * countRec ( i + 1 , end , dp , st ) ; } else if ( st [ start ] == ' ? ' && st [ i ] == ' ? ' ) { sum = sum + countRec ( start + 1 , i - 1 , dp , st ) * countRec ( i + 1 , end , dp , st ) * 3 ; } } return dp [ start ] [ end ] = sum ; } int countWays ( string st ) { int n = st . length ( ) ; if ( n % 2 == 1 ) return 0 ; int dp [ MAX ] [ MAX ] ; memset ( dp , -1 , sizeof ( dp ) ) ; return countRec ( 0 , n - 1 , dp , st ) ; } int main ( ) { string st = " ( ? ( [ ? ) ] ? } ? " ; cout << countWays ( st ) ; return 0 ; } |
Count pairs ( A , B ) such that A has X and B has Y number of set bits and A + B = C | C ++ implementation of the above approach ; Initial DP array ; Recursive function to generate all combinations of bits ; if the state has already been visited ; find if C has no more set bits on left ; if no set bits are left for C and there are no set bits for A and B and the carry is 0 , then this combination is possible ; if no set bits are left for C and requirement of set bits for A and B have exceeded ; Find if the bit is 1 or 0 at third index to the left ; carry = 1 and bit set = 1 ; since carry is 1 , and we need 1 at C 's bit position we can use 0 and 0 or 1 and 1 at A and B bit position ; carry = 0 and bit set = 1 ; since carry is 0 , and we need 1 at C 's bit position we can use 1 and 0 or 0 and 1 at A and B bit position ; carry = 1 and bit set = 0 ; since carry is 1 , and we need 0 at C 's bit position we can use 1 and 0 or 0 and 1 at A and B bit position ; carry = 0 and bit set = 0 ; since carry is 0 , and we need 0 at C 's bit position we can use 0 and 0 or 1 and 1 at A and B bit position ; Function to count ways ; function call that returns the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 64 ] [ 64 ] [ 64 ] [ 2 ] ; int func ( int third , int seta , int setb , int carry , int number ) { if ( dp [ third ] [ seta ] [ setb ] [ carry ] != -1 ) return dp [ third ] [ seta ] [ setb ] [ carry ] ; int shift = ( number >> third ) ; if ( shift == 0 and seta == 0 and setb == 0 and carry == 0 ) return 1 ; if ( shift == 0 or seta < 0 or setb < 0 ) return 0 ; int mask = shift & 1 ; dp [ third ] [ seta ] [ setb ] [ carry ] = 0 ; if ( ( mask ) && carry ) { dp [ third ] [ seta ] [ setb ] [ carry ] += func ( third + 1 , seta , setb , 0 , number ) + func ( third + 1 , seta - 1 , setb - 1 , 1 , number ) ; } else if ( mask && ! carry ) { dp [ third ] [ seta ] [ setb ] [ carry ] += func ( third + 1 , seta - 1 , setb , 0 , number ) + func ( third + 1 , seta , setb - 1 , 0 , number ) ; } else if ( ! mask && carry ) { dp [ third ] [ seta ] [ setb ] [ carry ] += func ( third + 1 , seta - 1 , setb , 1 , number ) + func ( third + 1 , seta , setb - 1 , 1 , number ) ; } else if ( ! mask && ! carry ) { dp [ third ] [ seta ] [ setb ] [ carry ] += func ( third + 1 , seta , setb , 0 , number ) + func ( third + 1 , seta - 1 , setb - 1 , 1 , number ) ; } return dp [ third ] [ seta ] [ setb ] [ carry ] ; } int possibleSwaps ( int a , int b , int c ) { memset ( dp , -1 , sizeof ( dp ) ) ; int ans = func ( 0 , a , b , 0 , c ) ; return ans ; } int main ( ) { int x = 2 , y = 2 , c = 20 ; cout << possibleSwaps ( x , y , c ) ; return 0 ; } |
Sum of Fibonacci numbers at even indexes upto N terms | C ++ Program to find sum of even - indiced Fibonacci numbers ; Computes value of first fibonacci numbers and stores the even - indexed sum ; Initialize result ; Add remaining terms ; For even indices ; Return the alternting sum ; Driver program to test above function ; Get n ; Find the even - indiced sum | #include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateEvenSum ( int n ) { if ( n <= 0 ) return 0 ; int fibo [ 2 * n + 1 ] ; fibo [ 0 ] = 0 , fibo [ 1 ] = 1 ; int sum = 0 ; for ( int i = 2 ; i <= 2 * n ; i ++ ) { fibo [ i ] = fibo [ i - 1 ] + fibo [ i - 2 ] ; if ( i % 2 == 0 ) sum += fibo [ i ] ; } return sum ; } int main ( ) { int n = 8 ; cout << " Even β indexed β Fibonacci β Sum β upto β " << n << " β terms : β " << calculateEvenSum ( n ) << endl ; return 0 ; } |
Sum of Fibonacci numbers at even indexes upto N terms | C ++ Program to find even indexed Fibonacci Sum in O ( Log n ) time . ; Create an array for memoization ; Returns n 'th Fibonacci number using table f[] ; Base cases ; If fib ( n ) is already computed ; Applying above formula [ Note value n & 1 is 1 if n is odd , else 0 ] . ; Computes value of even - indexed Fibonacci Sum ; Driver program to test above function ; Get n ; Find the alternating sum | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000 ; int f [ MAX ] = { 0 } ; int fib ( int n ) { if ( n == 0 ) return 0 ; if ( n == 1 n == 2 ) return ( f [ n ] = 1 ) ; if ( f [ n ] ) return f [ n ] ; int k = ( n & 1 ) ? ( n + 1 ) / 2 : n / 2 ; f [ n ] = ( n & 1 ) ? ( fib ( k ) * fib ( k ) + fib ( k - 1 ) * fib ( k - 1 ) ) : ( 2 * fib ( k - 1 ) + fib ( k ) ) * fib ( k ) ; return f [ n ] ; } int calculateEvenSum ( int n ) { return ( fib ( 2 * n + 1 ) - 1 ) ; } int main ( ) { int n = 8 ; cout << " Even β indexed β Fibonacci β Sum β upto β " << n << " β terms : β " << calculateEvenSum ( n ) << endl ; return 0 ; } |
Gould 's Sequence | CPP program to generate Gould 's Sequence ; 32768 = 2 ^ 15 ; Array to store Sequence up to 2 ^ 16 = 65536 ; Utility function to pre - compute odd numbers in ith row of Pascals 's triangle ; First term of the Sequence is 1 ; Initialize i to 1 ; Initialize p to 1 ( i . e 2 ^ i ) in each iteration i will be pth power of 2 ; loop to generate gould 's Sequence ; i is pth power of 2 traverse the array from j = 0 to i i . e ( 2 ^ p ) ; double the value of arr [ j ] and store to arr [ i + j ] ; update i to next power of 2 ; increment p ; Function to print gould 's Sequence ; loop to generate gould 's Sequence up to n ; Driver code ; Get n ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 32768 NEW_LINE int arr [ 2 * MAX ] ; int gouldSequence ( ) { arr [ 0 ] = 1 ; int i = 1 ; int p = 1 ; while ( i <= MAX ) { int j = 0 ; while ( j < i ) { arr [ i + j ] = 2 * arr [ j ] ; j ++ ; } i = ( 1 << p ) ; p ++ ; } } void printSequence ( int n ) { for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " β " ; } } int main ( ) { gouldSequence ( ) ; int n = 16 ; printSequence ( n ) ; return 0 ; } |
Count the number of ways to traverse a Matrix | C ++ program for above approach ; Find factorial ; Find number of ways to reach mat [ m - 1 ] [ n - 1 ] from mat [ 0 ] [ 0 ] in a matrix mat [ ] [ ] ] ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int factorial ( int n ) { int res = 1 , i ; for ( i = 2 ; i <= n ; i ++ ) res *= i ; return res ; } int countWays ( int m , int n ) { m = m - 1 ; n = n - 1 ; return factorial ( m + n ) / ( factorial ( m ) * factorial ( n ) ) ; } int main ( ) { int m = 5 ; int n = 5 ; int result = countWays ( m , n ) ; cout << result ; } |
Matrix Chain Multiplication ( A O ( N ^ 2 ) Solution ) | CPP program to implement optimized matrix chain multiplication problem . ; Matrix Mi has dimension p [ i - 1 ] x p [ i ] for i = 1. . n ; For simplicity of the program , one extra row and one extra column are allocated in dp [ ] [ ] . 0 th row and 0 th column of dp [ ] [ ] are not used ; cost is zero when multiplying one matrix . ; Simply following above recursive formula . ; Driver code | #include <iostream> NEW_LINE using namespace std ; int MatrixChainOrder ( int p [ ] , int n ) { int dp [ n ] [ n ] ; for ( int i = 1 ; i < n ; i ++ ) dp [ i ] [ i ] = 0 ; for ( int L = 1 ; L < n - 1 ; L ++ ) for ( int i = 1 ; i < n - L ; i ++ ) dp [ i ] [ i + L ] = min ( dp [ i + 1 ] [ i + L ] + p [ i - 1 ] * p [ i ] * p [ i + L ] , dp [ i ] [ i + L - 1 ] + p [ i - 1 ] * p [ i + L - 1 ] * p [ i + L ] ) ; return dp [ 1 ] [ n - 1 ] ; } int main ( ) { int arr [ ] = { 10 , 20 , 30 , 40 , 30 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Minimum β number β of β multiplications β is β % d β " , MatrixChainOrder ( arr , size ) ) ; return 0 ; } |
Count common subsequence in two strings | C ++ program to count common subsequence in two strings ; return the number of common subsequence in two strings ; for each character of S ; for each character in T ; if character are same in both the string ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CommomSubsequencesCount ( string s , string t ) { int n1 = s . length ( ) ; int n2 = t . length ( ) ; int dp [ n1 + 1 ] [ n2 + 1 ] ; for ( int i = 0 ; i <= n1 ; i ++ ) { for ( int j = 0 ; j <= n2 ; j ++ ) { dp [ i ] [ j ] = 0 ; } } for ( int i = 1 ; i <= n1 ; i ++ ) { for ( int j = 1 ; j <= n2 ; j ++ ) { if ( s [ i - 1 ] == t [ j - 1 ] ) dp [ i ] [ j ] = 1 + dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ j ] ; else dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ j ] - dp [ i - 1 ] [ j - 1 ] ; } } return dp [ n1 ] [ n2 ] ; } int main ( ) { string s = " ajblqcpdz " ; string t = " aefcnbtdi " ; cout << CommomSubsequencesCount ( s , t ) << endl ; return 0 ; } |
Minimum number of palindromes required to express N as a sum | Set 2 | C ++ program to find the minimum number of palindromes required to express N as a sum ; A utility for creating palindrome ; checks if number of digits is odd or even if odd then neglect the last digit of input in finding reverse as in case of odd number of digits middle element occur once ; Creates palindrome by just appending reverse of number to itself ; Function to generate palindromes ; Run two times for odd and even length palindromes ; Creates palindrome numbers with first half as i . Value of j decides whether we need an odd length or even length palindrome . ; Function to find the minimum number of palindromes required to express N as a sum ; Checking if the number is a palindrome ; Getting the list of all palindromes upto N ; Sorting the list of palindromes ; The answer is three if the control reaches till this point ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int createPalindrome ( int input , bool isOdd ) { int n = input ; int palin = input ; if ( isOdd ) n /= 10 ; while ( n > 0 ) { palin = palin * 10 + ( n % 10 ) ; n /= 10 ; } return palin ; } vector < int > generatePalindromes ( int N ) { vector < int > palindromes ; int number ; for ( int j = 0 ; j < 2 ; j ++ ) { int i = 1 ; while ( ( number = createPalindrome ( i ++ , j ) ) <= N ) palindromes . push_back ( number ) ; } return palindromes ; } int minimumNoOfPalindromes ( int N ) { string a , b = a = to_string ( N ) ; reverse ( b . begin ( ) , b . end ( ) ) ; if ( a == b ) return 1 ; vector < int > palindromes = generatePalindromes ( N ) ; sort ( palindromes . begin ( ) , palindromes . end ( ) ) ; int l = 0 , r = palindromes . size ( ) - 1 ; while ( l < r ) { if ( palindromes [ l ] + palindromes [ r ] == N ) return 2 ; else if ( palindromes [ l ] + palindromes [ r ] < N ) ++ l ; else -- r ; } return 3 ; } int main ( ) { int N = 65 ; cout << minimumNoOfPalindromes ( N ) ; return 0 ; } |
Minimum Cost to make two Numeric Strings Identical | CPP program to find minimum cost to make two numeric strings identical ; Function to find weight of LCS ; if this state is already calculated then return ; adding required weight for particular match ; recurse for left and right child and store the max ; Function to calculate cost of string ; Driver code ; Minimum cost needed to make two strings identical | #include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long int ll ; int lcs ( int dp [ 101 ] [ 101 ] , string a , string b , int m , int n ) { for ( int i = 0 ; i < 100 ; i ++ ) for ( int j = 0 ; j < 100 ; j ++ ) dp [ i ] [ j ] = -1 ; if ( m < 0 n < 0 ) { return 0 ; } if ( dp [ m ] [ n ] != -1 ) return dp [ m ] [ n ] ; int ans = 0 ; if ( a [ m ] == b [ n ] ) { ans = int ( a [ m ] - 48 ) + lcs ( dp , a , b , m - 1 , n - 1 ) ; } else ans = max ( lcs ( dp , a , b , m - 1 , n ) , lcs ( dp , a , b , m , n - 1 ) ) ; dp [ m ] [ n ] = ans ; return ans ; } int costOfString ( string str ) { int cost = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) cost += int ( str [ i ] - 48 ) ; return cost ; } int main ( ) { string a , b ; a = "9142" ; b = "1429" ; int dp [ 101 ] [ 101 ] ; cout << ( costOfString ( a ) + costOfString ( b ) - 2 * lcs ( dp , a , b , a . length ( ) - 1 , b . length ( ) - 1 ) ) ; return 0 ; } |
Longest subarray having maximum sum | C ++ implementation to find the length of the longest subarray having maximum sum ; function to find the maximum sum that exists in a subarray ; function to find the length of longest subarray having sum k ; unordered_map ' um ' implemented as hash table ; traverse the given array ; accumulate sum ; when subarray starts from index '0' ; make an entry for ' sum ' if it is not present in ' um ' ; check if ' sum - k ' is present in ' um ' or not ; update maxLength ; required maximum length ; function to find the length of the longest subarray having maximum sum ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubArraySum ( int arr [ ] , int size ) { int max_so_far = arr [ 0 ] ; int curr_max = arr [ 0 ] ; for ( int i = 1 ; i < size ; i ++ ) { curr_max = max ( arr [ i ] , curr_max + arr [ i ] ) ; max_so_far = max ( max_so_far , curr_max ) ; } return max_so_far ; } int lenOfLongSubarrWithGivenSum ( int arr [ ] , int n , int k ) { unordered_map < int , int > um ; int sum = 0 , maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum == k ) maxLen = i + 1 ; if ( um . find ( sum ) == um . end ( ) ) um [ sum ] = i ; if ( um . find ( sum - k ) != um . end ( ) ) { if ( maxLen < ( i - um [ sum - k ] ) ) maxLen = i - um [ sum - k ] ; } } return maxLen ; } int lenLongSubarrWithMaxSum ( int arr [ ] , int n ) { int maxSum = maxSubArraySum ( arr , n ) ; return lenOfLongSubarrWithGivenSum ( arr , n , maxSum ) ; } int main ( ) { int arr [ ] = { 5 , -2 , -1 , 3 , -4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Length β of β longest β subarray β having β maximum β sum β = β " << lenLongSubarrWithMaxSum ( arr , n ) ; return 0 ; } |
Find the largest area rectangular sub | C ++ implementation to find the largest area rectangular sub - matrix whose sum is equal to k ; This function basically finds largest ' k ' sum subarray in arr [ 0. . n - 1 ] . If ' k ' sum doesn 't exist, then it returns false. Else it returns true and sets starting and ending indexes as start and end. ; unordered_map ' um ' implemented as hash table ; traverse the given array ; accumulate sum ; when subarray starts from index '0' update maxLength and start and end points ; make an entry for ' sum ' if it is not present in ' um ' ; check if ' sum - k ' is present in ' um ' or not ; update maxLength and start and end points ; Return true if maximum length is non - zero ; function to find the largest area rectangular sub - matrix whose sum is equal to k ; Variables to store the temporary values ; Variables to store the final output ; Set the left column ; Initialize all elements of temp as 0 ; Set the right column for the left column set by outer loop ; Calculate sum between current left and right column for every row ' i ' ; Find largest subarray with ' k ' sum in temp [ ] . The sumEqualToK ( ) function also sets values of ' up ' and ' down ; ' . So if ' sum ' is true then rectangle exists between ( up , left ) and ( down , right ) which are the boundary values . ; Compare no . of elements with previous no . of elements in sub - Matrix . If new sub - matrix has more elements then update maxArea and final boundaries like fup , fdown , fleft , fright ; If there is no change in boundaries than check if mat [ 0 ] [ 0 ] equals ' k ' If it is not equal to ' k ' then print that no such k - sum sub - matrix exists ; Print final values ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; bool sumEqualToK ( int arr [ ] , int & start , int & end , int n , int k ) { unordered_map < int , int > um ; int sum = 0 , maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum == k ) { maxLen = i + 1 ; start = 0 ; end = i ; } if ( um . find ( sum ) == um . end ( ) ) um [ sum ] = i ; if ( um . find ( sum - k ) != um . end ( ) ) { if ( maxLen < ( i - um [ sum - k ] ) ) { maxLen = i - um [ sum - k ] ; start = um [ sum - k ] + 1 ; end = i ; } } } return ( maxLen != 0 ) ; } void sumZeroMatrix ( int mat [ ] [ MAX ] , int row , int col , int k ) { int temp [ row ] , area ; bool sum ; int up , down ; int fup = 0 , fdown = 0 , fleft = 0 , fright = 0 ; int maxArea = INT_MIN ; for ( int left = 0 ; left < col ; left ++ ) { memset ( temp , 0 , sizeof ( temp ) ) ; for ( int right = left ; right < col ; right ++ ) { for ( int i = 0 ; i < row ; i ++ ) temp [ i ] += mat [ i ] [ right ] ; sum = sumEqualToK ( temp , up , down , row , k ) ; area = ( down - up + 1 ) * ( right - left + 1 ) ; if ( sum && maxArea < area ) { fup = up ; fdown = down ; fleft = left ; fright = right ; maxArea = area ; } } } if ( fup == 0 && fdown == 0 && fleft == 0 && fright == 0 && mat [ 0 ] [ 0 ] != k ) { cout << " No β sub - matrix β with β sum β " << k << " β exists " ; return ; } cout << " ( Top , β Left ) : β " << " ( " << fup << " , β " << fleft << " ) " << endl ; cout << " ( Bottom , β Right ) : β " << " ( " << fdown << " , β " << fright << " ) " << endl ; for ( int j = fup ; j <= fdown ; j ++ ) { for ( int i = fleft ; i <= fright ; i ++ ) cout << mat [ j ] [ i ] << " β " ; cout << endl ; } } int main ( ) { int mat [ ] [ MAX ] = { { 1 , 7 , -6 , 5 } , { -8 , 6 , 7 , -2 } , { 10 , -15 , 3 , 2 } , { -5 , 2 , 0 , 9 } } ; int row = 4 , col = 4 ; int k = 7 ; sumZeroMatrix ( mat , row , col , k ) ; return 0 ; } |
Sum of elements of all partitions of number such that no element is less than K | C ++ implementation of above approach ; Function that returns total number of valid partitions of integer N ; Global declaration of 2D dp array which will be later used for memoization ; initializing 2D dp array with - 1 we will use this 2D array for memoization ; if this subproblem is already previously calculated , then directly return that answer ; if N < K , then no valid partition is possible ; if N is between K to 2 * K then there is only one partition and that is the number N itself ; Initialize answer with 1 as the number N itself is always a valid partition ; for loop to iterate over K to N and find number of possible valid partitions recursively . ; memoization is done by storing this calculated answer ; returning number of valid partitions ; Driver code ; Printing total number of valid partitions | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int countPartitions ( int n , int k ) { long long int dp [ 201 ] [ 201 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) { for ( int j = 0 ; j < n + 1 ; j ++ ) { dp [ i ] [ j ] = -1 ; } } if ( dp [ n ] [ k ] >= 0 ) return dp [ n ] [ k ] ; if ( n < k ) return 0 ; if ( n < 2 * k ) return 1 ; long long int answer = 1 ; for ( int i = k ; i < n ; i ++ ) answer = answer + countPartitions ( n - i , i ) ; dp [ n ] [ k ] = answer ; return answer ; } int main ( ) { int n = 10 , k = 3 ; cout << " Total β Aggregate β sum β of β all β Valid β Partitions : β " << countPartitions ( n , k ) * n ; return 0 ; } |
Number of Co | C ++ program to count the pairs whose sum of digits is co - prime ; Function to find the elements after doing the sum of digits ; Traverse from a to b ; Find the sum of the digits of the elements in the given range one by one ; Function to count the co - prime pairs ; Function to make the pairs by doing the sum of digits ; Count pairs that are co - primes ; Driver code ; Function to count the pairs | #include <bits/stdc++.h> NEW_LINE using namespace std ; int makePairs ( vector < int > & pairs , int a , int b ) { for ( int i = a ; i <= b ; i ++ ) { int sumOfDigits = 0 , k = i ; while ( k > 0 ) { sumOfDigits += k % 10 ; k /= 10 ; } if ( sumOfDigits <= 162 ) pairs . push_back ( sumOfDigits ) ; } } int countCoPrime ( int a , int b ) { vector < int > pairs ; makePairs ( pairs , a , b ) ; int count = 0 ; for ( int i = 0 ; i < pairs . size ( ) ; i ++ ) for ( int j = i + 1 ; j < pairs . size ( ) ; j ++ ) if ( __gcd ( pairs [ i ] , pairs [ j ] ) == 1 ) count ++ ; return count ; } int main ( ) { int a = 12 , b = 15 ; cout << countCoPrime ( a , b ) ; return 0 ; } |
Number of Co | C ++ program to count the pairs whose sum of digits is co - prime ; Recursive function to return the frequency of numbers having their sum of digits i ; Returns 1 or 0 ; Returns value of the dp if already stored ; Loop from digit 0 to 9 ; To change the tight to 1 ; Calling the recursive function to find the frequency ; Function to find out frequency of numbers from 1 to N having their sum of digits from 1 to 162 and store them in array ; Number to string conversion ; Calling the recursive function and pushing it into array ; Function to find the pairs ; Calling the formArray function of a - 1 numbers ; Calling the formArray function of b numbers ; Subtracting the frequency of higher number array with lower number array and thus finding the range of numbers from a to b having sum from 1 to 162 ; To find out total number of pairs which are co - prime ; Driver code ; Function to count the pairs | #include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll recursive ( ll idx , ll sum , ll tight , string st , ll dp [ 20 ] [ 2 ] [ 166 ] , ll num ) { if ( idx == num ) return sum == 0 ; if ( dp [ idx ] [ tight ] [ sum ] != -1 ) return dp [ idx ] [ tight ] [ sum ] ; bool newTight ; ll ans = 0 ; ll d ; for ( d = 0 ; d < 10 ; ++ d ) { newTight = false ; if ( tight && st [ idx ] - '0' < d ) continue ; if ( tight && st [ idx ] - '0' == d ) newTight = true ; if ( sum >= d ) ans += recursive ( idx + 1 , sum - d , newTight , st , dp , num ) ; } return dp [ idx ] [ tight ] [ sum ] = ans ; } vector < ll > formArray ( ll N ) { ll dp [ 20 ] [ 2 ] [ 166 ] ; memset ( dp , -1 , sizeof dp ) ; ostringstream x ; x << N ; string st = x . str ( ) ; ll num = st . size ( ) ; vector < ll > arr ; for ( int i = 1 ; i <= 162 ; ++ i ) { arr . push_back ( recursive ( 0 , i , 1 , st , dp , num ) ) ; } return arr ; } ll findPair ( ll a , ll b ) { vector < ll > arr_smaller = formArray ( a - 1 ) ; vector < ll > arr_greater = formArray ( b ) ; for ( int i = 0 ; i < arr_greater . size ( ) ; ++ i ) arr_greater [ i ] -= arr_smaller [ i ] ; int ans = 0 ; for ( int i = 1 ; i <= 162 ; ++ i ) { for ( int j = i + 1 ; j <= 162 ; ++ j ) { if ( __gcd ( i , j ) == 1 ) ans = ( ans + arr_greater [ i - 1 ] * arr_greater [ j - 1 ] ) ; } } return ans ; } int main ( ) { ll a = 12 , b = 15 ; cout << findPair ( a , b ) ; return 0 ; } |
Semiperfect Number | C ++ program to check if the number is semi - perfect or not ; code to find all the factors of the number excluding the number itself ; vector to store the factors ; note that this loop runs till sqrt ( n ) ; if the value of i is a factor ; condition to check the divisor is not the number itself ; return the vector ; Function to check if the number is semi - perfect or not ; find the divisors ; sorting the vector ; subset to check if no is semiperfect ; initialising 1 st column to true ; initializing 1 st row except zero position to 0 ; loop to find whether the number is semiperfect ; calculation to check if the number can be made by summation of divisors ; if not possible to make the number by any combination of divisors ; driver code to check if possible | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > factors ( int n ) { vector < int > v ; v . push_back ( 1 ) ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { v . push_back ( i ) ; if ( n / i != i ) { v . push_back ( n / i ) ; } } } return v ; } bool check ( int n ) { vector < int > v ; v = factors ( n ) ; sort ( v . begin ( ) , v . end ( ) ) ; int r = v . size ( ) ; bool subset [ r + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= r ; i ++ ) subset [ i ] [ 0 ] = true ; for ( int i = 1 ; i <= n ; i ++ ) subset [ 0 ] [ i ] = false ; for ( int i = 1 ; i <= r ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( j < v [ i - 1 ] ) subset [ i ] [ j ] = subset [ i - 1 ] [ j ] ; else { subset [ i ] [ j ] = subset [ i - 1 ] [ j ] || subset [ i - 1 ] [ j - v [ i - 1 ] ] ; } } } if ( ( subset [ r ] [ n ] ) == 0 ) return false ; else return true ; } int main ( ) { int n = 40 ; if ( check ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Number of ways to represent a number as sum of k fibonacci numbers | C ++ implementation of above approach ; to store fibonacci numbers 42 second number in fibonacci series largest possible integer ; Function to generate fibonacci series ; Recursive function to return the number of ways ; base condition ; for recursive function call ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int fib [ 43 ] = { 0 } ; void fibonacci ( ) { fib [ 0 ] = 1 ; fib [ 1 ] = 2 ; for ( int i = 2 ; i < 43 ; i ++ ) fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] ; } int rec ( int x , int y , int last ) { if ( y == 0 ) { if ( x == 0 ) return 1 ; return 0 ; } int sum = 0 ; for ( int i = last ; i >= 0 and fib [ i ] * y >= x ; i -- ) { if ( fib [ i ] > x ) continue ; sum += rec ( x - fib [ i ] , y - 1 , i ) ; } return sum ; } int main ( ) { fibonacci ( ) ; int n = 13 , k = 3 ; cout << " Possible β ways β are : β " << rec ( n , k , 42 ) ; return 0 ; } |
Minimum cost to reach the top of the floor by climbing stairs | C ++ program to find the minimum cost required to reach the n - th floor ; function to find the minimum cost to reach N - th floor ; declare an array ; base case ; initially to climb till 0 - th or 1 th stair ; iterate for finding the cost ; return the minimum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumCost ( int cost [ ] , int n ) { int dp [ n ] ; if ( n == 1 ) return cost [ 0 ] ; dp [ 0 ] = cost [ 0 ] ; dp [ 1 ] = cost [ 1 ] ; for ( int i = 2 ; i < n ; i ++ ) { dp [ i ] = min ( dp [ i - 1 ] , dp [ i - 2 ] ) + cost [ i ] ; } return min ( dp [ n - 2 ] , dp [ n - 1 ] ) ; } int main ( ) { int a [ ] = { 16 , 19 , 10 , 12 , 18 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << minimumCost ( a , n ) ; return 0 ; } |
Minimum cost to reach the top of the floor by climbing stairs | C ++ program to find the minimum cost required to reach the n - th floor space - optimized solution ; function to find the minimum cost to reach N - th floor ; traverse till N - th stair ; update the last two stairs value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumCost ( int cost [ ] , int n ) { int dp1 = 0 , dp2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int dp0 = cost [ i ] + min ( dp1 , dp2 ) ; dp2 = dp1 ; dp1 = dp0 ; } return min ( dp1 , dp2 ) ; } int main ( ) { int a [ ] = { 2 , 5 , 3 , 1 , 7 , 3 , 4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << minimumCost ( a , n ) ; return 0 ; } |
Sudo Placement [ 1.5 ] | Wolfish | C ++ program for SP - Wolfish ; Function to find the maxCost of path from ( n - 1 , n - 1 ) to ( 0 , 0 ) ; base condition ; reaches the point ; if the state has been visited previously ; i + j ; check if it is a power of 2 , then only move diagonally ; if not a power of 2 then move side - wise ; Function to return the maximum cost ; calling dp function to get the answer ; Driver Code ; Function calling to get the answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int size = 1000 ; int maxCost ( int a [ ] [ size ] , int m , int n , int dp [ ] [ size ] ) { if ( n < 0 m < 0 ) return -1e9 ; else if ( m == 0 && n == 0 ) return 0 ; else if ( dp [ m ] [ n ] != -1 ) return dp [ m ] [ n ] ; else { int num = m + n ; if ( ( num & ( num - 1 ) ) == 0 ) return dp [ m ] [ n ] = a [ m ] [ n ] + maxCost ( a , m - 1 , n - 1 , dp ) ; else return dp [ m ] [ n ] = ( a [ m ] [ n ] + max ( maxCost ( a , m - 1 , n , dp ) , maxCost ( a , m , n - 1 , dp ) ) ) ; } } int answer ( int a [ ] [ size ] , int n ) { int dp [ size ] [ size ] ; memset ( dp , -1 , sizeof dp ) ; return maxCost ( a , n - 1 , n - 1 , dp ) ; } int main ( ) { int a [ ] [ size ] = { { 1 , 2 , 3 , 1 } , { 4 , 5 , 6 , 1 } , { 7 , 8 , 9 , 1 } , { 1 , 1 , 1 , 1 } } ; int n = 4 ; cout << answer ( a , n ) ; return 0 ; } |
Edit distance and LCS ( Longest Common Subsequence ) | CPP program to find Edit Distance ( when only twooperations are allowed , insert and delete ) using LCS . ; Find LCS ; Edit distance is delete operations + insert operations . ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int editDistanceWith2Ops ( string & X , string & Y ) { int m = X . length ( ) , n = Y . length ( ) ; int L [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; else L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } int lcs = L [ m ] [ n ] ; return ( m - lcs ) + ( n - lcs ) ; } int main ( ) { string X = " abc " , Y = " acd " ; cout << editDistanceWith2Ops ( X , Y ) ; return 0 ; } |
Longest Common Subsequence | DP using Memoization | A Naive C ++ recursive implementation of LCS of two strings ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Driver Code ; Find the length of string | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lcs ( string X , string Y , int m , int n ) { if ( m == 0 n == 0 ) return 0 ; if ( X [ m - 1 ] == Y [ n - 1 ] ) return 1 + lcs ( X , Y , m - 1 , n - 1 ) ; else return max ( lcs ( X , Y , m , n - 1 ) , lcs ( X , Y , m - 1 , n ) ) ; } int main ( ) { string X = " AGGTAB " ; string Y = " GXTXAYB " ; int m = X . length ( ) ; int n = Y . length ( ) ; cout << " Length β of β LCS : β " << lcs ( X , Y , m , n ) ; return 0 ; } |
Number of different cyclic paths of length N in a tetrahedron | C ++ program count total number of paths to reach B from B ; Function to count the number of steps in a tetrahedron ; initially coming to B is B -> B ; cannot reach A , D or C ; iterate for all steps ; recurrence relation ; memoize previous values ; returns steps ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int countPaths ( int n ) { int zB = 1 ; int zADC = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int nzB = zADC * 3 ; int nzADC = ( zADC * 2 + zB ) ; zB = nzB ; zADC = nzADC ; } return zB ; } int main ( ) { int n = 3 ; cout << countPaths ( n ) ; return 0 ; } |
Maximum sub | C ++ implementation to find the maximum area sub - matrix having count of 1 ' s β one β more β than β count β of β 0' s ; function to find the length of longest subarray having count of 1 ' s β one β more β than β count β of β 0' s ; unordered_map ' um ' implemented as hash table ; traverse the given array ; accumulating sum ; when subarray starts form index '0' ; make an entry for ' sum ' if it is not present in ' um ' ; check if ' sum - 1' is present in ' um ' or not ; update ' start ' , ' finish ' and maxLength ; required maximum length ; function to find the maximum area sub - matrix having count of 1 ' s β one β more β than β count β of β 0' s ; variables to store final and intermediate results ; set the left column ; Initialize all elements of temp as 0 ; Set the right column for the left column set by outer loop ; Calculate sum between current left and right for every row ' i ' , consider '0' as ' - 1' ; function to set the ' start ' and ' finish ' variables having index values of temp [ ] which contains the longest subarray of temp [ ] having count of 1 ' s β β one β more β than β count β of β 0' s ; Compare with maximum area so far and accordingly update the final variables ; Print final values ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 10 NEW_LINE int lenOfLongSubarr ( int arr [ ] , int n , int & start , int & finish ) { unordered_map < int , int > um ; int sum = 0 , maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( sum == 1 ) { start = 0 ; finish = i ; maxLen = i + 1 ; } else if ( um . find ( sum ) == um . end ( ) ) um [ sum ] = i ; if ( um . find ( sum - 1 ) != um . end ( ) ) { if ( maxLen < ( i - um [ sum - 1 ] ) ) start = um [ sum - 1 ] + 1 ; finish = i ; maxLen = i - um [ sum - 1 ] ; } } return maxLen ; } void largestSubmatrix ( int mat [ SIZE ] [ SIZE ] , int n ) { int finalLeft , finalRight , finalTop , finalBottom ; int temp [ n ] , maxArea = 0 , len , start , finish ; for ( int left = 0 ; left < n ; left ++ ) { memset ( temp , 0 , sizeof ( temp ) ) ; for ( int right = left ; right < n ; right ++ ) { for ( int i = 0 ; i < n ; ++ i ) temp [ i ] += mat [ i ] [ right ] == 0 ? -1 : 1 ; len = lenOfLongSubarr ( temp , n , start , finish ) ; if ( ( len != 0 ) && ( maxArea < ( finish - start + 1 ) * ( right - left + 1 ) ) ) { finalLeft = left ; finalRight = right ; finalTop = start ; finalBottom = finish ; maxArea = ( finish - start + 1 ) * ( right - left + 1 ) ; } } } cout << " ( Top , β Left ) : β ( " << finalTop << " , β " << finalLeft << " ) STRNEWLINE " ; cout << " ( Bottom , β Right ) : β ( " << finalBottom << " , β " << finalRight << " ) STRNEWLINE " ; cout << " Maximum β area : β " << maxArea ; } int main ( ) { int mat [ SIZE ] [ SIZE ] = { { 1 , 0 , 0 , 1 } , { 0 , 1 , 1 , 1 } , { 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 } } ; int n = 4 ; largestSubmatrix ( mat , n ) ; return 0 ; } |
Minimum steps to reach target by a Knight | Set 2 | C ++ code for minimum steps for a knight to reach target position ; initializing the matrix . ; if knight is on the target position return 0. ; if already calculated then return that value . Taking absolute difference . ; there will be two distinct positions from the knight towards a target . if the target is in same row or column as of knight than there can be four positions towards the target but in that two would be the same and the other two would be the same . ; ( x1 , y1 ) and ( x2 , y2 ) are two positions . these can be different according to situation . From position of knight , the chess board can be divided into four blocks i . e . . N - E , E - S , S - W , W - N . ; ans will be , 1 + minimum of steps required from ( x1 , y1 ) and ( x2 , y2 ) . ; exchanging the coordinates x with y of both knight and target will result in same ans . ; Driver Code ; size of chess board n * n ; ( x , y ) coordinate of the knight . ( tx , ty ) coordinate of the target position . ; ( Exception ) these are the four corner points for which the minimum steps is 4. ; dp [ a ] [ b ] , here a , b is the difference of x & tx and y & ty respectively . | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 8 ] [ 8 ] = { 0 } ; int getsteps ( int x , int y , int tx , int ty ) { if ( x == tx && y == ty ) return dp [ 0 ] [ 0 ] ; else { if ( dp [ abs ( x - tx ) ] [ abs ( y - ty ) ] != 0 ) return dp [ abs ( x - tx ) ] [ abs ( y - ty ) ] ; else { int x1 , y1 , x2 , y2 ; if ( x <= tx ) { if ( y <= ty ) { x1 = x + 2 ; y1 = y + 1 ; x2 = x + 1 ; y2 = y + 2 ; } else { x1 = x + 2 ; y1 = y - 1 ; x2 = x + 1 ; y2 = y - 2 ; } } else { if ( y <= ty ) { x1 = x - 2 ; y1 = y + 1 ; x2 = x - 1 ; y2 = y + 2 ; } else { x1 = x - 2 ; y1 = y - 1 ; x2 = x - 1 ; y2 = y - 2 ; } } dp [ abs ( x - tx ) ] [ abs ( y - ty ) ] = min ( getsteps ( x1 , y1 , tx , ty ) , getsteps ( x2 , y2 , tx , ty ) ) + 1 ; dp [ abs ( y - ty ) ] [ abs ( x - tx ) ] = dp [ abs ( x - tx ) ] [ abs ( y - ty ) ] ; return dp [ abs ( x - tx ) ] [ abs ( y - ty ) ] ; } } } int main ( ) { int i , n , x , y , tx , ty , ans ; n = 100 ; x = 4 ; y = 5 ; tx = 1 ; ty = 1 ; if ( ( x == 1 && y == 1 && tx == 2 && ty == 2 ) || ( x == 2 && y == 2 && tx == 1 && ty == 1 ) ) ans = 4 ; else if ( ( x == 1 && y == n && tx == 2 && ty == n - 1 ) || ( x == 2 && y == n - 1 && tx == 1 && ty == n ) ) ans = 4 ; else if ( ( x == n && y == 1 && tx == n - 1 && ty == 2 ) || ( x == n - 1 && y == 2 && tx == n && ty == 1 ) ) ans = 4 ; else if ( ( x == n && y == n && tx == n - 1 && ty == n - 1 ) || ( x == n - 1 && y == n - 1 && tx == n && ty == n ) ) ans = 4 ; else { dp [ 1 ] [ 0 ] = 3 ; dp [ 0 ] [ 1 ] = 3 ; dp [ 1 ] [ 1 ] = 2 ; dp [ 2 ] [ 0 ] = 2 ; dp [ 0 ] [ 2 ] = 2 ; dp [ 2 ] [ 1 ] = 1 ; dp [ 1 ] [ 2 ] = 1 ; ans = getsteps ( x , y , tx , ty ) ; } cout << ans << endl ; return 0 ; } |
Sequence Alignment problem | CPP program to implement sequence alignment problem . ; function to find out the minimum penalty ; table for storing optimal substructure answers ; initialising the table ; calculating the minimum penalty ; Reconstructing the solution int l = n + m ; maximum possible length ; Final answers for the respective strings ; Since we have assumed the answer to be n + m long , we need to remove the extra gaps in the starting id represents the index from which the arrays xans , yans are useful ; Printing the final answer ; Driver code ; input strings ; initialising penalties of different types ; calling the function to calculate the result | #include <bits/stdc++.h> NEW_LINE using namespace std ; void getMinimumPenalty ( string x , string y , int pxy , int pgap ) { int dp [ m + 1 ] [ n + 1 ] = { 0 } ; for ( i = 0 ; i <= ( n + m ) ; i ++ ) { dp [ i ] [ 0 ] = i * pgap ; dp [ 0 ] [ i ] = i * pgap ; } for ( i = 1 ; i <= m ; i ++ ) { for ( j = 1 ; j <= n ; j ++ ) { if ( x [ i - 1 ] == y [ j - 1 ] ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] ; } else { dp [ i ] [ j ] = min ( { dp [ i - 1 ] [ j - 1 ] + pxy , dp [ i - 1 ] [ j ] + pgap , dp [ i ] [ j - 1 ] + pgap } ) ; } } } i = m ; j = n ; int xpos = l ; int ypos = l ; int xans [ l + 1 ] , yans [ l + 1 ] ; while ( ! ( i == 0 j == 0 ) ) { if ( x [ i - 1 ] == y [ j - 1 ] ) { xans [ xpos -- ] = ( int ) x [ i - 1 ] ; yans [ ypos -- ] = ( int ) y [ j - 1 ] ; i -- ; j -- ; } else if ( dp [ i - 1 ] [ j - 1 ] + pxy == dp [ i ] [ j ] ) { xans [ xpos -- ] = ( int ) x [ i - 1 ] ; yans [ ypos -- ] = ( int ) y [ j - 1 ] ; i -- ; j -- ; } else if ( dp [ i - 1 ] [ j ] + pgap == dp [ i ] [ j ] ) { xans [ xpos -- ] = ( int ) x [ i - 1 ] ; yans [ ypos -- ] = ( int ) ' _ ' ; i -- ; } else if ( dp [ i ] [ j - 1 ] + pgap == dp [ i ] [ j ] ) { xans [ xpos -- ] = ( int ) ' _ ' ; yans [ ypos -- ] = ( int ) y [ j - 1 ] ; j -- ; } } while ( xpos > 0 ) { if ( i > 0 ) xans [ xpos -- ] = ( int ) x [ -- i ] ; else xans [ xpos -- ] = ( int ) ' _ ' ; } while ( ypos > 0 ) { if ( j > 0 ) yans [ ypos -- ] = ( int ) y [ -- j ] ; else yans [ ypos -- ] = ( int ) ' _ ' ; } int id = 1 ; for ( i = l ; i >= 1 ; i -- ) { if ( ( char ) yans [ i ] == ' _ ' && ( char ) xans [ i ] == ' _ ' ) { id = i + 1 ; break ; } } cout << " Minimum β Penalty β in β aligning β the β genes β = β " ; cout << dp [ m ] [ n ] << " STRNEWLINE " ; cout << " The β aligned β genes β are β : STRNEWLINE " ; for ( i = id ; i <= l ; i ++ ) { cout << ( char ) xans [ i ] ; } cout << " STRNEWLINE " ; for ( i = id ; i <= l ; i ++ ) { cout << ( char ) yans [ i ] ; } return ; } int main ( ) { string gene1 = " AGGGCT " ; string gene2 = " AGGCA " ; int misMatchPenalty = 3 ; int gapPenalty = 2 ; getMinimumPenalty ( gene1 , gene2 , misMatchPenalty , gapPenalty ) ; return 0 ; } |
Number of subsets with sum divisible by m | C ++ program which returns the Number of sub sequences ( or subsets ) which are divisible by m . ; Use Dynamic Programming to find sum of subsequences . ; Find sum pf array elements ; dp [ i ] [ j ] would be > 0 if arr [ 0. . i - 1 ] has a subsequence with sum equal to j . ; There is always sum equals zero ; Fill up the dp table ; Initialize the counter ; Check if the sum exists ; check sum is divisible by m ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumSubSequence ( vector < int > arr , int len , int m ) { int sum = 0 ; for ( auto x : arr ) sum += x ; vector < vector < int > > dp ( len + 1 , vector < int > ( sum + 1 , 0 ) ) ; for ( int i = 0 ; i <= len ; i ++ ) dp [ i ] [ 0 ] ++ ; for ( int i = 1 ; i <= len ; i ++ ) { dp [ i ] [ arr [ i - 1 ] ] ++ ; for ( int j = 1 ; j <= sum ; j ++ ) { if ( dp [ i - 1 ] [ j ] > 0 ) { dp [ i ] [ j ] ++ ; dp [ i ] [ j + arr [ i - 1 ] ] ++ ; } } } int count = 0 ; for ( int j = 1 ; j <= sum ; j ++ ) if ( dp [ len ] [ j ] > 0 ) if ( j % m == 0 ) count += dp [ len ] [ j ] ; return count ; } int main ( ) { vector < int > arr { 1 , 2 , 3 } ; int m = 3 ; int len = arr . size ( ) ; cout << sumSubSequence ( arr , len , m ) << endl ; return 0 ; } |
Longest Decreasing Subsequence | CPP program to find the length of the longest decreasing subsequence ; Function that returns the length of the longest decreasing subsequence ; Initialize LDS with 1 for all index The minimum LDS starting with any element is always 1 ; Compute LDS from every index in bottom up manner ; Select the maximum of all the LDS values ; returns the length of the LDS ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lds ( int arr [ ] , int n ) { int lds [ n ] ; int i , j , max = 0 ; for ( i = 0 ; i < n ; i ++ ) lds [ i ] = 1 ; for ( i = 1 ; i < n ; i ++ ) for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] < arr [ j ] && lds [ i ] < lds [ j ] + 1 ) lds [ i ] = lds [ j ] + 1 ; for ( i = 0 ; i < n ; i ++ ) if ( max < lds [ i ] ) max = lds [ i ] ; return max ; } int main ( ) { int arr [ ] = { 15 , 27 , 14 , 38 , 63 , 55 , 46 , 65 , 85 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Length β of β LDS β is β " << lds ( arr , n ) ; return 0 ; } |
Total number of decreasing paths in a matrix | CPP program to count number of decreasing path in a matrix ; Function that returns the number of decreasing paths from a cell ( i , j ) ; checking if already calculated ; all possible paths ; counts the total number of paths ; In all four allowed direction . ; new co - ordinates ; Checking if not going out of matrix and next cell value is less than current cell value . ; function that returns the answer ; Function that counts the total decreasing path in the matrix ; Initialising dp [ ] [ ] to - 1. ; Calculating number of decreasing path from each cell . ; Driver Code ; function call that returns the count of decreasing paths in a matrix | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE int CountDecreasingPathsCell ( int mat [ MAX ] [ MAX ] , int dp [ MAX ] [ MAX ] , int n , int x , int y ) { if ( dp [ x ] [ y ] != -1 ) return dp [ x ] [ y ] ; int delta [ 4 ] [ 2 ] = { { 0 , 1 } , { 1 , 0 } , { -1 , 0 } , { 0 , -1 } } ; int newx , newy ; int ans = 1 ; for ( int i = 0 ; i < 4 ; i ++ ) { newx = x + delta [ i ] [ 0 ] ; newy = y + delta [ i ] [ 1 ] ; if ( newx >= 0 && newx < n && newy >= 0 && newy < n && mat [ newx ] [ newy ] < mat [ x ] [ y ] ) { ans += CountDecreasingPathsCell ( mat , dp , n , newx , newy ) ; } } return dp [ x ] [ y ] = ans ; } int countDecreasingPathsMatrix ( int n , int mat [ MAX ] [ MAX ] ) { int dp [ MAX ] [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) dp [ i ] [ j ] = -1 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) sum += CountDecreasingPathsCell ( mat , dp , n , i , j ) ; return sum ; } int main ( ) { int n = 2 ; int mat [ MAX ] [ MAX ] = { { 1 , 2 } , { 1 , 3 } } ; cout << countDecreasingPathsMatrix ( n , mat ) << endl ; return 0 ; } |
Sum of product of consecutive Binomial Coefficients | CPP Program to find sum of product of consecutive Binomial Coefficient . ; Find the binomial coefficient upto nth term ; C [ 0 ] = 1 ; nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Return the sum of the product of consecutive binomial coefficient . ; finding the sum of product of consecutive coefficient . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE void binomialCoeff ( int C [ ] , int n ) { for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = min ( i , n ) ; j > 0 ; j -- ) C [ j ] = C [ j ] + C [ j - 1 ] ; } } int sumOfproduct ( int n ) { int sum = 0 ; int C [ MAX ] = { 0 } ; binomialCoeff ( C , n ) ; for ( int i = 0 ; i <= n ; i ++ ) sum += C [ i ] * C [ i + 1 ] ; return sum ; } int main ( ) { int n = 3 ; cout << sumOfproduct ( n ) << endl ; return 0 ; } |
Sum of product of r and rth Binomial Coefficient ( r * nCr ) | CPP Program to find sum of product of r and rth Binomial Coefficient i . e summation r * nCr ; Return the first n term of binomial coefficient . ; C [ 0 ] = 1 ; nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Return summation of r * nCr ; finding the first n term of binomial coefficient ; Iterate a loop to find the sum . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE void binomialCoeff ( int n , int C [ ] ) { for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = min ( i , n ) ; j > 0 ; j -- ) C [ j ] = C [ j ] + C [ j - 1 ] ; } } int summation ( int n ) { int C [ MAX ] ; memset ( C , 0 , sizeof ( C ) ) ; binomialCoeff ( n , C ) ; int sum = 0 ; for ( int i = 0 ; i <= n ; i ++ ) sum += ( i * C [ i ] ) ; return sum ; } int main ( ) { int n = 2 ; cout << summation ( n ) << endl ; return 0 ; } |
Number of arrays of size N whose elements are positive integers and sum is K | CPP Program to find the number of arrays of size N whose elements are positive integers and sum is K ; Return nCr ; C [ 0 ] = 1 ; nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Return the number of array that can be formed of size n and sum equals to k . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int binomialCoeff ( int n , int k ) { int C [ k + 1 ] ; memset ( C , 0 , sizeof ( C ) ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = min ( i , k ) ; j > 0 ; j -- ) C [ j ] = C [ j ] + C [ j - 1 ] ; } return C [ k ] ; } int countArray ( int N , int K ) { return binomialCoeff ( K - 1 , N - 1 ) ; } int main ( ) { int N = 2 , K = 3 ; cout << countArray ( N , K ) << endl ; return 0 ; } |
Partitioning into two contiguous element subarrays with equal sums | CPP Program to find the minimum element to be added such that the array can be partitioned into two contiguous subarrays with equal sums ; Structure to store the minimum element and its position ; initialize prefix and suffix sum arrays with 0 ; add current element to Sum ; add current element to Sum ; initialize the minimum element to be a large value ; check for the minimum absolute difference between current prefix sum and the next suffix sum element ; if prefixsum has a greater value then position is the next element , else it 's the same element. ; return the data in struct . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct data { int element ; int position ; } ; struct data findMinElement ( int arr [ ] , int n ) { struct data result ; int prefixSum [ n ] = { 0 } ; int suffixSum [ n ] = { 0 } ; prefixSum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { prefixSum [ i ] = prefixSum [ i - 1 ] + arr [ i ] ; } suffixSum [ n - 1 ] = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) { suffixSum [ i ] = suffixSum [ i + 1 ] + arr [ i ] ; } int min = suffixSum [ 0 ] ; int pos ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( abs ( suffixSum [ i + 1 ] - prefixSum [ i ] ) < min ) { min = abs ( suffixSum [ i + 1 ] - prefixSum [ i ] ) ; if ( suffixSum [ i + 1 ] < prefixSum [ i ] ) pos = i + 1 ; else pos = i ; } } result . element = min ; result . position = pos ; return result ; } int main ( ) { int arr [ ] = { 10 , 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; struct data values ; values = findMinElement ( arr , n ) ; cout << " Minimum β element β : β " << values . element << endl << " Position β : β " << values . position ; return 0 ; } |
Number of circular tours that visit all petrol pumps | C ++ Program to find the number of circular tour that visits all petrol pump ; Return the number of pumps from where we can start the journey . ; Making Circular Array . ; for each of the petrol pump . ; If tank is less than 0. ; If starting pump is greater than n , return ans as 0. ; For each of the petrol pump ; Finding the need array ; If need is 0 , increment the count . ; Drivers code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100 NEW_LINE int count ( int n , int c , int a [ ] , int b [ ] ) { int need [ N ] ; for ( int i = 0 ; i < n ; i ++ ) { a [ i + n ] = a [ i ] ; b [ i + n ] = b [ i ] ; } int s = 0 ; int tank = 0 ; for ( int i = 0 ; i < 2 * n ; i ++ ) { tank += a [ i ] ; tank = min ( tank , c ) ; tank -= b [ i ] ; if ( tank < 0 ) { tank = 0 ; s = i + 1 ; } } if ( s >= n ) return 0 ; int ans = 1 ; need [ s + n ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int id = s + n - i ; need [ id ] = max ( 0 , need [ id + 1 ] + b [ id ] - min ( a [ id ] , c ) ) ; if ( need [ id ] == 0 ) ans ++ ; } return ans ; } int main ( ) { int n = 3 ; int c = 3 ; int a [ 2 * N ] = { 3 , 1 , 2 } ; int b [ 2 * N ] = { 2 , 2 , 2 } ; cout << count ( n , c , a , b ) << endl ; return 0 ; } |
Print equal sum sets of array ( Partition Problem ) | Set 2 | CPP program to print equal sum sets of array . ; Function to print equal sum sets of array . ; Finding sum of array elements ; Check sum is even or odd . If odd then array cannot be partitioned . Print - 1 and return . ; Divide sum by 2 to find sum of two possible subsets . ; Boolean DP table to store result of states . dp [ i ] [ j ] = true if there is a subset of elements in first i elements of array that has sum equal to j . ; If number of elements are zero , then no sum can be obtained . ; Sum 0 can be obtained by not selecting any element . ; Fill the DP table in bottom up manner . ; Excluding current element . ; Including current element ; Required sets set1 and set2 . ; If partition is not possible print - 1 and return . ; Start from last element in dp table . ; If current element does not contribute to k , then it belongs to set 2. ; If current element contribute to k then it belongs to set 1. ; Print elements of both the sets . ; Driver program . | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printEqualSumSets ( int arr [ ] , int n ) { int i , currSum ; int sum = accumulate ( arr , arr + n , 0 ) ; if ( sum & 1 ) { cout << " - 1" ; return ; } int k = sum >> 1 ; bool dp [ n + 1 ] [ k + 1 ] ; for ( i = 1 ; i <= k ; i ++ ) dp [ 0 ] [ i ] = false ; for ( i = 0 ; i <= n ; i ++ ) dp [ i ] [ 0 ] = true ; for ( i = 1 ; i <= n ; i ++ ) { for ( currSum = 1 ; currSum <= k ; currSum ++ ) { dp [ i ] [ currSum ] = dp [ i - 1 ] [ currSum ] ; if ( arr [ i - 1 ] <= currSum ) dp [ i ] [ currSum ] = dp [ i ] [ currSum ] | dp [ i - 1 ] [ currSum - arr [ i - 1 ] ] ; } } vector < int > set1 , set2 ; if ( ! dp [ n ] [ k ] ) { cout << " - 1 STRNEWLINE " ; return ; } i = n ; currSum = k ; while ( i > 0 && currSum >= 0 ) { if ( dp [ i - 1 ] [ currSum ] ) { i -- ; set2 . push_back ( arr [ i ] ) ; } else if ( dp [ i - 1 ] [ currSum - arr [ i - 1 ] ] ) { i -- ; currSum -= arr [ i ] ; set1 . push_back ( arr [ i ] ) ; } } cout << " Set β 1 β elements : β " ; for ( i = 0 ; i < set1 . size ( ) ; i ++ ) cout << set1 [ i ] << " β " ; cout << " Set 2 elements : " for ( i = 0 ; i < set2 . size ( ) ; i ++ ) cout << set2 [ i ] << " β " ; } int main ( ) { int arr [ ] = { 5 , 5 , 1 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printEqualSumSets ( arr , n ) ; return 0 ; } |
Maximum average sum partition of an array | CPP program for maximum average sum partition ; storing prefix sums ; for each i to n storing averages ; Driver code ; int K = 3 ; atmost partitioning size | #include <bits/stdc++.h> NEW_LINE using namespace std ; double largestSumOfAverages ( vector < int > & A , int K ) { int n = A . size ( ) ; double pre_sum [ n + 1 ] ; pre_sum [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) pre_sum [ i + 1 ] = pre_sum [ i ] + A [ i ] ; double dp [ n ] = { 0 } ; double sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) dp [ i ] = ( pre_sum [ n ] - pre_sum [ i ] ) / ( n - i ) ; for ( int k = 0 ; k < K - 1 ; k ++ ) for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) dp [ i ] = max ( dp [ i ] , ( pre_sum [ j ] - pre_sum [ i ] ) / ( j - i ) + dp [ j ] ) ; return dp [ 0 ] ; } int main ( ) { vector < int > A = { 9 , 1 , 2 , 3 , 9 } ; cout << largestSumOfAverages ( A , K ) << endl ; return 0 ; } |
Find maximum sum array of length less than or equal to m | A Dynamic Programming based C ++ program to find maximum sum of array of size less than or equal to m from given n arrays ; N and M to define sizes of arr , dp , current_arr and maxSum ; INF to define min value ; Function to find maximum sum ; dp array of size N x M ; current_arr of size M ; maxsum of size M ; if we have 0 elements from 0 th array ; compute the cumulative sum array ; calculating the maximum contiguous array for every length j , j is from 1 to lengtn of the array ; every state is depending on its previous state ; computation of dp table similar approach as knapsack problem ; now we have done processing with the last array lets find out what is the maximum sum possible ; Driver program ; first element of each row is the size of that row | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 105 NEW_LINE #define M 1001 NEW_LINE #define INF -1111111111 NEW_LINE int maxSum ( int arr [ ] [ N ] ) { int dp [ N ] [ M ] ; int current_arr [ M ] ; int maxsum [ M ] ; memset ( dp , -1 , sizeof ( dp [ 0 ] [ 0 ] ) * N * M ) ; current_arr [ 0 ] = 0 ; dp [ 0 ] [ 0 ] = 0 ; for ( int i = 1 ; i <= 5 ; i ++ ) { int len = arr [ i - 1 ] [ 0 ] ; for ( int j = 1 ; j <= len ; j ++ ) { current_arr [ j ] = arr [ i - 1 ] [ j ] ; current_arr [ j ] += current_arr [ j - 1 ] ; maxsum [ j ] = INF ; } for ( int j = 1 ; j <= len && j <= 6 ; j ++ ) for ( int k = 1 ; k <= len ; k ++ ) if ( j + k - 1 <= len ) maxsum [ j ] = max ( maxsum [ j ] , current_arr [ j + k - 1 ] - current_arr [ k - 1 ] ) ; for ( int j = 0 ; j <= 6 ; j ++ ) dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; for ( int j = 1 ; j <= 6 ; j ++ ) for ( int cur = 1 ; cur <= j && cur <= len ; cur ++ ) dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - cur ] + maxsum [ cur ] ) ; } int ans = 0 ; for ( int i = 0 ; i <= 6 ; i ++ ) ans = max ( ans , dp [ 5 ] [ i ] ) ; return ans ; } int main ( ) { int arr [ ] [ N ] = { { 3 , 2 , 3 , 5 } , { 2 , 7 , -1 } , { 2 , 8 , 10 } , { 4 , 5 , 2 , 6 , 1 } , { 3 , 2 , 3 , -2 } } ; cout << " Maximum β sum β can β be β obtained β " << " is β : β " << maxSum ( arr ) << " STRNEWLINE " ; } |
Maximize array elements upto given number | C ++ program to find maximum value of number obtained by using array elements by using dynamic programming . ; Function to find maximum possible value of number that can be obtained using array elements . ; Variable to represent current index . ; Variable to show value between 0 and maxLimit . ; Table to store whether a value can be obtained or not upto a certain index . 1. dp [ i ] [ j ] = 1 if value j can be obtained upto index i . 2. dp [ i ] [ j ] = 0 if value j cannot be obtained upto index i . ; Check for index 0 if given value val can be obtained by either adding to or subtracting arr [ 0 ] from num . ; 1. If arr [ ind ] is added to obtain given val then val - arr [ ind ] should be obtainable from index ind - 1. 2. If arr [ ind ] is subtracted to obtain given val then val + arr [ ind ] should be obtainable from index ind - 1. Check for both the conditions . ; If either of one condition is true , then val is obtainable at index ind . ; Find maximum value that is obtained at index n - 1. ; If no solution exists return - 1. ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxVal ( int arr [ ] , int n , int num , int maxLimit ) { int ind ; int val ; int dp [ n ] [ maxLimit + 1 ] ; for ( ind = 0 ; ind < n ; ind ++ ) { for ( val = 0 ; val <= maxLimit ; val ++ ) { if ( ind == 0 ) { if ( num - arr [ ind ] == val num + arr [ ind ] == val ) { dp [ ind ] [ val ] = 1 ; } else { dp [ ind ] [ val ] = 0 ; } } else { if ( val - arr [ ind ] >= 0 && val + arr [ ind ] <= maxLimit ) { dp [ ind ] [ val ] = dp [ ind - 1 ] [ val - arr [ ind ] ] || dp [ ind - 1 ] [ val + arr [ ind ] ] ; } else if ( val - arr [ ind ] >= 0 ) { dp [ ind ] [ val ] = dp [ ind - 1 ] [ val - arr [ ind ] ] ; } else if ( val + arr [ ind ] <= maxLimit ) { dp [ ind ] [ val ] = dp [ ind - 1 ] [ val + arr [ ind ] ] ; } else { dp [ ind ] [ val ] = 0 ; } } } } for ( val = maxLimit ; val >= 0 ; val -- ) { if ( dp [ n - 1 ] [ val ] ) { return val ; } } return -1 ; } int main ( ) { int num = 1 ; int arr [ ] = { 3 , 10 , 6 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int maxLimit = 15 ; cout << findMaxVal ( arr , n , num , maxLimit ) ; return 0 ; } |
Moser | CPP code to generate first ' n ' terms of the Moser - de Bruijn Sequence ; Function to generate nth term of Moser - de Bruijn Sequence ; S ( 0 ) = 0 ; S ( 1 ) = 1 ; S ( 2 * n ) = 4 * S ( n ) ; S ( 2 * n + 1 ) = 4 * S ( n ) + 1 ; Generating the first ' n ' terms of Moser - de Bruijn Sequence ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gen ( int n ) { if ( n == 0 ) return 0 ; else if ( n == 1 ) return 1 ; else if ( n % 2 == 0 ) return 4 * gen ( n / 2 ) ; else if ( n % 2 == 1 ) return 4 * gen ( n / 2 ) + 1 ; } void moserDeBruijn ( int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << gen ( i ) << " β " ; cout << " STRNEWLINE " ; } int main ( ) { int n = 15 ; cout << " First β " << n << " β terms β of β " << " Moser - de β Bruijn β Sequence β : β STRNEWLINE " ; moserDeBruijn ( n ) ; return 0 ; } |
Minimum Sum Path in a Triangle | C ++ program for Dynamic Programming implementation of Min Sum Path in a Triangle ; Util function to find minimum sum for a path ; For storing the result in a 1 - D array , and simultaneously updating the result . ; For the bottom row ; Calculation of the remaining rows , in bottom up manner . ; return the top element ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSumPath ( vector < vector < int > > & A ) { int memo [ A . size ( ) ] ; int n = A . size ( ) - 1 ; for ( int i = 0 ; i < A [ n ] . size ( ) ; i ++ ) memo [ i ] = A [ n ] [ i ] ; for ( int i = A . size ( ) - 2 ; i >= 0 ; i -- ) for ( int j = 0 ; j < A [ i ] . size ( ) ; j ++ ) memo [ j ] = A [ i ] [ j ] + min ( memo [ j ] , memo [ j + 1 ] ) ; return memo [ 0 ] ; } int main ( ) { vector < vector < int > > A { { 2 } , { 3 , 9 } , { 1 , 6 , 7 } } ; cout << minSumPath ( A ) ; return 0 ; } |
Check if any valid sequence is divisible by M | ; Base case ; check if sum is divisible by M ; 1. Try placing ' + ' ; 2. Try placing ' - ' | bool isPossible ( int index , int sum ) { if ( index == n ) { if ( ( sum % M ) == 0 ) return true ; return false ; } bool placeAdd = isPossible ( index + 1 , sum + arr [ index ] ) ; bool placeMinus = isPossible ( index + 1 , sum - arr [ index ] ) ; if ( placeAdd placeMinus ) return true ; return false ; } |
Minimum removals from array to make max | CPP program to find minimum removals to make max - min <= K ; function to check all possible combinations of removal and return the minimum one ; base case when all elements are removed ; if condition is satisfied , no more removals are required ; if the state has already been visited ; when Amax - Amin > d ; minimum is taken of the removal of minimum element or removal of the maximum element ; To sort the array and return the answer ; sort the array ; fill all stated with - 1 when only one element ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE int dp [ MAX ] [ MAX ] ; int countRemovals ( int a [ ] , int i , int j , int k ) { if ( i >= j ) return 0 ; else if ( ( a [ j ] - a [ i ] ) <= k ) return 0 ; else if ( dp [ i ] [ j ] != -1 ) return dp [ i ] [ j ] ; else if ( ( a [ j ] - a [ i ] ) > k ) { dp [ i ] [ j ] = 1 + min ( countRemovals ( a , i + 1 , j , k ) , countRemovals ( a , i , j - 1 , k ) ) ; } return dp [ i ] [ j ] ; } int removals ( int a [ ] , int n , int k ) { sort ( a , a + n ) ; memset ( dp , -1 , sizeof ( dp ) ) ; if ( n == 1 ) return 0 ; else return countRemovals ( a , 0 , n - 1 , k ) ; } int main ( ) { int a [ ] = { 1 , 3 , 4 , 9 , 10 , 11 , 12 , 17 , 20 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 4 ; cout << removals ( a , n , k ) ; return 0 ; } |
Minimum removals from array to make max | C ++ program for the above approach ; Function to find rightmost index which satisfies the condition arr [ j ] - arr [ i ] <= k ; Initialising start to i + 1 ; Initialising end to n - 1 ; Binary search implementation to find the rightmost element that satisfy the condition ; Check if the condition satisfies ; Store the position ; Make start = mid + 1 ; Make end = mid ; Return the rightmost position ; Function to calculate minimum number of elements to be removed ; Sort the given array ; Iterate from 0 to n - 1 ; Find j such that arr [ j ] - arr [ i ] <= k ; If there exist such j that satisfies the condition ; Number of elements to be removed for this particular case is ( j - i + 1 ) ; Return answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findInd ( int key , int i , int n , int k , int arr [ ] ) { int start , end , mid , ind = -1 ; start = i + 1 ; end = n - 1 ; while ( start < end ) { mid = start + ( end - start ) / 2 ; if ( arr [ mid ] - key <= k ) { ind = mid ; start = mid + 1 ; } else { end = mid ; } } return ind ; } int removals ( int arr [ ] , int n , int k ) { int i , j , ans = n - 1 ; sort ( arr , arr + n ) ; for ( i = 0 ; i < n ; i ++ ) { j = findInd ( arr [ i ] , i , n , k , arr ) ; if ( j != -1 ) { ans = min ( ans , n - ( j - i + 1 ) ) ; } } return ans ; } int main ( ) { int a [ ] = { 1 , 3 , 4 , 9 , 10 , 11 , 12 , 17 , 20 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 4 ; cout << removals ( a , n , k ) ; return 0 ; } |
Number of ordered pairs such that ( Ai & Aj ) = 0 | CPP program to calculate the number of ordered pairs such that their bitwise and is zero ; Naive function to count the number of ordered pairs such that their bitwise and is 0 ; check for all possible pairs ; add 2 as ( i , j ) and ( j , i ) are considered different ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int a [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) if ( ( a [ i ] & a [ j ] ) == 0 ) count += 2 ; } return count ; } int main ( ) { int a [ ] = { 3 , 4 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countPairs ( a , n ) ; return 0 ; } |
Number of ordered pairs such that ( Ai & Aj ) = 0 | CPP program to calculate the number of ordered pairs such that their bitwise and is zero ; efficient function to count pairs ; stores the frequency of each number ; count the frequency of every element ; iterate for al possible values that a [ i ] can be ; if the last bit is ON ; else is the last bit is OFF ; iterate till n ; if mask 's ith bit is set ; else if mask 's ith bit is not set ; iterate for all the array element and count the number of pairs ; return answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 15 ; long long countPairs ( int a [ ] , int n ) { unordered_map < int , int > hash ; long long dp [ 1 << N ] [ N + 1 ] ; for ( int i = 0 ; i < n ; ++ i ) hash [ a [ i ] ] += 1 ; for ( long long mask = 0 ; mask < ( 1 << N ) ; ++ mask ) { if ( mask & 1 ) dp [ mask ] [ 0 ] = hash [ mask ] + hash [ mask ^ 1 ] ; dp [ mask ] [ 0 ] = hash [ mask ] ; for ( int i = 1 ; i <= N ; ++ i ) { if ( mask & ( 1 << i ) ) { dp [ mask ] [ i ] = dp [ mask ] [ i - 1 ] + dp [ mask ^ ( 1 << i ) ] [ i - 1 ] ; } dp [ mask ] [ i ] = dp [ mask ] [ i - 1 ] ; } } long long ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans += dp [ ( ( 1 << N ) - 1 ) ^ a [ i ] ] [ N ] ; return ans ; } int main ( ) { int a [ ] = { 5 , 4 , 1 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countPairs ( a , n ) ; return 0 ; } |
Minimum sum of multiplications of n numbers | CPP program to find the minimum sum of multiplication of n numbers ; Used in recursive memoized solution ; function to calculate the cumulative sum from a [ i ] to a [ j ] ; base case ; memoization , if the partition has been called before then return the stored value ; store a max value ; we break them into k partitions ; store the min of the formula thus obtained ; return the minimum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long dp [ 1000 ] [ 1000 ] ; long long sum ( int a [ ] , int i , int j ) { long long ans = 0 ; for ( int m = i ; m <= j ; m ++ ) ans = ( ans + a [ m ] ) % 100 ; return ans ; } long long solve ( int a [ ] , int i , int j ) { if ( i == j ) return 0 ; if ( dp [ i ] [ j ] != -1 ) return dp [ i ] [ j ] ; dp [ i ] [ j ] = INT_MAX ; for ( int k = i ; k < j ; k ++ ) { dp [ i ] [ j ] = min ( dp [ i ] [ j ] , ( solve ( a , i , k ) + solve ( a , k + 1 , j ) + ( sum ( a , i , k ) * sum ( a , k + 1 , j ) ) ) ) ; } return dp [ i ] [ j ] ; } void initialize ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= n ; j ++ ) dp [ i ] [ j ] = -1 ; } int main ( ) { int a [ ] = { 40 , 60 , 20 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; initialize ( n ) ; cout << solve ( a , 0 , n - 1 ) << endl ; return 0 ; } |
Print Fibonacci Series in reverse order | CPP Program to print Fibonacci series in reverse order ; assigning first and second elements ; storing sum in the preceding location ; printing array in reverse order ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void reverseFibonacci ( int n ) { int a [ n ] ; a [ 0 ] = 0 ; a [ 1 ] = 1 ; for ( int i = 2 ; i < n ; i ++ ) { a [ i ] = a [ i - 2 ] + a [ i - 1 ] ; } for ( int i = n - 1 ; i >= 0 ; i -- ) { cout << a [ i ] << " β " ; } } int main ( ) { int n = 5 ; reverseFibonacci ( n ) ; return 0 ; } |
Check if it is possible to transform one string to another | cpp program to check if a string can be converted to another string by performing operations ; function to check if a string can be converted to another string by performing following operations ; calculates length ; mark 1 st position as true ; traverse for all DPi , j ; if possible for to convert i characters of s1 to j characters of s2 ; if upper_case ( s1 [ i ] ) == s2 [ j ] is same ; if not upper then deletion is possible ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string s1 , string s2 ) { int n = s1 . length ( ) ; int m = s2 . length ( ) ; bool dp [ n + 1 ] [ m + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= m ; j ++ ) { dp [ i ] [ j ] = false ; } } dp [ 0 ] [ 0 ] = true ; for ( int i = 0 ; i < s1 . length ( ) ; i ++ ) { for ( int j = 0 ; j <= s2 . length ( ) ; j ++ ) { if ( dp [ i ] [ j ] ) { if ( j < s2 . length ( ) && ( toupper ( s1 [ i ] ) == s2 [ j ] ) ) dp [ i + 1 ] [ j + 1 ] = true ; if ( ! isupper ( s1 [ i ] ) ) dp [ i + 1 ] [ j ] = true ; } } } return ( dp [ n ] [ m ] ) ; } int main ( ) { string s1 = " daBcd " ; string s2 = " ABC " ; if ( check ( s1 , s2 ) ) cout << " YES " ; else cout << " NO " ; return 0 ; } |
Probability of reaching a point with 2 or 3 steps at a time | CPP Program to find probability to reach N with P probability to take 2 steps ( 1 - P ) to take 3 steps ; Returns probability to reach N ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float find_prob ( int N , float P ) { double dp [ N + 1 ] ; dp [ 0 ] = 1 ; dp [ 1 ] = 0 ; dp [ 2 ] = P ; dp [ 3 ] = 1 - P ; for ( int i = 4 ; i <= N ; ++ i ) dp [ i ] = ( P ) * dp [ i - 2 ] + ( 1 - P ) * dp [ i - 3 ] ; return dp [ N ] ; } int main ( ) { int n = 5 ; float p = 0.2 ; cout << find_prob ( n , p ) ; return 0 ; } |
Minimum number of deletions to make a string palindrome | Set 2 | CPP program to find minimum deletions to make palindrome . ; Find reverse of input string ; Create a DP table for storing edit distance of string and reverse . ; Find edit distance between input and revInput considering only delete operation . ; Go from bottom left to top right and find the minimum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getLevenstein ( string const & input ) { string revInput ( input . rbegin ( ) , input . rend ( ) ) ; int n = input . size ( ) ; vector < vector < int > > dp ( n + 1 , vector < int > ( n + 1 , -1 ) ) ; for ( int i = 0 ; i <= n ; ++ i ) { dp [ 0 ] [ i ] = i ; dp [ i ] [ 0 ] = i ; } for ( int i = 1 ; i <= n ; ++ i ) { for ( int j = 1 ; j <= n ; ++ j ) { if ( input [ i - 1 ] == revInput [ j - 1 ] ) dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = 1 + min ( { dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] } ) ; } } int res = numeric_limits < int > :: max ( ) ; for ( int i = n , j = 0 ; i >= 0 ; -- i , ++ j ) { res = min ( res , dp [ i ] [ j ] ) ; if ( i < n ) res = min ( res , dp [ i + 1 ] [ j ] ) ; if ( i > 0 ) res = min ( res , dp [ i - 1 ] [ j ] ) ; } return res ; } int main ( ) { string input ( " myfirstgeekarticle " ) ; cout << getLevenstein ( input ) ; return 0 ; } |
Number of ways to form a heap with n distinct integers | CPP program to count max heaps with n distinct keys ; dp [ i ] = number of max heaps for i distinct integers ; nck [ i ] [ j ] = number of ways to choose j elements form i elements , no order ; log2 [ i ] = floor of logarithm of base 2 of i ; to calculate nCk ; calculate l for give value of n ; number of elements that are actually present in last level ( hth level ) ( 2 ^ h - 1 ) ; if more than half - filled ; return ( 1 << h ) - 1 ; ( 2 ^ h ) - 1 ; find maximum number of heaps for n ; function to initialize arrays ; for each power of two find logarithm ; driver function | #include <iostream> NEW_LINE using namespace std ; int dp [ MAXN ] ; int nck [ MAXN ] [ MAXN ] ; int log2 [ MAXN ] ; int choose ( int n , int k ) { if ( k > n ) return 0 ; if ( n <= 1 ) return 1 ; if ( k == 0 ) return 1 ; if ( nck [ n ] [ k ] != -1 ) return nck [ n ] [ k ] ; int answer = choose ( n - 1 , k - 1 ) + choose ( n - 1 , k ) ; nck [ n ] [ k ] = answer ; return answer ; } int getLeft ( int n ) { if ( n == 1 ) return 0 ; int h = log2 [ n ] ; int last = n - ( ( 1 << h ) - 1 ) ; if ( last >= ( numh / 2 ) ) else return ( 1 << h ) - 1 - ( ( numh / 2 ) - last ) ; } int numberOfHeaps ( int n ) { if ( n <= 1 ) return 1 ; if ( dp [ n ] != -1 ) return dp [ n ] ; int left = getLeft ( n ) ; int ans = ( choose ( n - 1 , left ) * numberOfHeaps ( left ) ) * ( numberOfHeaps ( n - 1 - left ) ) ; dp [ n ] = ans ; return ans ; } int solve ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) dp [ i ] = -1 ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= n ; j ++ ) nck [ i ] [ j ] = -1 ; int currLog2 = -1 ; int currPower2 = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( currPower2 == i ) { currLog2 ++ ; currPower2 *= 2 ; } log2 [ i ] = currLog2 ; } return numberOfHeaps ( n ) ; } int main ( ) { int n = 10 ; cout << solve ( n ) << endl ; return 0 ; } |
Hosoya 's Triangle | CPP Program to print Hosoya 's triangle of height n. ; Print the Hosoya triangle of height n . ; base case . ; For each row . ; for each column ; ; recursive steps . ; printing the solution ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define N 5 NEW_LINE using namespace std ; void printHosoya ( int n ) { int dp [ N ] [ N ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = dp [ 1 ] [ 0 ] = dp [ 1 ] [ 1 ] = 1 ; for ( int i = 2 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i > j ) dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i - 2 ] [ j ] ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] + dp [ i - 2 ] [ j - 2 ] ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) cout << dp [ i ] [ j ] << " β " ; cout << endl ; } } int main ( ) { int n = 5 ; printHosoya ( n ) ; return 0 ; } |
Different ways to sum n using numbers greater than or equal to m | CPP Program to find number of ways to which numbers that are greater than given number can be added to get sum . ; Return number of ways to which numbers that are greater than given number can be added to get sum . ; Filling the table . k is for numbers greater than or equal that are allowed . ; i is for sum ; initializing dp [ i ] [ k ] to number ways to get sum using numbers greater than or equal k + 1 ; if i > k ; Driver Program | #include <bits/stdc++.h> NEW_LINE #define MAX 100 NEW_LINE using namespace std ; int numberofways ( int n , int m ) { int dp [ n + 2 ] [ n + 2 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ n + 1 ] = 1 ; for ( int k = n ; k >= m ; k -- ) { for ( int i = 0 ; i <= n ; i ++ ) { dp [ i ] [ k ] = dp [ i ] [ k + 1 ] ; if ( i - k >= 0 ) dp [ i ] [ k ] = ( dp [ i ] [ k ] + dp [ i - k ] [ k ] ) ; } } return dp [ n ] [ m ] ; } int main ( ) { int n = 3 , m = 1 ; cout << numberofways ( n , m ) << endl ; return 0 ; } |
Entringer Number | CPP Program to find Entringer Number E ( n , k ) ; Return Entringer Number E ( n , k ) ; Base Case ; Base Case ; Recursive step ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int zigzag ( int n , int k ) { if ( n == 0 && k == 0 ) return 1 ; if ( k == 0 ) return 0 ; return zigzag ( n , k - 1 ) + zigzag ( n - 1 , n - k ) ; } int main ( ) { int n = 4 , k = 3 ; cout << zigzag ( n , k ) << endl ; return 0 ; } |
Eulerian Number | CPP Program to find Eulerian number A ( n , m ) ; Return euleriannumber A ( n , m ) ; For each row from 1 to n ; For each column from 0 to m ; If i is greater than j ; If j is 0 , then make that state as 1. ; basic recurrence relation . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int eulerian ( int n , int m ) { int dp [ n + 1 ] [ m + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= m ; j ++ ) { if ( i > j ) { if ( j == 0 ) dp [ i ] [ j ] = 1 ; else dp [ i ] [ j ] = ( ( i - j ) * dp [ i - 1 ] [ j - 1 ] ) + ( ( j + 1 ) * dp [ i - 1 ] [ j ] ) ; } } } return dp [ n ] [ m ] ; } int main ( ) { int n = 3 , m = 1 ; cout << eulerian ( n , m ) << endl ; return 0 ; } |
Delannoy Number | CPP Program of finding nth Delannoy Number . ; Return the nth Delannoy Number . ; Base case ; Recursive step . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dealnnoy ( int n , int m ) { if ( m == 0 n == 0 ) return 1 ; return dealnnoy ( m - 1 , n ) + dealnnoy ( m - 1 , n - 1 ) + dealnnoy ( m , n - 1 ) ; } int main ( ) { int n = 3 , m = 4 ; cout << dealnnoy ( n , m ) << endl ; return 0 ; } |
Delannoy Number | CPP Program of finding nth Delannoy Number . ; Return the nth Delannoy Number . ; Base cases ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dealnnoy ( int n , int m ) { int dp [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) dp [ i ] [ 0 ] = 1 ; for ( int i = 0 ; i <= m ; i ++ ) dp [ 0 ] [ i ] = 1 ; for ( int i = 1 ; i <= m ; i ++ ) for ( int j = 1 ; j <= n ; j ++ ) dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j - 1 ] + dp [ i ] [ j - 1 ] ; return dp [ m ] [ n ] ; } int main ( ) { int n = 3 , m = 4 ; cout << dealnnoy ( n , m ) << endl ; return 0 ; } |
Longest alternating ( positive and negative ) subarray starting at every index | CPP program to find longest alternating subarray starting from every index . ; Fill count [ ] from end . ; Print result ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void longestAlternating ( int arr [ ] , int n ) { int count [ n ] ; count [ n - 1 ] = 1 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] * arr [ i + 1 ] < 0 ) count [ i ] = count [ i + 1 ] + 1 ; else count [ i ] = 1 ; } for ( int i = 0 ; i < n ; i ++ ) cout << count [ i ] << " β " ; } int main ( ) { int a [ ] = { -5 , -1 , -1 , 2 , -2 , -3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; longestAlternating ( a , n ) ; return 0 ; } |
Maximum value with the choice of either dividing or considering as it is | CPP program for maximize result when we have choice to divide or consider as it is . ; function for calculating max possible result ; Compute remaining values in bottom up manner . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDP ( int n ) { int res [ n + 1 ] ; res [ 0 ] = 0 ; res [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res [ i ] = max ( i , ( res [ i / 2 ] + res [ i / 3 ] + res [ i / 4 ] + res [ i / 5 ] ) ) ; return res [ n ] ; } int main ( ) { int n = 60 ; cout << " MaxSum β = " << maxDP ( n ) ; return 0 ; } |
Maximum difference of zeros and ones in binary string | CPP Program to find the length of substring with maximum difference of zeroes and ones in binary string . ; Return true if there all 1 s ; Checking each index is 0 or not . ; Find the length of substring with maximum difference of zeroes and ones in binary string ; If string is over . ; If the state is already calculated . ; Returns length of substring which is having maximum difference of number of 0 s and number of 1 s ; If all 1 s return - 1. ; Else find the length . ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define MAX 100 NEW_LINE using namespace std ; bool allones ( string s , int n ) { int co = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) co += ( s [ i ] == '1' ) ; return ( co == n ) ; } int findlength ( int arr [ ] , string s , int n , int ind , int st , int dp [ ] [ 3 ] ) { if ( ind >= n ) return 0 ; if ( dp [ ind ] [ st ] != -1 ) return dp [ ind ] [ st ] ; if ( st == 0 ) return dp [ ind ] [ st ] = max ( arr [ ind ] + findlength ( arr , s , n , ind + 1 , 1 , dp ) , findlength ( arr , s , n , ind + 1 , 0 , dp ) ) ; else return dp [ ind ] [ st ] = max ( arr [ ind ] + findlength ( arr , s , n , ind + 1 , 1 , dp ) , 0 ) ; } int maxLen ( string s , int n ) { if ( allones ( s , n ) ) return -1 ; int arr [ MAX ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = ( s [ i ] == '0' ? 1 : -1 ) ; int dp [ MAX ] [ 3 ] ; memset ( dp , -1 , sizeof dp ) ; return findlength ( arr , s , n , 0 , 0 , dp ) ; } int main ( ) { string s = "11000010001" ; int n = 11 ; cout << maxLen ( s , n ) << endl ; return 0 ; } |
Minimum jumps to reach last building in a matrix | Recursive CPP program to find minimum jumps to reach last building from first . ; Returns minimum jump path from ( 0 , 0 ) to ( m , n ) in height [ R ] [ C ] ; base case ; Find minimum jumps if we go through diagonal ; Find minimum jumps if we go through down ; Find minimum jumps if we go through right ; return minimum jumps ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; # define R 4 NEW_LINE # define C 3 NEW_LINE bool isSafe ( int x , int y ) { return ( x < R && y < C ) ; } int minJump ( int height [ R ] [ C ] , int x , int y ) { if ( x == R - 1 && y == C - 1 ) return 0 ; int diag = INT_MAX ; if ( isSafe ( x + 1 , y + 1 ) ) diag = minJump ( height , x + 1 , y + 1 ) + abs ( height [ x ] [ y ] - height [ x + 1 ] [ y + 1 ] ) ; int down = INT_MAX ; if ( isSafe ( x + 1 , y ) ) down = minJump ( height , x + 1 , y ) + abs ( height [ x ] [ y ] - height [ x + 1 ] [ y ] ) ; int right = INT_MAX ; if ( isSafe ( x , y + 1 ) ) right = minJump ( height , x , y + 1 ) + abs ( height [ x ] [ y ] - height [ x ] [ y + 1 ] ) ; return min ( { down , right , diag } ) ; } int main ( ) { int height [ ] [ C ] = { { 5 , 4 , 2 } , { 9 , 2 , 1 } , { 2 , 5 , 9 } , { 1 , 3 , 11 } } ; cout << minJump ( height , 0 , 0 ) ; return 0 ; } |
Maximum sum subsequence with at | CPP program to find maximum sum subsequence such that elements are at least k distance away . ; MS [ i ] is going to store maximum sum subsequence in subarray from arr [ i ] to arr [ n - 1 ] ; We fill MS from right to left . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int arr [ ] , int N , int k ) { int MS [ N ] ; MS [ N - 1 ] = arr [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( i + k + 1 >= N ) MS [ i ] = max ( arr [ i ] , MS [ i + 1 ] ) ; else MS [ i ] = max ( arr [ i ] + MS [ i + k + 1 ] , MS [ i + 1 ] ) ; } return MS [ 0 ] ; } int main ( ) { int N = 10 , k = 2 ; int arr [ ] = { 50 , 70 , 40 , 50 , 90 , 70 , 60 , 40 , 70 , 50 } ; cout << maxSum ( arr , N , k ) ; return 0 ; } |
Length of Longest Balanced Subsequence | C ++ program to find length of the longest balanced subsequence ; Variable to count all the open brace that does not have the corresponding closing brace . ; To count all the close brace that does not have the corresponding open brace . ; Iterating over the String ; Number of open braces that hasn 't been closed yet. ; Number of close braces that cannot be mapped to any open brace . ; Mapping the ith close brace to one of the open brace . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLength ( char s [ ] , int n ) { int invalidOpenBraces = 0 ; int invalidCloseBraces = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ( ' ) { invalidOpenBraces ++ ; } else { if ( invalidOpenBraces == 0 ) { invalidCloseBraces ++ ; } else { invalidOpenBraces -- ; } } } return ( n - ( invalidOpenBraces + invalidCloseBraces ) ) ; } int main ( ) { char s [ ] = " ( ) ( ( ( ( ( ( ) " ; int n = strlen ( s ) ; cout << maxLength ( s , n ) << endl ; return 0 ; } |
Longest alternating sub | C ++ program to calculate longest alternating sub - array for each index elements ; Function to calculate alternating sub - array for each index of array elements ; Initialize the base state of len [ ] ; Calculating value for each element ; If both elements are different then add 1 to next len [ i + 1 ] ; else initialize to 1 ; Print lengths of binary subarrays . ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void alternateSubarray ( bool arr [ ] , int n ) { int len [ n ] ; len [ n - 1 ] = 1 ; for ( int i = n - 2 ; i >= 0 ; -- i ) { if ( arr [ i ] ^ arr [ i + 1 ] == 1 ) len [ i ] = len [ i + 1 ] + 1 ; else len [ i ] = 1 ; } for ( int i = 0 ; i < n ; ++ i ) cout << len [ i ] << " β " ; } int main ( ) { bool arr [ ] = { 1 , 0 , 1 , 0 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; alternateSubarray ( arr , n ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.