text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Absolute difference between sum and product of roots of a quartic equation | C ++ implementation of above approach ; Function taking coefficient of each term of equation as input ; Finding sum of roots ; Finding product of roots ; Absolute difference ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double sumProductDifference ( int a , int b , int c , int d , int e ) { double rootSum = ( double ) ( -1 * b ) / a ; double rootProduct = ( double ) e / a ; return abs ( rootSum - rootProduct ) ; } int main ( ) { cout << sumProductDifference ( 8 , 4 , 6 , 4 , 1 ) ; return 0 ; }
Number of solutions of n = x + n Γ’Ε  β€’ x | C ++ implementation of above approach ; Function to find the number of solutions of n = n xor x ; Counter to store the number of solutions found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfSolutions ( int n ) { int c = 0 ; for ( int x = 0 ; x <= n ; ++ x ) if ( n == x + n ^ x ) ++ c ; return c ; } int main ( ) { int n = 3 ; cout << numberOfSolutions ( n ) ; return 0 ; }
Program to find minimum number of lectures to attend to maintain 75 % | C ++ Program to find minimum number of lectures to attend to maintain 75 % attendance ; Function to compute minimum lecture ; Formula to compute ; Driver function
#include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int minimumLectures ( int m , int n ) { int ans = 0 ; if ( n < ( int ) ceil ( 0.75 * m ) ) ans = ( int ) ceil ( ( ( 0.75 * m ) - n ) / 0.25 ) ; else ans = 0 ; return ans ; } int main ( ) { int M = 9 , N = 1 ; cout << minimumLectures ( M , N ) ; return 0 ; }
Count Numbers with N digits which consists of odd number of 0 's | C ++ program to count numbers with N digits which consists of odd number of 0 's ; Function to count Numbers with N digits which consists of odd number of 0 's ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countNumbers ( int N ) { return ( pow ( 10 , N ) - pow ( 8 , N ) ) / 2 ; } int main ( ) { int n = 5 ; cout << countNumbers ( n ) << endl ; return 0 ; }
Sum of all Primes in a given range using Sieve of Eratosthenes | CPP program to find sum of primes in range L to R ; prefix [ i ] is going to store sum of primes till i ( including i ) . ; Function to build the prefix sum array ; Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Build prefix array ; Function to return sum of prime in range ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 10000 ; int prefix [ MAX + 1 ] ; void buildPrefix ( ) { bool prime [ MAX + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } prefix [ 0 ] = prefix [ 1 ] = 0 ; for ( int p = 2 ; p <= MAX ; p ++ ) { prefix [ p ] = prefix [ p - 1 ] ; if ( prime [ p ] ) prefix [ p ] += p ; } } int sumPrimeRange ( int L , int R ) { buildPrefix ( ) ; return prefix [ R ] - prefix [ L - 1 ] ; } int main ( ) { int L = 10 , R = 20 ; cout << sumPrimeRange ( L , R ) << endl ; return 0 ; }
Sum of the first N terms of the series 5 , 12 , 23 , 38. ... | C ++ program to find sum of first n terms ; Function to calculate the sum ; Driver code ; number of terms to be included in sum ; find the Sn
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateSum ( int n ) { return 2 * ( n * ( n + 1 ) * ( 2 * n + 1 ) / 6 ) + n * ( n + 1 ) / 2 + 2 * ( n ) ; } int main ( ) { int n = 3 ; cout << " Sum ▁ = ▁ " << calculateSum ( n ) ; return 0 ; }
Program to find number of solutions in Quadratic Equation | C ++ Program to find the solutions of specified equations ; Method to check for solutions of equations ; If the expression is greater than 0 , then 2 solutions ; If the expression is equal 0 , then 2 solutions ; Else no solutions ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void checkSolution ( int a , int b , int c ) { if ( ( ( b * b ) - ( 4 * a * c ) ) > 0 ) cout << "2 ▁ solutions " ; else if ( ( ( b * b ) - ( 4 * a * c ) ) == 0 ) cout << "1 ▁ solution " ; else cout << " No ▁ solutions " ; } int main ( ) { int a = 2 , b = 5 , c = 2 ; checkSolution ( a , b , c ) ; return 0 ; }
Program to convert KiloBytes to Bytes and Bits | C ++ implementation of above program ; Function to calculates the bits ; calculates Bits 1 kilobytes ( s ) = 8192 bits ; Function to calculates the bytes ; calculates Bytes 1 KB = 1024 bytes ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long Bits ( int kilobytes ) { long Bits = 0 ; Bits = kilobytes * 8192 ; return Bits ; } long Bytes ( int kilobytes ) { long Bytes = 0 ; Bytes = kilobytes * 1024 ; return Bytes ; } int main ( ) { int kilobytes = 1 ; cout << kilobytes << " ▁ Kilobytes ▁ = ▁ " << Bytes ( kilobytes ) << " ▁ Bytes ▁ and ▁ " << Bits ( kilobytes ) << " ▁ Bits . " ; return 0 ; }
Program to find the Hidden Number | C ++ Program to find the hidden number ; Driver Code ; Getting the size of array ; Getting the array of size n ; Solution ; Finding sum of the array elements ; Dividing sum by size n ; Print x , if found
#include <iostream> NEW_LINE using namespace std ; int main ( ) { int n = 3 ; int a [ ] = { 1 , 2 , 3 } ; int i = 0 ; long sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; } long x = sum / n ; if ( x * n == sum ) cout << x << endl ; else cout << ( " - 1" ) << endl ; return 0 ; }
Find sum of the series ? 3 + ? 12 + ... ... ... upto N terms | C ++ implementation of above approach ; Function to find the sum ; Apply AP formula ; Driver code ; number of terms
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; double findSum ( ll n ) { return sqrt ( 3 ) * ( n * ( n + 1 ) / 2 ) ; } int main ( ) { ll n = 10 ; cout << findSum ( n ) << endl ; return 0 ; }
Find the sum of the series x ( x + y ) + x ^ 2 ( x ^ 2 + y ^ 2 ) + x ^ 3 ( x ^ 3 + y ^ 3 ) + ... + x ^ n ( x ^ n + y ^ n ) | CPP program to find the sum of series ; Function to return required sum ; sum of first series ; sum of second series ; Driver Code ; function call to print sum
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int x , int y , int n ) { int sum1 = ( pow ( x , 2 ) * ( pow ( x , 2 * n ) - 1 ) ) / ( pow ( x , 2 ) - 1 ) ; int sum2 = ( x * y * ( pow ( x , n ) * pow ( y , n ) - 1 ) ) / ( x * y - 1 ) ; return sum1 + sum2 ; } int main ( ) { int x = 2 , y = 2 , n = 2 ; cout << sum ( x , y , n ) ; return 0 ; }
Find any pair with given GCD and LCM | C ++ program to print any pair with a given gcd G and lcm L ; Function to print the pairs ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void printPair ( int g , int l ) { cout << g << " ▁ " << l ; } int main ( ) { int g = 3 , l = 12 ; printPair ( g , l ) ; return 0 ; }
Sum of first n terms of a given series 3 , 6 , 11 , ... . . | C ++ program to find sum of first n terms ; Function to calculate the sum ; starting number ; Common Ratio ; Common difference ; Driver code ; N th term to be find ; find the Sn
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateSum ( int n ) { int a1 = 1 , a2 = 2 ; int r = 2 ; int d = 1 ; return ( n ) * ( 2 * a1 + ( n - 1 ) * d ) / 2 + a2 * ( pow ( r , n ) - 1 ) / ( r - 1 ) ; } int main ( ) { int n = 5 ; cout << " Sum ▁ = ▁ " << calculateSum ( n ) ; return 0 ; }
Maximum of sum and product of digits until number is reduced to a single digit | CPP implementation of above approach ; Function to sum the digits until it becomes a single digit ; Function to product the digits until it becomes a single digit ; Loop to do sum while sum is not less than or equal to 9 ; Function to find the maximum among repeated sum and repeated product ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long repeatedSum ( long n ) { if ( n == 0 ) return 0 ; return ( n % 9 == 0 ) ? 9 : ( n % 9 ) ; } long repeatedProduct ( long n ) { long prod = 1 ; while ( n > 0 prod > 9 ) { if ( n == 0 ) { n = prod ; prod = 1 ; } prod *= n % 10 ; n /= 10 ; } return prod ; } long maxSumProduct ( long N ) { if ( N < 10 ) return N ; return max ( repeatedSum ( N ) , repeatedProduct ( N ) ) ; } int main ( ) { long n = 631 ; cout << maxSumProduct ( n ) << endl ; return 0 ; }
Find maximum possible value of advertising | C ++ program for the above approach ; Function to find maximum possible advertising value ; To store advertising value at i - th minute ; Base Case ; If no advertisement is taken on ith minute ; If advertisement is taken on i - th minute ; Driver 's Code ; array [ ] [ 0 ] start time array [ ] [ 1 ] advertising value
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE int max_value ( int array [ ] [ 2 ] , int M , int K , int N ) { int time [ M ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { time [ array [ i ] [ 0 ] ] = array [ i ] [ 1 ] ; } int dp [ M ] [ 2 ] ; dp [ 0 ] [ 0 ] = 0 ; dp [ 0 ] [ 1 ] = time [ 0 ] ; for ( int i = 1 ; i < M ; i ++ ) { dp [ i ] [ 0 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) ; dp [ i ] [ 1 ] = time [ i ] ; if ( i - K >= 0 ) { dp [ i ] [ 1 ] += max ( dp [ i - K ] [ 0 ] , dp [ i - K ] [ 1 ] ) ; } } return max ( dp [ M - 1 ] [ 0 ] , dp [ M - 1 ] [ 1 ] ) ; } int main ( ) { int array [ ] [ 2 ] = { { 0 , 10 } , { 4 , 110 } , { 5 , 30 } } ; int N = 3 ; int K = 4 ; int M = 6 ; cout << max_value ( array , M , K , N ) ; }
Count numbers with exactly K non | C ++ program to Count the numbers having exactly K non - zero digits and sum of digits are odd and distinct . ; To store digits of N ; visited map ; DP Table ; Push all the digits of N into digits vector ; Function returns the count ; If desired number is formed whose sum is odd ; If it is not present in map , mark it as true and return 1 ; Sum is present in map already ; Desired result not found ; If that state is already calculated just return that state value ; Upper limit ; To store the count of desired numbers ; If k is non - zero , i ranges from 0 to j else [ 1 , j ] ; If current digit is 0 , decrement k and recurse sum is not changed as we are just adding 0 that makes no difference ; If i is non zero , then k remains unchanged and value is added to sum ; Memoize and return ; Driver code ; K is the number of exact non - zero elements to have in number ; break N into its digits ; We keep record of 0 s we need to place in the number
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > digits ; bool vis [ 170 ] = { false } ; int dp [ 19 ] [ 19 ] [ 2 ] [ 170 ] ; void ConvertIntoDigit ( int n ) { while ( n ) { int dig = n % 10 ; digits . push_back ( dig ) ; n /= 10 ; } reverse ( digits . begin ( ) , digits . end ( ) ) ; } int solve ( int idx , int k , int tight , int sum ) { if ( idx == digits . size ( ) && k == 0 && sum & 1 ) { if ( ! vis [ sum ] ) { vis [ sum ] = 1 ; return 1 ; } return 0 ; } if ( idx > digits . size ( ) ) { return 0 ; } if ( dp [ idx ] [ k ] [ tight ] [ sum ] ) { return dp [ idx ] [ k ] [ tight ] [ sum ] ; } int j ; if ( tight == 0 ) { j = digits [ idx ] ; } else { j = 9 ; } int cnt = 0 ; for ( int i = ( k ? 0 : 1 ) ; i <= j ; i ++ ) { int newtight = tight ; if ( i < j ) { newtight = 1 ; } if ( i == 0 ) cnt += solve ( idx + 1 , k - 1 , newtight , sum ) ; else cnt += solve ( idx + 1 , k , newtight , sum + i ) ; } return dp [ idx ] [ k ] [ tight ] [ sum ] = cnt ; } int main ( ) { int N , k ; N = 169 , k = 2 ; ConvertIntoDigit ( N ) ; k = digits . size ( ) - k ; cout << solve ( 0 , k , 0 , 0 ) ; }
Count of subsets of integers from 1 to N having no adjacent elements | C ++ Code to count subsets not containing adjacent elements from 1 to N ; Function to count subsets ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubsets ( int N ) { if ( N <= 2 ) return N ; if ( N == 3 ) return 2 ; int DP [ N + 1 ] = { 0 } ; DP [ 0 ] = 0 , DP [ 1 ] = 1 , DP [ 2 ] = 2 , DP [ 3 ] = 2 ; for ( int i = 4 ; i <= N ; i ++ ) { DP [ i ] = DP [ i - 2 ] + DP [ i - 3 ] ; } return DP [ N ] ; } int main ( ) { int N = 20 ; cout << countSubsets ( N ) ; return 0 ; }
Count the number of ordered sets not containing consecutive numbers | C ++ program to Count the number of ordered sets not containing consecutive numbers ; DP table ; Function to calculate the count of ordered set for a given size ; Base cases ; If subproblem has been soved before ; Store and return answer to this subproblem ; Function returns the count of all ordered sets ; Prestore the factorial value ; Initialise the dp table ; Iterate all ordered set sizes and find the count for each one maximum ordered set size will be smaller than N as all elements are distinct and non consecutive . ; Multiply ny size ! for all the arrangements because sets are ordered . ; Add to total answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 500 ] [ 500 ] ; int CountSets ( int x , int pos ) { if ( x <= 0 ) { if ( pos == 0 ) return 1 ; else return 0 ; } if ( pos == 0 ) return 1 ; if ( dp [ x ] [ pos ] != -1 ) return dp [ x ] [ pos ] ; int answer = CountSets ( x - 1 , pos ) + CountSets ( x - 2 , pos - 1 ) ; return dp [ x ] [ pos ] = answer ; } int CountOrderedSets ( int n ) { int factorial [ 10000 ] ; factorial [ 0 ] = 1 ; for ( int i = 1 ; i < 10000 ; i ++ ) factorial [ i ] = factorial [ i - 1 ] * i ; int answer = 0 ; memset ( dp , -1 , sizeof ( dp ) ) ; for ( int i = 1 ; i <= n ; i ++ ) { int sets = CountSets ( n , i ) * factorial [ i ] ; answer = answer + sets ; } return answer ; } int main ( ) { int N = 3 ; cout << CountOrderedSets ( N ) ; return 0 ; }
Count the Arithmetic sequences in the Array of size at least 3 | C ++ program to find all arithmetic sequences of size atleast 3 ; Function to find all arithmetic sequences of size atleast 3 ; If array size is less than 3 ; Finding arithmetic subarray length ; To store all arithmetic subarray of length at least 3 ; Check if current element makes arithmetic sequence with previous two elements ; Begin with a new element for new arithmetic sequences ; Accumulate result in till i . ; Return final count ; Driver code ; Function to find arithmetic sequences
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfArithmeticSequences ( int L [ ] , int N ) { if ( N <= 2 ) return 0 ; int count = 0 ; int res = 0 ; for ( int i = 2 ; i < N ; ++ i ) { if ( L [ i ] - L [ i - 1 ] == L [ i - 1 ] - L [ i - 2 ] ) { ++ count ; } else { count = 0 ; } res += count ; } return res ; } int main ( ) { int L [ ] = { 1 , 3 , 5 , 6 , 7 , 8 } ; int N = sizeof ( L ) / sizeof ( L [ 0 ] ) ; cout << numberOfArithmeticSequences ( L , N ) ; return 0 ; }
Count triplet of indices ( i , j , k ) such that XOR of elements between [ i , j ) equals [ j , k ] | C ++ program to count the Number of triplets in array having subarray XOR equal ; Function return the count of triplets having subarray XOR equal ; XOR value till i ; Count and ways array as defined above ; Using the formula stated ; Increase the frequency of x ; Add i + 1 to ways [ x ] for upcoming indices ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountOfTriplets ( int a [ ] , int n ) { int answer = 0 ; int x = 0 ; int count [ 100005 ] = { 0 } ; int ways [ 100005 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { x ^= a [ i ] ; answer += count [ x ] * i - ways [ x ] ; count [ x ] ++ ; ways [ x ] += ( i + 1 ) ; } return answer ; } int main ( ) { int Arr [ ] = { 3 , 6 , 12 , 8 , 6 , 2 , 1 , 5 } ; int N = sizeof ( Arr ) / sizeof ( Arr [ 0 ] ) ; cout << CountOfTriplets ( Arr , N ) ; return 0 ; }
Count of subarrays of an Array having all unique digits | C ++ program to find the count of subarrays of an Array having all unique digits ; Dynamic programming table ; Function to obtain the mask for any integer ; Function to count the number of ways ; Subarray must not be empty ; If subproblem has been solved ; Excluding this element in the subarray ; If there are no common digits then only this element can be included ; Calculate the new mask if this element is included ; Store and return the answer ; Function to find the count of subarray with all digits unique ; initializing dp ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 5000 ] [ ( 1 << 10 ) + 5 ] ; int getmask ( int val ) { int mask = 0 ; if ( val == 0 ) return 1 ; while ( val ) { int d = val % 10 ; mask |= ( 1 << d ) ; val /= 10 ; } return mask ; } int countWays ( int pos , int mask , int a [ ] , int n ) { if ( pos == n ) return ( mask > 0 ? 1 : 0 ) ; if ( dp [ pos ] [ mask ] != -1 ) return dp [ pos ] [ mask ] ; int count = 0 ; count = count + countWays ( pos + 1 , mask , a , n ) ; if ( ( getmask ( a [ pos ] ) & mask ) == 0 ) { int new_mask = ( mask | ( getmask ( a [ pos ] ) ) ) ; count = count + countWays ( pos + 1 , new_mask , a , n ) ; } return dp [ pos ] [ mask ] = count ; } int numberOfSubarrays ( int a [ ] , int n ) { memset ( dp , -1 , sizeof ( dp ) ) ; return countWays ( 0 , 0 , a , n ) ; } int main ( ) { int N = 4 ; int A [ ] = { 1 , 12 , 23 , 34 } ; cout << numberOfSubarrays ( A , N ) ; return 0 ; }
Count of Fibonacci paths in a Binary tree | C ++ program to count all of Fibonacci paths in a Binary tree ; Vector to store the fibonacci series ; Binary Tree Node ; Function to create a new tree node ; Function to find the height of the given tree ; Function to make fibonacci series upto n terms ; Preorder Utility function to count exponent path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is not a number of pow ( x , y ) ; Increment count when encounter leaf node ; Left recursive call save the value of count ; Right recursive call and return value of count ; Function to find whether fibonacci path exists or not ; To find the height ; Making fibonacci series upto ht terms ; Driver code ; Create binary tree ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > fib ; struct node { struct node * left ; int data ; struct node * right ; } ; node * newNode ( int data ) { node * temp = new node ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } int height ( node * root ) { int ht = 0 ; if ( root == NULL ) return 0 ; return ( max ( height ( root -> left ) , height ( root -> right ) ) + 1 ) ; } void FibonacciSeries ( int n ) { fib . push_back ( 0 ) ; fib . push_back ( 1 ) ; for ( int i = 2 ; i < n ; i ++ ) fib . push_back ( fib [ i - 1 ] + fib [ i - 2 ] ) ; } int CountPathUtil ( node * root , int i , int count ) { if ( root == NULL || ! ( fib [ i ] == root -> data ) ) { return count ; } if ( ! root -> left && ! root -> right ) { count ++ ; } count = CountPathUtil ( root -> left , i + 1 , count ) ; return CountPathUtil ( root -> right , i + 1 , count ) ; } void CountPath ( node * root ) { int ht = height ( root ) ; FibonacciSeries ( ht ) ; cout << CountPathUtil ( root , 0 , 0 ) ; } int main ( ) { node * root = newNode ( 0 ) ; root -> left = newNode ( 1 ) ; root -> right = newNode ( 1 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 4 ) ; root -> right -> right = newNode ( 1 ) ; root -> right -> right -> left = newNode ( 2 ) ; CountPath ( root ) ; return 0 ; }
Numbers with a Fibonacci difference between Sum of digits at even and odd positions in a given range | C ++ program to count the numbers in the range having the difference between the sum of digits at even and odd positions as a Fibonacci Number ; To store all the Fibonacci numbers ; Function to generate Fibonacci numbers upto 100 ; Adding the first two Fibonacci numbers in the set ; Computing the remaining Fibonacci numbers using the first two Fibonacci numbers ; Function to return the count of required numbers from 0 to num ; Base Case ; Check if the difference is equal to any fibonacci 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 ; Generate fibonacci numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 18 ; int a , b , dp [ M ] [ 90 ] [ 90 ] [ 2 ] ; set < int > fib ; void fibonacci ( ) { int prev = 0 , curr = 1 ; fib . insert ( prev ) ; fib . insert ( curr ) ; while ( curr <= 100 ) { int temp = curr + prev ; fib . insert ( temp ) ; prev = curr ; curr = temp ; } } 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 ; if ( fib . find ( d ) != fib . end ( ) ) 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 ( ) { fibonacci ( ) ; 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 ; }
Count maximum occurrence of subsequence in string such that indices in subsequence is in A . P . | C ++ implementation to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Function to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Frequency for characters ; Loop to count the occurrence of ith character before jth character in the given string ; Increase the frequency of s [ i ] or c of string ; Maximum occurrence of subsequence of length 1 in given string ; Maximum occurrence of subsequence of length 2 in given string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumOccurrence ( string s ) { int n = s . length ( ) ; int freq [ 26 ] = { 0 } ; int dp [ 26 ] [ 26 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int c = ( s [ i ] - ' a ' ) ; for ( int j = 0 ; j < 26 ; j ++ ) dp [ j ] += freq [ j ] ; freq ++ ; } int answer = INT_MIN ; for ( int i = 0 ; i < 26 ; i ++ ) answer = max ( answer , freq [ i ] ) ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) { answer = max ( answer , dp [ i ] [ j ] ) ; } } return answer ; } int main ( ) { string s = " xxxyy " ; cout << maximumOccurrence ( s ) ; return 0 ; }
Count the numbers with N digits and whose suffix is divisible by K | C ++ implementation to Count the numbers with N digits and whose suffix is divisible by K ; Suffix of length pos with remainder rem and Z representing whether the suffix has a non zero digit until now ; Base case ; If count of digits is less than n ; Placing all possible digits in remaining positions ; If remainder non zero and suffix has n digits ; If the subproblem is already solved ; Placing all digits at MSB of suffix and increasing it 's length by 1 ; Non zero digit is placed ; Store and return the solution to this subproblem ; Function to Count the numbers with N digits and whose suffix is divisible by K ; Since we need powers of 10 for counting , it 's better to pre store them along with their modulo with 1e9 + 7 for counting ; Since at each recursive step we increase the suffix length by 1 by placing digits at its leftmost position , we need powers of 10 modded with k , in order to fpos the new remainder efficiently ; Initialising dp table values - 1 represents subproblem hasn 't been solved yet ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int mod = 1000000007 ; int dp [ 1005 ] [ 105 ] [ 2 ] ; int powers [ 1005 ] ; int powersModk [ 1005 ] ; int calculate ( int pos , int rem , int z , int k , int n ) { if ( rem == 0 && z ) { if ( pos != n ) return ( powers [ n - pos - 1 ] * 9 ) % mod ; else return 1 ; } if ( pos == n ) return 0 ; if ( dp [ pos ] [ rem ] [ z ] != -1 ) return dp [ pos ] [ rem ] [ z ] ; int count = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) { if ( i == 0 ) count = ( count + ( calculate ( pos + 1 , ( rem + ( i * powersModk [ pos ] ) % k ) % k , z , k , n ) ) ) % mod ; else count = ( count + ( calculate ( pos + 1 , ( rem + ( i * powersModk [ pos ] ) % k ) % k , 1 , k , n ) ) ) % mod ; } return dp [ pos ] [ rem ] [ z ] = count ; } int countNumbers ( int n , int k ) { int st = 1 ; for ( int i = 0 ; i <= n ; i ++ ) { powers [ i ] = st ; st *= 10 ; st %= mod ; } st = 1 ; for ( int i = 0 ; i <= n ; i ++ ) { powersModk [ i ] = st ; st *= 10 ; st %= mod ; } memset ( dp , -1 , sizeof ( dp ) ) ; return calculate ( 0 , 0 , 0 , k , n ) ; } int main ( ) { int N = 2 ; int K = 2 ; cout << countNumbers ( N , K ) ; return 0 ; }
Shortest path with exactly k edges in a directed and weighted graph | Set 2 | C ++ implementation of the above approach ; Function to find the smallest path with exactly K edges ; Array to store dp ; Initialising the array ; Loop to solve DP ; Initialising next state ; Recurrence relation ; Returning final answer ; Driver code ; Input edges ; Source and Destination ; Number of edges in path ; Calling the function
#include <bits/stdc++.h> NEW_LINE #define inf 100000000 NEW_LINE using namespace std ; double smPath ( int s , int d , vector < pair < pair < int , int > , int > > ed , int n , int k ) { int dis [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) dis [ i ] = inf ; dis [ s ] = 0 ; for ( int i = 0 ; i < k ; i ++ ) { int dis1 [ n + 1 ] ; for ( int j = 0 ; j <= n ; j ++ ) dis1 [ j ] = inf ; for ( auto it : ed ) dis1 [ it . first . second ] = min ( dis1 [ it . first . second ] , dis [ it . first . first ] + it . second ) ; for ( int i = 0 ; i <= n ; i ++ ) dis [ i ] = dis1 [ i ] ; } if ( dis [ d ] == inf ) return -1 ; else return dis [ d ] ; } int main ( ) { int n = 4 ; vector < pair < pair < int , int > , int > > ed ; ed = { { { 0 , 1 } , 10 } , { { 0 , 2 } , 3 } , { { 0 , 3 } , 2 } , { { 1 , 3 } , 7 } , { { 2 , 3 } , 7 } } ; int s = 0 , d = 3 ; int k = 2 ; cout << smPath ( s , d , ed , n , k ) ; }
Path with smallest product of edges with weight > 0 | C ++ implementation of the approach . ; Function to return the smallest product of edges ; If the source is equal to the destination ; Array to store distances ; Initialising the array ; Bellman ford algorithm ; Loop to detect cycle ; Returning final answer ; Driver code ; Input edges ; Source and Destination ; Bellman ford
#include <bits/stdc++.h> NEW_LINE using namespace std ; double inf = std :: numeric_limits < double > :: infinity ( ) ; double bellman ( int s , int d , vector < pair < pair < int , int > , double > > ed , int n ) { if ( s == d ) return 0 ; double dis [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) dis [ i ] = inf ; dis [ s ] = 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) for ( auto it : ed ) dis [ it . first . second ] = min ( dis [ it . first . second ] , dis [ it . first . first ] * it . second ) ; for ( auto it : ed ) { if ( dis [ it . first . second ] > dis [ it . first . first ] * it . second ) return -2 ; } if ( dis [ d ] == inf ) return -1 ; else return dis [ d ] ; } int main ( ) { int n = 3 ; vector < pair < pair < int , int > , double > > ed ; ed = { { { 1 , 2 } , 0.5 } , { { 1 , 3 } , 1.9 } , { { 2 , 3 } , 3 } } ; int s = 1 , d = 3 ; double get = bellman ( s , d , ed , n ) ; if ( get == -2 ) cout << " Cycle ▁ Detected " ; else cout << get ; }
Find Maximum Length Of A Square Submatrix Having Sum Of Elements At | C ++ implementation of the above approach ; Function to return maximum length of square submatrix having sum of elements at - most K ; Matrix to store prefix sum ; Current maximum length ; Variable for storing maximum length of square ; Calculating prefix sum ; Checking whether there exits square with length cur_max + 1 or not ; Returning the maximum length ; Driver code
#include <iostream> NEW_LINE using namespace std ; int maxLengthSquare ( int row , int column , int arr [ ] [ 4 ] , int k ) { int sum [ row + 1 ] [ column + 1 ] ; for ( int i = 1 ; i <= row ; i ++ ) for ( int j = 0 ; j <= column ; j ++ ) sum [ i ] [ j ] = 0 ; int cur_max = 1 ; int max = 0 ; for ( int i = 1 ; i <= row ; i ++ ) { for ( int j = 1 ; j <= column ; j ++ ) { sum [ i ] [ j ] = sum [ i - 1 ] [ j ] + sum [ i ] [ j - 1 ] + arr [ i - 1 ] [ j - 1 ] - sum [ i - 1 ] [ j - 1 ] ; if ( i >= cur_max && j >= cur_max && sum [ i ] [ j ] - sum [ i - cur_max ] [ j ] - sum [ i ] [ j - cur_max ] + sum [ i - cur_max ] [ j - cur_max ] <= k ) { max = cur_max ++ ; } } } return max ; } int main ( ) { int row = 4 , column = 4 ; int matrix [ 4 ] [ 4 ] = { { 1 , 1 , 1 , 1 } , { 1 , 0 , 0 , 0 } , { 1 , 0 , 0 , 0 } , { 1 , 0 , 0 , 0 } } ; int k = 6 ; int ans = maxLengthSquare ( row , column , matrix , k ) ; cout << ans ; return 0 ; }
Sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times | C ++ program to find sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times ; exactsum [ i ] [ j ] [ k ] stores the sum of all the numbers having exact i 4 ' s , ▁ j ▁ 5' s and k 6 's ; exactnum [ i ] [ j ] [ k ] stores numbers of numbers having exact i 4 ' s , ▁ j ▁ 5' s and k 6 's ; Utility function to calculate the sum for x 4 ' s , ▁ y ▁ 5' s and z 6 's ; Computing exactsum [ i ] [ j ] [ k ] as explained above ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 101 ; const int mod = 1e9 + 7 ; int exactsum [ N ] [ N ] [ N ] ; int exactnum [ N ] [ N ] [ N ] ; int getSum ( int x , int y , int z ) { int ans = 0 ; exactnum [ 0 ] [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i <= x ; ++ i ) { for ( int j = 0 ; j <= y ; ++ j ) { for ( int k = 0 ; k <= z ; ++ k ) { if ( i > 0 ) { exactsum [ i ] [ j ] [ k ] += ( exactsum [ i - 1 ] [ j ] [ k ] * 10 + 4 * exactnum [ i - 1 ] [ j ] [ k ] ) % mod ; exactnum [ i ] [ j ] [ k ] += exactnum [ i - 1 ] [ j ] [ k ] % mod ; } if ( j > 0 ) { exactsum [ i ] [ j ] [ k ] += ( exactsum [ i ] [ j - 1 ] [ k ] * 10 + 5 * exactnum [ i ] [ j - 1 ] [ k ] ) % mod ; exactnum [ i ] [ j ] [ k ] += exactnum [ i ] [ j - 1 ] [ k ] % mod ; } if ( k > 0 ) { exactsum [ i ] [ j ] [ k ] += ( exactsum [ i ] [ j ] [ k - 1 ] * 10 + 6 * exactnum [ i ] [ j ] [ k - 1 ] ) % mod ; exactnum [ i ] [ j ] [ k ] += exactnum [ i ] [ j ] [ k - 1 ] % mod ; } ans += exactsum [ i ] [ j ] [ k ] % mod ; ans %= mod ; } } } return ans ; } int main ( ) { int x = 1 , y = 1 , z = 1 ; cout << ( getSum ( x , y , z ) % mod ) ; return 0 ; }
Maximum value obtained by performing given operations in an Array | C ++ implementation of the above approach ; A function to calculate the maximum value ; basecases ; Loop to iterate and add the max value in the dp array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMax ( int a [ ] , int n ) { int dp [ n ] [ 2 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = a [ 0 ] + a [ 1 ] ; dp [ 0 ] [ 1 ] = a [ 0 ] * a [ 1 ] ; for ( int i = 1 ; i <= n - 2 ; i ++ ) { dp [ i ] [ 0 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) + a [ i + 1 ] ; dp [ i ] [ 1 ] = dp [ i - 1 ] [ 0 ] - a [ i ] + a [ i ] * a [ i + 1 ] ; } cout << max ( dp [ n - 2 ] [ 0 ] , dp [ n - 2 ] [ 1 ] ) ; } int main ( ) { int arr [ ] = { 5 , -1 , -5 , -3 , 2 , 9 , -4 } ; findMax ( arr , 7 ) ; }
Optimal strategy for a Game with modifications | C ++ implementation of the above approach ; Function to return sum of subarray from l to r ; calculate sum by a loop from l to r ; dp to store the values of sub problems ; if length of the array is less than k return the sum ; if the value is previously calculated ; else calculate the value ; select all the sub array of length len_r ; get the sum of that sub array ; check if it is the maximum or not ; store it in the table ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll sum ( int arr [ ] , int l , int r ) { ll s = 0 ; for ( int i = l ; i <= r ; i ++ ) { s += arr [ i ] ; } return s ; } ll dp [ 101 ] [ 101 ] [ 101 ] = { 0 } ; ll solve ( int arr [ ] , int l , int r , int k ) { if ( r - l + 1 <= k ) return sum ( arr , l , r ) ; if ( dp [ l ] [ r ] [ k ] ) return dp [ l ] [ r ] [ k ] ; ll sum_ = sum ( arr , l , r ) ; ll len_r = ( r - l + 1 ) - k ; ll len = ( r - l + 1 ) ; ll ans = 0 ; for ( int i = 0 ; i < len - len_r + 1 ; i ++ ) { ll sum_sub = sum ( arr , i + l , i + l + len_r - 1 ) ; ans = max ( ans , ( sum_ - sum_sub ) + ( sum_sub - solve ( arr , i + l , i + l + len_r - 1 , k ) ) ) ; } dp [ l ] [ r ] [ k ] = ans ; return ans ; } int main ( ) { int arr [ ] = { 10 , 15 , 20 , 9 , 2 , 5 } , k = 2 ; int n = sizeof ( arr ) / sizeof ( int ) ; memset ( dp , 0 , sizeof ( dp ) ) ; cout << solve ( arr , 0 , n - 1 , k ) ; return 0 ; }
Find the minimum difference path from ( 0 , 0 ) to ( N | C ++ implementation of the approach ; Function to return the minimum difference path from ( 0 , 0 ) to ( N - 1 , M - 1 ) ; Terminating case ; Base case ; If it is already visited ; Recursive calls ; Return the value ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXI 50 NEW_LINE int dp [ MAXI ] [ MAXI ] [ MAXI * MAXI ] ; int n , m ; int minDifference ( int x , int y , int k , vector < vector < int > > b , vector < vector < int > > c ) { if ( x >= n or y >= m ) return INT_MAX ; if ( x == n - 1 and y == m - 1 ) { int diff = b [ x ] [ y ] - c [ x ] [ y ] ; return min ( abs ( k - diff ) , abs ( k + diff ) ) ; } int & ans = dp [ x ] [ y ] [ k ] ; if ( ans != -1 ) return ans ; ans = INT_MAX ; int diff = b [ x ] [ y ] - c [ x ] [ y ] ; ans = min ( ans , minDifference ( x + 1 , y , abs ( k + diff ) , b , c ) ) ; ans = min ( ans , minDifference ( x , y + 1 , abs ( k + diff ) , b , c ) ) ; ans = min ( ans , minDifference ( x + 1 , y , abs ( k - diff ) , b , c ) ) ; ans = min ( ans , minDifference ( x , y + 1 , abs ( k - diff ) , b , c ) ) ; return ans ; } int main ( ) { n = 2 , m = 2 ; vector < vector < int > > b = { { 1 , 4 } , { 2 , 4 } } ; vector < vector < int > > c = { { 3 , 2 } , { 3 , 1 } } ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << minDifference ( 0 , 0 , 0 , b , c ) ; return 0 ; }
Longest subsequence having difference atmost K | C ++ program for the above approach ; Function to find the longest Special Sequence ; Creating a list with all 0 's of size equal to the length of string ; Supporting list with all 0 's of size 26 since the given string consists of only lower case alphabets ; Converting the ascii value to list indices ; Determining the lower bound ; Determining the upper bound ; Filling the dp array with values ; Filling the max_length array with max length of subsequence till now ; return the max length of subsequence ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longest_subseq ( int n , int k , string s ) { vector < int > dp ( n , 0 ) ; int max_length [ 26 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int curr = s [ i ] - ' a ' ; int lower = max ( 0 , curr - k ) ; int upper = min ( 25 , curr + k ) ; for ( int j = lower ; j < upper + 1 ; j ++ ) { dp [ i ] = max ( dp [ i ] , max_length [ j ] + 1 ) ; } max_length [ curr ] = max ( dp [ i ] , max_length [ curr ] ) ; } int ans = 0 ; for ( int i : dp ) ans = max ( i , ans ) ; return ans ; } int main ( ) { string s = " geeksforgeeks " ; int n = s . size ( ) ; int k = 3 ; cout << ( longest_subseq ( n , k , s ) ) ; return 0 ; }
Maximum sum subarray after altering the array | C ++ implementation of the approach ; Function that returns true if all the array element are <= 0 ; If any element is non - negative ; Function to return the vector representing the right to left Kadane array as described in the approach ; Function to return the prefix_sum vector ; Function to return the maximum sum subarray ; Function to get the maximum sum subarray in the modified array ; kadane_r_to_l [ i ] will store the maximum subarray sum for thre subarray arr [ i ... N - 1 ] ; Get the prefix sum array ; To get max_prefix_sum_at_any_index ; Summation of both gives the maximum subarray sum after applying the operation ; Function to return the maximum subarray sum after performing the given operation at most once ; If all element are negative then return the maximum element ; Maximum subarray sum without performing any operation ; Maximum subarray sum after performing the operations of first type ; Reversing the array to use the same existing function for operations of the second type ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool areAllNegative ( vector < int > arr ) { for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( arr [ i ] > 0 ) return false ; } return true ; } vector < int > getRightToLeftKadane ( vector < int > arr ) { int max_so_far = 0 , max_ending_here = 0 ; int size = arr . size ( ) ; for ( int i = size - 1 ; i >= 0 ; i -- ) { max_ending_here = max_ending_here + arr [ i ] ; if ( max_ending_here < 0 ) max_ending_here = 0 ; else if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; arr [ i ] = max_so_far ; } return arr ; } vector < int > getPrefixSum ( vector < int > arr ) { for ( int i = 1 ; i < arr . size ( ) ; i ++ ) arr [ i ] = arr [ i - 1 ] + arr [ i ] ; return arr ; } int maxSumSubArr ( vector < int > a ) { int max_so_far = 0 , max_ending_here = 0 ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { max_ending_here = max_ending_here + a [ i ] ; if ( max_ending_here < 0 ) max_ending_here = 0 ; else if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; } return max_so_far ; } int maxSumSubWithOp ( vector < int > arr ) { vector < int > kadane_r_to_l = getRightToLeftKadane ( arr ) ; vector < int > prefixSum = getPrefixSum ( arr ) ; int size = arr . size ( ) ; for ( int i = 1 ; i < size ; i ++ ) { prefixSum [ i ] = max ( prefixSum [ i - 1 ] , prefixSum [ i ] ) ; } int max_subarray_sum = 0 ; for ( int i = 0 ; i < size - 1 ; i ++ ) { max_subarray_sum = max ( max_subarray_sum , prefixSum [ i ] + kadane_r_to_l [ i + 1 ] ) ; } return max_subarray_sum ; } int maxSum ( vector < int > arr , int size ) { if ( areAllNegative ( arr ) ) { return ( * max_element ( arr . begin ( ) , arr . end ( ) ) ) ; } int resSum = maxSumSubArr ( arr ) ; resSum = max ( resSum , maxSumSubWithOp ( arr ) ) ; reverse ( arr . begin ( ) , arr . end ( ) ) ; resSum = max ( resSum , maxSumSubWithOp ( arr ) ) ; return resSum ; } int main ( ) { vector < int > arr { -9 , 21 , 24 , 24 , -51 , -6 , 17 , -42 , -39 , 33 } ; int size = arr . size ( ) ; cout << maxSum ( arr , size ) ; return 0 ; }
Maximum possible array sum after performing the given operation | C ++ implementation of the approach ; Function to return the maximum possible sum after performing the given operation ; Dp vector to store the answer ; Base value ; Return the maximum sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max_sum ( int a [ ] , int n ) { vector < vector < int > > dp ( n + 1 , vector < int > ( 2 , 0 ) ) ; dp [ 0 ] [ 0 ] = 0 , dp [ 0 ] [ 1 ] = -999999 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) { dp [ i + 1 ] [ 0 ] = max ( dp [ i ] [ 0 ] + a [ i ] , dp [ i ] [ 1 ] - a [ i ] ) ; dp [ i + 1 ] [ 1 ] = max ( dp [ i ] [ 0 ] - a [ i ] , dp [ i ] [ 1 ] + a [ i ] ) ; } return dp [ n ] [ 0 ] ; } int main ( ) { int a [ ] = { -10 , 5 , -4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << max_sum ( a , n ) ; return 0 ; }
Find the number of ways to reach Kth step in stair case | C ++ implementation of the approach ; Function to return the number of ways to reach the kth step ; Create the dp array ; Broken steps ; Calculate the number of ways for the rest of the positions ; If it is a blocked position ; Number of ways to get to the ith step ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = 1000000007 ; int number_of_ways ( int arr [ ] , int n , int k ) { if ( k == 1 ) return 1 ; int dp [ k + 1 ] ; memset ( dp , -1 , sizeof dp ) ; for ( int i = 0 ; i < n ; i ++ ) dp [ arr [ i ] ] = 0 ; dp [ 0 ] = 1 ; dp [ 1 ] = ( dp [ 1 ] == -1 ) ? 1 : dp [ 1 ] ; for ( int i = 2 ; i <= k ; ++ i ) { if ( dp [ i ] == 0 ) continue ; dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] ; dp [ i ] %= MOD ; } return dp [ k ] ; } int main ( ) { int arr [ ] = { 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 6 ; cout << number_of_ways ( arr , n , k ) ; return 0 ; }
Minimum number of coins that can generate all the values in the given range | C ++ program to find minimum number of coins ; Function to find minimum number of coins ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCount ( int n ) { return log ( n ) / log ( 2 ) + 1 ; } int main ( ) { int N = 10 ; cout << findCount ( N ) << endl ; return 0 ; }
Calculate the number of set bits for every number from 0 to N | C ++ implementation of the approach ; Function to find the count of set bits in all the integers from 0 to n ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSetBits ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) cout << __builtin_popcount ( i ) << " ▁ " ; } int main ( ) { int n = 5 ; findSetBits ( n ) ; return 0 ; }
Count number of ways to arrange first N numbers | C ++ implementation of the approach ; Function to return the count of required arrangements ; Create a vector ; Store numbers from 1 to n ; To store the count of ways ; Generate all the permutations using next_permutation in STL ; Initialize flag to true if first element is 1 else false ; Checking if the current permutation satisfies the given conditions ; If the current permutation is invalid then set the flag to false ; If valid arrangement ; Generate the next permutation ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int n ) { vector < int > a ; int i = 1 ; while ( i <= n ) a . push_back ( i ++ ) ; int ways = 0 ; do { bool flag = ( a [ 0 ] == 1 ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( abs ( a [ i ] - a [ i - 1 ] ) > 2 ) flag = 0 ; } if ( flag ) ways ++ ; } while ( next_permutation ( a . begin ( ) , a . end ( ) ) ) ; return ways ; } int main ( ) { int n = 6 ; cout << countWays ( n ) ; return 0 ; }
Count number of ways to arrange first N numbers | C ++ implementation of the approach ; Function to return the count of required arrangements ; Create the dp array ; Initialize the base cases as explained above ; ( 12 ) as the only possibility ; Generate answer for greater values ; dp [ n ] contains the desired answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int n ) { int dp [ n + 1 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = 1 ; dp [ 2 ] = 1 ; for ( int i = 3 ; i <= n ; i ++ ) { dp [ i ] = dp [ i - 1 ] + dp [ i - 3 ] + 1 ; } return dp [ n ] ; } int main ( ) { int n = 6 ; cout << countWays ( n ) ; return 0 ; }
Number of shortest paths to reach every cell from bottom | CPP program to find number of shortest paths ; Function to find number of shortest paths ; Compute the grid starting from the bottom - left corner ; Print the grid ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void NumberOfShortestPaths ( int n , int m ) { int a [ n ] [ m ] ; for ( int i = 0 ; i < n ; i ++ ) memset ( a [ i ] , 0 , sizeof ( a [ i ] ) ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { for ( int j = 0 ; j < m ; j ++ ) { if ( j == 0 or i == n - 1 ) a [ i ] [ j ] = 1 ; else a [ i ] [ j ] = a [ i ] [ j - 1 ] + a [ i + 1 ] [ j ] ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { cout << a [ i ] [ j ] << " ▁ " ; } cout << endl ; } } int main ( ) { int n = 5 , m = 2 ; NumberOfShortestPaths ( n , m ) ; return 0 ; }
Maximum sum combination from two arrays | CPP program to maximum sum combination from two arrays ; Function to maximum sum combination from two arrays ; To store dp value ; For loop to calculate the value of dp ; Return the required answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Max_Sum ( int arr1 [ ] , int arr2 [ ] , int n ) { int dp [ n ] [ 2 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) { dp [ i ] [ 0 ] = arr1 [ i ] ; dp [ i ] [ 1 ] = arr2 [ i ] ; continue ; } dp [ i ] [ 0 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] + arr1 [ i ] ) ; dp [ i ] [ 1 ] = max ( dp [ i - 1 ] [ 1 ] , dp [ i - 1 ] [ 0 ] + arr2 [ i ] ) ; } return max ( dp [ n - 1 ] [ 0 ] , dp [ n - 1 ] [ 1 ] ) ; } int main ( ) { int arr1 [ ] = { 9 , 3 , 5 , 7 , 3 } ; int arr2 [ ] = { 5 , 8 , 1 , 4 , 5 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; cout << Max_Sum ( arr1 , arr2 , n ) ; return 0 ; }
Partition the array in K segments such that bitwise AND of individual segment sum is maximized | CPP program to find maximum possible AND ; Function to check whether a k segment partition is possible such that bitwise AND is ' mask ' ; dp [ i ] [ j ] stores whether it is possible to partition first i elements into j segments such that all j segments are ' good ' ; Initialising dp ; Filling dp in bottom - up manner ; Finding a cut such that first l elements can be partitioned into j - 1 ' good ' segments and arr [ l + 1 ] + ... + arr [ i ] is a ' good ' segment ; Function to find maximum possible AND ; Array to store prefix sums ; Maximum no of bits in the possible answer ; This will store the final answer ; Constructing answer greedily selecting from the higher most bit ; Checking if array can be partitioned such that the bitwise AND is ans | ( 1 << i ) ; if possible , update the answer ; Return the final answer ; Driver code ; n = 11 , first element is zero to make array 1 based indexing . So , number of elements are 10 ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkpossible ( int mask , int * arr , int * prefix , int n , int k ) { bool dp [ n + 1 ] [ k + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= k ; j ++ ) { for ( int l = i - 1 ; l >= 0 ; -- l ) { if ( dp [ l ] [ j - 1 ] && ( ( ( prefix [ i ] - prefix [ l ] ) & mask ) == mask ) ) { dp [ i ] [ j ] = 1 ; break ; } } } } return dp [ n ] [ k ] ; } int Partition ( int arr [ ] , int n , int k ) { int prefix [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] + arr [ i ] ; } int LOGS = 20 ; int ans = 0 ; for ( int i = LOGS ; i >= 0 ; -- i ) { if ( checkpossible ( ans | ( 1 << i ) , arr , prefix , n , k ) ) { ans = ans | ( 1 << i ) ; } } return ans ; } int main ( ) { int arr [ ] = { 0 , 1 , 2 , 7 , 10 , 23 , 21 , 6 , 8 , 7 , 3 } , k = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) - 1 ; cout << Partition ( arr , n , k ) ; return 0 ; }
Cost Based Tower of Hanoi | C ++ implementation of the approach ; Function to initialize the dp table ; Initialize with maximum value ; Function to return the minimum cost ; Base case ; If problem is already solved , return the pre - calculated answer ; Number of the auxiliary disk ; Initialize the minimum cost as Infinity ; Calculationg the cost for first case ; Calculating the cost for second case ; Minimum of both the above cases ; Store it in the dp table ; Return the minimum cost ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define RODS 3 NEW_LINE #define N 3 NEW_LINE int dp [ N + 1 ] [ RODS + 1 ] [ RODS + 1 ] ; void initialize ( ) { for ( int i = 0 ; i <= N ; i += 1 ) { for ( int j = 1 ; j <= RODS ; j ++ ) { for ( int k = 1 ; k <= RODS ; k += 1 ) { dp [ i ] [ j ] [ k ] = INT_MAX ; } } } } int mincost ( int idx , int src , int dest , int costs [ RODS ] [ RODS ] ) { if ( idx > N ) return 0 ; if ( dp [ idx ] [ src ] [ dest ] != INT_MAX ) return dp [ idx ] [ src ] [ dest ] ; int rem = 6 - ( src + dest ) ; int ans = INT_MAX ; int case1 = costs [ src - 1 ] [ dest - 1 ] + mincost ( idx + 1 , src , rem , costs ) + mincost ( idx + 1 , rem , dest , costs ) ; int case2 = costs [ src - 1 ] [ rem - 1 ] + mincost ( idx + 1 , src , dest , costs ) + mincost ( idx + 1 , dest , src , costs ) + costs [ rem - 1 ] [ dest - 1 ] + mincost ( idx + 1 , src , dest , costs ) ; ans = min ( case1 , case2 ) ; dp [ idx ] [ src ] [ dest ] = ans ; return ans ; } int main ( ) { int costs [ RODS ] [ RODS ] = { { 0 , 1 , 2 } , { 2 , 0 , 1 } , { 3 , 2 , 0 } } ; initialize ( ) ; cout << mincost ( 1 , 1 , 3 , costs ) ; return 0 ; }
Minimum time required to rot all oranges | Dynamic Programming | C ++ implementation of the approach ; DP table to memoize the values ; Visited array to keep track of visited nodes in order to avoid infinite loops ; Function to return the minimum of four numbers ; Function to return the minimum distance to any rotten orange from [ i , j ] ; If i , j lie outside the array ; If 0 then it can 't lead to any path so return INT_MAX ; If 2 then we have reached our rotten oranges so return from here ; If this node is already visited then return to avoid infinite loops ; Mark the current node as visited ; Check in all four possible directions ; Take the minimum of all ; If result already exists in the table check if min_value is less than existing value ; Function to return the minimum time required to rot all the oranges ; Calculate the minimum distances to any rotten orange from all the fresh oranges ; Pick the maximum distance of fresh orange to some rotten orange ; If all oranges can be rotten ; Driver Code
#include <iostream> NEW_LINE using namespace std ; #define C 5 NEW_LINE #define R 3 NEW_LINE #define INT_MAX 10000000 NEW_LINE int table [ R ] [ C ] = { 0 } ; int visited [ R ] [ C ] = { 0 } ; int min ( int p , int q , int r , int s ) { int temp1 = p < q ? p : q ; int temp2 = r < s ? r : s ; if ( temp1 < temp2 ) return temp1 ; return temp2 ; } int Distance ( int arr [ R ] [ C ] , int i , int j ) { if ( i >= R j >= C i < 0 j < 0 ) return INT_MAX ; else if ( arr [ i ] [ j ] == 0 ) { table [ i ] [ j ] = INT_MAX ; return INT_MAX ; } else if ( arr [ i ] [ j ] == 2 ) { table [ i ] [ j ] = 0 ; return 0 ; } else if ( visited [ i ] [ j ] ) { return INT_MAX ; } else { visited [ i ] [ j ] = 1 ; int temp1 = Distance ( arr , i + 1 , j ) ; int temp2 = Distance ( arr , i - 1 , j ) ; int temp3 = Distance ( arr , i , j + 1 ) ; int temp4 = Distance ( arr , i , j - 1 ) ; int min_value = 1 + min ( temp1 , temp2 , temp3 , temp4 ) ; if ( table [ i ] [ j ] > 0 && table [ i ] [ j ] < INT_MAX ) { if ( min_value < table [ i ] [ j ] ) table [ i ] [ j ] = min_value ; } else table [ i ] [ j ] = min_value ; visited [ i ] [ j ] = 0 ; return table [ i ] [ j ] ; } } int minTime ( int arr [ ] [ C ] ) { int max = 0 ; for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { if ( arr [ i ] [ j ] == 1 ) Distance ( arr , i , j ) ; } } for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { if ( arr [ i ] [ j ] == 1 && table [ i ] [ j ] > max ) max = table [ i ] [ j ] ; } } if ( max < INT_MAX ) return max ; return -1 ; } int main ( ) { int arr [ R ] [ C ] = { { 2 , 1 , 0 , 2 , 1 } , { 0 , 0 , 1 , 2 , 1 } , { 1 , 0 , 0 , 2 , 1 } } ; cout << minTime ( arr ) ; return 0 ; }
Maximum sum of non | 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 ; Variable to store prefix sum for sub - array { i , j } ; Required recurrence relation ; Returning the value ; Driver code ; Input array
#include <bits/stdc++.h> NEW_LINE #define maxLen 10 NEW_LINE using namespace std ; int dp [ maxLen ] ; bool visit [ maxLen ] ; int maxSum ( int arr [ ] , int i , int n , int k ) { if ( i >= n ) return 0 ; if ( visit [ i ] ) return dp [ i ] ; visit [ i ] = 1 ; int tot = 0 ; dp [ i ] = maxSum ( arr , i + 1 , n , k ) ; for ( int j = i ; j < i + k and j < n ; j ++ ) { tot += arr [ j ] ; dp [ i ] = max ( dp [ i ] , tot + maxSum ( arr , j + 2 , n , k ) ) ; } return dp [ i ] ; } int main ( ) { int arr [ ] = { -1 , 2 , -3 , 4 , 5 } ; int k = 2 ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << maxSum ( arr , 0 , n , k ) ; return 0 ; }
Maximum subset sum such that no two elements in set have same digit in them | C ++ implementation of above approach ; Function to create mask for every number ; Recursion for Filling DP array ; Base Condition ; Recurrence Relation ; Function to find Maximum Subset Sum ; Initialize DP array ; Iterate over all possible masks of 10 bit number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 1024 ] ; int get_binary ( int u ) { int ans = 0 ; while ( u ) { int rem = u % 10 ; ans |= ( 1 << rem ) ; u /= 10 ; } return ans ; } int recur ( int u , int array [ ] , int n ) { if ( u == 0 ) return 0 ; if ( dp [ u ] != -1 ) return dp [ u ] ; int temp = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int mask = get_binary ( array [ i ] ) ; if ( ( mask u ) == u ) { dp [ u ] = max ( max ( 0 , dp [ u ^ mask ] ) + array [ i ] , dp [ u ] ) ; } } return dp [ u ] ; } int solve ( int array [ ] , int n ) { for ( int i = 0 ; i < ( 1 << 10 ) ; i ++ ) { dp [ i ] = -1 ; } int ans = 0 ; for ( int i = 0 ; i < ( 1 << 10 ) ; i ++ ) { ans = max ( ans , recur ( i , array , n ) ) ; } return ans ; } int main ( ) { int array [ ] = { 22 , 132 , 4 , 45 , 12 , 223 } ; int n = sizeof ( array ) / sizeof ( array [ 0 ] ) ; cout << solve ( array , n ) ; }
Minimize the sum after choosing elements from the given three arrays | C ++ implementation of the above approach ; Function to return the minimized sum ; If all the indices have been used ; If this value is pre - calculated then return its value from dp array instead of re - computing it ; If A [ i - 1 ] was chosen previously then only B [ i ] or C [ i ] can chosen now choose the one which leads to the minimum sum ; If B [ i - 1 ] was chosen previously then only A [ i ] or C [ i ] can chosen now choose the one which leads to the minimum sum ; If C [ i - 1 ] was chosen previously then only A [ i ] or B [ i ] can chosen now choose the one which leads to the minimum sum ; Driver code ; Initialize the dp [ ] [ ] array ; min ( start with A [ 0 ] , start with B [ 0 ] , start with C [ 0 ] )
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 3 NEW_LINE const int N = 3 ; int minSum ( int A [ ] , int B [ ] , int C [ ] , int i , int n , int curr , int dp [ SIZE ] [ N ] ) { if ( n <= 0 ) return 0 ; if ( dp [ n ] [ curr ] != -1 ) return dp [ n ] [ curr ] ; if ( curr == 0 ) { return dp [ n ] [ curr ] = min ( B [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 1 , dp ) , C [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 2 , dp ) ) ; } if ( curr == 1 ) return dp [ n ] [ curr ] = min ( A [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 0 , dp ) , C [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 2 , dp ) ) ; return dp [ n ] [ curr ] = min ( A [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 0 , dp ) , B [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 1 , dp ) ) ; } int main ( ) { int A [ ] = { 1 , 50 , 1 } ; int B [ ] = { 50 , 50 , 50 } ; int C [ ] = { 50 , 50 , 50 } ; int dp [ SIZE ] [ N ] ; for ( int i = 0 ; i < SIZE ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) dp [ i ] [ j ] = -1 ; cout << min ( A [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 0 , dp ) , min ( B [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 1 , dp ) , C [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 2 , dp ) ) ) ; return 0 ; }
Maximise matrix sum by following the given Path | C ++ implementation of the approach ; To store the states of the DP ; Function to return the maximum of the three integers ; Function to return the maximum score ; Base cases ; If the state has already been solved then return it ; Marking the state as solved ; Growing phase ; Shrinking phase ; Returning the solved state ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define n 3 NEW_LINE int dp [ n ] [ n ] [ 2 ] ; bool v [ n ] [ n ] [ 2 ] ; int max ( int a , int b , int c ) { int m = a ; if ( m < b ) m = b ; if ( m < c ) m = c ; return m ; } int maxScore ( int arr [ ] [ n ] , int i , int j , int s ) { if ( i > n - 1 i < 0 j > n - 1 ) return 0 ; if ( i == 0 and j == n - 1 ) return arr [ i ] [ j ] ; if ( v [ i ] [ j ] [ s ] ) return dp [ i ] [ j ] [ s ] ; v [ i ] [ j ] [ s ] = 1 ; if ( ! s ) dp [ i ] [ j ] [ s ] = arr [ i ] [ j ] + max ( maxScore ( arr , i + 1 , j , s ) , maxScore ( arr , i , j + 1 , s ) , maxScore ( arr , i - 1 , j , ! s ) ) ; else dp [ i ] [ j ] [ s ] = arr [ i ] [ j ] + max ( maxScore ( arr , i - 1 , j , s ) , maxScore ( arr , i , j + 1 , s ) ) ; return dp [ i ] [ j ] [ s ] ; } int main ( ) { int arr [ n ] [ n ] = { { 1 , 1 , 1 } , { 1 , 5 , 1 } , { 1 , 1 , 1 } } ; cout << maxScore ( arr , 0 , 0 , 0 ) ; return 0 ; }
Find maximum topics to prepare in order to pass the exam | C ++ implementation of the approach ; Function to return the maximum marks by considering topics which can be completed in the given time duration ; If we are given 0 time then nothing can be done So all values are 0 ; If we are given 0 topics then the time required will be 0 for sure ; Calculating the maximum marks that can be achieved under the given time constraints ; If time taken to read that topic is more than the time left now at position j then do no read that topic ; Two cases arise : 1 ) Considering current topic 2 ) Ignoring current topic We are finding maximum of ( current topic weightage + topics which can be done in leftover time - current topic time ) and ignoring current topic weightage sum ; Moving upwards in table from bottom right to calculate the total time taken to read the topics which can be done in given time and have highest weightage sum ; It means we have not considered reading this topic for max weightage sum ; Adding the topic time ; Evaluating the left over time after considering this current topic ; One topic completed ; It contains the maximum weightage sum formed by considering the topics ; Condition when exam cannot be passed ; Return the marks that can be obtained after passing the exam ; Driver code ; Number of topics , hours left and the passing marks ; n + 1 is taken for simplicity in loops Array will be indexed starting from 1
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MaximumMarks ( int marksarr [ ] , int timearr [ ] , int h , int n , int p ) { int no_of_topics = n + 1 ; int total_time = h + 1 ; int T [ no_of_topics ] [ total_time ] ; for ( int i = 0 ; i < no_of_topics ; i ++ ) { T [ i ] [ 0 ] = 0 ; } for ( int j = 0 ; j < total_time ; j ++ ) { T [ 0 ] [ j ] = 0 ; } for ( int i = 1 ; i < no_of_topics ; i ++ ) { for ( int j = 1 ; j < total_time ; j ++ ) { if ( j < timearr [ i ] ) { T [ i ] [ j ] = T [ i - 1 ] [ j ] ; } else { T [ i ] [ j ] = max ( marksarr [ i ] + T [ i - 1 ] [ j - timearr [ i ] ] , T [ i - 1 ] [ j ] ) ; } } } int i = no_of_topics - 1 , j = total_time - 1 ; int sum = 0 ; while ( i > 0 && j > 0 ) { if ( T [ i ] [ j ] == T [ i - 1 ] [ j ] ) { i -- ; } else { sum += timearr [ i ] ; j -= timearr [ i ] ; i -- ; } } int marks = T [ no_of_topics - 1 ] [ total_time - 1 ] ; if ( marks < p ) return -1 ; return sum ; } int main ( ) { int n = 4 , h = 10 , p = 10 ; int marksarr [ n + 1 ] = { 0 , 6 , 4 , 2 , 8 } ; int timearr [ n + 1 ] = { 0 , 4 , 6 , 2 , 7 } ; cout << MaximumMarks ( marksarr , timearr , h , n , p ) ; return 0 ; }
Minimize the number of steps required to reach the end of the array | C ++ implementation of the above approach ; variable to store states of dp ; variable to check if a given state has been solved ; Function to find the minimum number of steps required to reach the end of the array ; 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 #define maskLen 130 NEW_LINE using namespace std ; int dp [ maxLen ] [ maskLen ] ; bool v [ maxLen ] [ maskLen ] ; int minSteps ( int arr [ ] , int i , int mask , int n ) { if ( i == n - 1 ) return 0 ; if ( i > n - 1 i < 0 ) return 9999999 ; if ( ( mask >> i ) & 1 ) return 9999999 ; if ( v [ i ] [ mask ] ) return dp [ i ] [ mask ] ; v [ i ] [ mask ] = 1 ; dp [ i ] [ mask ] = 1 + min ( minSteps ( arr , i - arr [ i ] , ( mask | ( 1 << i ) ) , n ) , minSteps ( arr , i + arr [ i ] , ( mask | ( 1 << i ) ) , n ) ) ; return dp [ i ] [ mask ] ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 2 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int ans = minSteps ( arr , 0 , 0 , n ) ; if ( ans >= 9999999 ) cout << -1 ; else cout << ans ; }
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 ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int oSRec ( int arr [ ] , int i , int j , int sum ) { if ( j == i + 1 ) return max ( arr [ i ] , arr [ j ] ) ; return max ( ( sum - oSRec ( arr , i + 1 , j , sum - arr [ i ] ) ) , ( sum - oSRec ( arr , i , j - 1 , sum - arr [ j ] ) ) ) ; } int optimalStrategyOfGame ( int * arr , int n ) { int sum = 0 ; sum = accumulate ( arr , arr + n , sum ) ; 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 number of sub | C ++ implementation of the approach ; Function that returns true if n is a power of 5 ; Function to return the decimal value of binary equivalent ; Function to return the minimum cuts required ; Allocating memory for dp [ ] array ; From length 1 to n ; If previous character is '0' then ignore to avoid number with leading 0 s . ; Ignore s [ j ] = '0' starting numbers ; Number formed from s [ j ... . i ] ; Check for power of 5 ; Assigning min value to get min cut possible ; ( n + 1 ) to check if all the strings are traversed and no divisible by 5 is obtained like 000000 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll unsigned long long NEW_LINE bool ispower ( ll n ) { if ( n < 125 ) return ( n == 1 n == 5 n == 25 ) ; if ( n % 125 != 0 ) return false ; else return ispower ( n / 125 ) ; } ll number ( string s , int i , int j ) { ll ans = 0 ; for ( int x = i ; x < j ; x ++ ) { ans = ans * 2 + ( s [ x ] - '0' ) ; } return ans ; } int minCuts ( string s , int n ) { int dp [ n + 1 ] ; memset ( dp , n + 1 , sizeof ( dp ) ) ; dp [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( s [ i - 1 ] == '0' ) continue ; for ( int j = 0 ; j < i ; j ++ ) { if ( s [ j ] == '0' ) continue ; ll num = number ( s , j , i ) ; if ( ! ispower ( num ) ) continue ; dp [ i ] = min ( dp [ i ] , dp [ j ] + 1 ) ; } } return ( ( dp [ n ] < n + 1 ) ? dp [ n ] : -1 ) ; } int main ( ) { string s = "101101101" ; int n = s . length ( ) ; cout << minCuts ( s , n ) ; return 0 ; }
Minimum number of cubes whose sum equals to given number N | C ++ implementation of the approach ; Function to return the minimum number of cubes whose sum is k ; If k is less than the 2 ^ 3 ; Initialize with the maximum number of cubes required ; Driver code
#include <iostream> NEW_LINE using namespace std ; int MinOfCubed ( int k ) { if ( k < 8 ) return k ; int res = k ; for ( int i = 1 ; i <= k ; i ++ ) { if ( ( i * i * i ) > k ) return res ; res = min ( res , MinOfCubed ( k - ( i * i * i ) ) + 1 ) ; } return res ; } int main ( ) { int num = 15 ; cout << MinOfCubed ( num ) ; return 0 ; }
Minimum number of cubes whose sum equals to given number N | C ++ implementation of the approach ; Function to return the minimum number of cubes whose sum is k ; While current perfect cube is less than current element ; If i is a perfect cube ; i = ( i - 1 ) + 1 ^ 3 ; Next perfect cube ; Re - initialization for next element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinOfCubedDP ( int k ) { int * DP = new int [ k + 1 ] , j = 1 , t = 1 ; DP [ 0 ] = 0 ; for ( int i = 1 ; i <= k ; i ++ ) { DP [ i ] = INT_MAX ; while ( j <= i ) { if ( j == i ) DP [ i ] = 1 ; else if ( DP [ i ] > DP [ i - j ] ) DP [ i ] = DP [ i - j ] + 1 ; t ++ ; j = t * t * t ; } t = j = 1 ; } return DP [ k ] ; } int main ( ) { int num = 15 ; cout << MinOfCubedDP ( num ) ; return 0 ; }
Maximum Subarray Sum after inverting at most two elements | C ++ implementation of the approach ; Function to return the maximum required sub - array sum ; Creating one based indexing ; 2d array to contain solution for each step ; Case 1 : Choosing current or ( current + previous ) whichever is smaller ; Case 2 : ( a ) Altering sign and add to previous case 1 or value 0 ; Case 2 : ( b ) Adding current element with previous case 2 and updating the maximum ; Case 3 : ( a ) Altering sign and add to previous case 2 ; Case 3 : ( b ) Adding current element with previous case 3 ; Updating the maximum value of variable ans ; Return the final solution ; Driver code
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int maxSum ( int a [ ] , int n ) { int ans = 0 ; int * arr = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) arr [ i ] = a [ i - 1 ] ; int * * dp = new int * [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) dp [ i ] = new int [ 3 ] ; for ( int i = 1 ; i <= n ; ++ i ) { dp [ i ] [ 0 ] = max ( arr [ i ] , dp [ i - 1 ] [ 0 ] + arr [ i ] ) ; dp [ i ] [ 1 ] = max ( 0 , dp [ i - 1 ] [ 0 ] ) - arr [ i ] ; if ( i >= 2 ) dp [ i ] [ 1 ] = max ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 1 ] + arr [ i ] ) ; if ( i >= 2 ) dp [ i ] [ 2 ] = dp [ i - 1 ] [ 1 ] - arr [ i ] ; if ( i >= 3 ) dp [ i ] [ 2 ] = max ( dp [ i ] [ 2 ] , dp [ i - 1 ] [ 2 ] + arr [ i ] ) ; ans = max ( ans , dp [ i ] [ 0 ] ) ; ans = max ( ans , dp [ i ] [ 1 ] ) ; ans = max ( ans , dp [ i ] [ 2 ] ) ; } return ans ; } int main ( ) { int arr [ ] = { -5 , 3 , 2 , 7 , -8 , 3 , 7 , -9 , 10 , 12 , -6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSum ( arr , n ) ; return 0 ; }
Maximum sum possible for a sub | C ++ implementation of the approach ; Function to return the maximum sum possible ; dp [ i ] represent the maximum sum so far after reaching current position i ; Initialize dp [ 0 ] ; Initialize the dp values till k since any two elements included in the sub - sequence must be atleast k indices apart , and thus first element and second element will be k indices apart ; Fill remaining positions ; Return the maximum sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int * arr , int k , int n ) { if ( n == 0 ) return 0 ; if ( n == 1 ) return arr [ 0 ] ; if ( n == 2 ) return max ( arr [ 0 ] , arr [ 1 ] ) ; int dp [ n ] ; dp [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i <= k ; i ++ ) dp [ i ] = max ( arr [ i ] , dp [ i - 1 ] ) ; for ( int i = k + 1 ; i < n ; i ++ ) dp [ i ] = max ( arr [ i ] , dp [ i - ( k + 1 ) ] + arr [ i ] ) ; int max = * ( std :: max_element ( dp , dp + n ) ) ; return max ; } int main ( ) { int arr [ ] = { 6 , 7 , 1 , 3 , 8 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << maxSum ( arr , k , n ) ; return 0 ; }
Minimum cost to form a number X by adding up powers of 2 | C ++ implementation of the approach ; Function to return the minimum cost ; Re - compute the array ; Add answers for set bits ; If bit is set ; Increase the counter ; Right shift the number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumCost ( int a [ ] , int n , int x ) { for ( int i = 1 ; i < n ; i ++ ) { a [ i ] = min ( a [ i ] , 2 * a [ i - 1 ] ) ; } int ind = 0 ; int sum = 0 ; while ( x ) { if ( x & 1 ) sum += a [ ind ] ; ind ++ ; x = x >> 1 ; } return sum ; } int main ( ) { int a [ ] = { 20 , 50 , 60 , 90 } ; int x = 7 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << MinimumCost ( a , n , x ) ; return 0 ; }
Ways to form an array having integers in given range such that total sum is divisible by 2 | C ++ implementation of the approach ; Function to return the number of ways to form an array of size n such that sum of all elements is divisible by 2 ; Represents first and last numbers of each type ( modulo 0 and 1 ) ; Count of numbers of each type between range ; Base Cases ; Ways to form array whose sum upto i numbers modulo 2 is 0 ; Ways to form array whose sum upto i numbers modulo 2 is 1 ; Return the required count of ways ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int n , int l , int r ) { int tL = l , tR = r ; int L [ 2 ] = { 0 } , R [ 2 ] = { 0 } ; L [ l % 2 ] = l , R [ r % 2 ] = r ; l ++ , r -- ; if ( l <= tR && r >= tL ) L [ l % 2 ] = l , R [ r % 2 ] = r ; int cnt0 = 0 , cnt1 = 0 ; if ( R [ 0 ] && L [ 0 ] ) cnt0 = ( R [ 0 ] - L [ 0 ] ) / 2 + 1 ; if ( R [ 1 ] && L [ 1 ] ) cnt1 = ( R [ 1 ] - L [ 1 ] ) / 2 + 1 ; int dp [ n ] [ 2 ] ; dp [ 1 ] [ 0 ] = cnt0 ; dp [ 1 ] [ 1 ] = cnt1 ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ i ] [ 0 ] = ( cnt0 * dp [ i - 1 ] [ 0 ] + cnt1 * dp [ i - 1 ] [ 1 ] ) ; dp [ i ] [ 1 ] = ( cnt0 * dp [ i - 1 ] [ 1 ] + cnt1 * dp [ i - 1 ] [ 0 ] ) ; } return dp [ n ] [ 0 ] ; } int main ( ) { int n = 2 , l = 1 , r = 3 ; cout << countWays ( n , l , r ) ; return 0 ; }
Color N boxes using M colors such that K boxes have different color from the box on its left | CPP Program to Paint N boxes using M colors such that K boxes have color different from color of box on its left ; This function returns the required number of ways where idx is the current index and diff is number of boxes having different color from box on its left ; Base Case ; If already computed ; Either paint with same color as previous one ; Or paint with remaining ( M - 1 ) colors ; Driver code ; Multiply M since first box can be painted with any of the M colors and start solving from 2 nd box
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 1001 ; const int MOD = 998244353 ; int dp [ M ] [ M ] ; int solve ( int idx , int diff , int N , int M , int K ) { if ( idx > N ) { if ( diff == K ) return 1 ; return 0 ; } if ( dp [ idx ] [ diff ] != -1 ) return dp [ idx ] [ diff ] ; int ans = solve ( idx + 1 , diff , N , M , K ) ; ans += ( M - 1 ) * solve ( idx + 1 , diff + 1 , N , M , K ) ; return dp [ idx ] [ diff ] = ans % MOD ; } int main ( ) { int N = 3 , M = 3 , K = 0 ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << ( M * solve ( 2 , 0 , N , M , K ) ) << endl ; return 0 ; }
Maximum path sum in an Inverted triangle | SET 2 | C ++ program implementation of Max sum problem in a triangle ; Function for finding maximum sum ; Loop for bottom - up calculation ; For each element , check both elements just below the number and below left to the number add the maximum of them to it ; Return the maximum sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 3 NEW_LINE int maxPathSum ( int tri [ ] [ N ] ) { int ans = 0 ; for ( int i = N - 2 ; i >= 0 ; i -- ) { for ( int j = 0 ; j < N - i ; j ++ ) { if ( j - 1 >= 0 ) tri [ i ] [ j ] += max ( tri [ i + 1 ] [ j ] , tri [ i + 1 ] [ j - 1 ] ) ; else tri [ i ] [ j ] += tri [ i + 1 ] [ j ] ; ans = max ( ans , tri [ i ] [ j ] ) ; } } return ans ; } int main ( ) { int tri [ N ] [ N ] = { { 1 , 5 , 3 } , { 4 , 8 , 0 } , { 1 , 0 , 0 } } ; cout << maxPathSum ( tri ) ; return 0 ; }
Count no . of ordered subsets having a particular XOR value | C ++ implementation of the approach ; Returns count of ordered subsets of arr [ ] with XOR value = K ; Find maximum element in arr [ ] ; Maximum possible XOR value ; The value of dp [ i ] [ j ] [ k ] is the number of subsets of length k having XOR of their elements as j from the set arr [ 0. . . i - 1 ] ; Initializing all the values of dp [ i ] [ j ] [ k ] as 0 ; The xor of empty subset is 0 ; Fill the dp table ; The answer is the number of subsets of all lengths from set arr [ 0. . n - 1 ] having XOR of elements as k ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int subsetXOR ( int arr [ ] , int n , int K ) { int max_ele = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > max_ele ) max_ele = arr [ i ] ; int m = ( 1 << ( int ) ( log2 ( max_ele ) + 1 ) ) - 1 ; int dp [ n + 1 ] [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= m ; j ++ ) for ( int k = 0 ; k <= n ; k ++ ) dp [ i ] [ j ] [ k ] = 0 ; for ( int i = 0 ; i <= n ; i ++ ) dp [ i ] [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= m ; j ++ ) { for ( int k = 0 ; k <= n ; k ++ ) { dp [ i ] [ j ] [ k ] = dp [ i - 1 ] [ j ] [ k ] ; if ( k != 0 ) { dp [ i ] [ j ] [ k ] += k * dp [ i - 1 ] [ j ^ arr [ i - 1 ] ] [ k - 1 ] ; } } } } int ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { ans += dp [ n ] [ K ] [ i ] ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int k = 1 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << subsetXOR ( arr , n , k ) ; return 0 ; }
Possible cuts of a number such that maximum parts are divisible by 3 | C ++ program to find the maximum number of numbers divisible by 3 in large number ; This will contain the count of the splits ; This will keep sum of all successive integers , when they are indivisible by 3 ; This is the condition of finding a split ; Driver code
#include <iostream> NEW_LINE using namespace std ; int get_max_splits ( string num_string ) { int count = 0 , current_num ; int running_sum = 0 ; for ( int i = 0 ; i < num_string . length ( ) ; i ++ ) { current_num = num_string [ i ] - '0' ; running_sum += current_num ; if ( current_num % 3 == 0 || ( running_sum != 0 && running_sum % 3 == 0 ) ) { count += 1 ; running_sum = 0 ; } } return count ; } int main ( ) { cout << get_max_splits ( "12345" ) << endl ; return 0 ; }
Count of Numbers in a Range where digit d occurs exactly K times | CPP Program to find the count of numbers in a range where digit d occurs exactly K times ; states - position , count , tight , nonz ; d is required digit and K is occurrence ; This function returns the count of required numbers from 0 to num ; Last position ; 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 ] ; Nonz is true if we placed a non zero digit at the starting of the number ; At this position , number becomes smaller ; Next recursive call , also set nonz to 1 if current digit is non zero ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver Code to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 20 ; int dp [ M ] [ M ] [ 2 ] [ 2 ] ; int d , K ; int count ( int pos , int cnt , int tight , int nonz , vector < int > num ) { if ( pos == num . size ( ) ) { if ( cnt == K ) return 1 ; return 0 ; } if ( dp [ pos ] [ cnt ] [ tight ] [ nonz ] != -1 ) return dp [ pos ] [ cnt ] [ tight ] [ nonz ] ; int ans = 0 ; int limit = ( tight ? 9 : num [ pos ] ) ; for ( int dig = 0 ; dig <= limit ; dig ++ ) { int currCnt = cnt ; if ( dig == d ) { if ( d != 0 || ( ! d && nonz ) ) currCnt ++ ; } int currTight = tight ; if ( dig < num [ pos ] ) currTight = 1 ; ans += count ( pos + 1 , currCnt , currTight , nonz || ( dig != 0 ) , num ) ; } return dp [ pos ] [ cnt ] [ tight ] [ nonz ] = 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 = 11 , R = 100 ; d = 2 , K = 1 ; cout << solve ( R ) - solve ( L - 1 ) << endl ; return 0 ; }
Count of Numbers in Range where first digit is equal to last digit of the number | C ++ program to implement the above approach ; Base Case ; Calculating the last digit ; Calculating the first digit ; Drivers Code
#include <iostream> NEW_LINE using namespace std ; int solve ( int x ) { int ans = 0 , first , last , temp = x ; if ( x < 10 ) return x ; last = x % 10 ; while ( x ) { first = x % 10 ; x /= 10 ; } if ( first <= last ) ans = 9 + temp / 10 ; else ans = 8 + temp / 10 ; return ans ; } int main ( ) { int L = 2 , R = 60 ; cout << solve ( R ) - solve ( L - 1 ) << endl ; L = 1 , R = 1000 ; cout << solve ( R ) - solve ( L - 1 ) << endl ; return 0 ; }
Form N | CPP code to find minimum cost to form a N - copy string ; Returns the minimum cost to form a n - copy string Here , x -> Cost to add / remove a single character ' G ' and y -> cost to append the string to itself ; Base Case : to form a 1 - copy string we need to perform an operation of type 1 ( i . e Add ) ; Case1 . Perform a Add operation on ( i - 1 ) - copy string , Case2 . Perform a type 2 operation on ( ( i + 1 ) / 2 ) - copy string ; Case1 . Perform a Add operation on ( i - 1 ) - copy string , Case2 . Perform a type 3 operation on ( i / 2 ) - copy string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinimumCost ( int n , int x , int y ) { int * dp = new int [ n + 1 ] ; dp [ 1 ] = x ; for ( int i = 2 ; i <= n ; i ++ ) { if ( i & 1 ) { dp [ i ] = min ( dp [ i - 1 ] + x , dp [ ( i + 1 ) / 2 ] + y + x ) ; } else { dp [ i ] = min ( dp [ i - 1 ] + x , dp [ i / 2 ] + y ) ; } } return dp [ n ] ; } int main ( ) { int n = 4 , x = 2 , y = 1 ; cout << findMinimumCost ( n , x , y ) ; return 0 ; }
Minimum steps to reach any of the boundary edges of a matrix | Set 1 | C ++ program to find Minimum steps to reach any of the boundary edges of a matrix ; Function to find out minimum steps ; boundary edges reached ; already had a route through this point , hence no need to re - visit ; visiting a position ; vertically up ; horizontally right ; horizontally left ; vertically down ; minimum of every path ; Function that returns the minimum steps ; index to store the location at which you are standing ; find '2' in the matrix ; Initialize dp matrix with - 1 ; Initialize vis matrix with false ; Call function to find out minimum steps using memoization and recursion ; if not possible ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define r 4 NEW_LINE #define col 5 NEW_LINE int findMinSteps ( int mat [ r ] [ col ] , int n , int m , int dp [ r ] [ col ] , bool vis [ r ] [ col ] ) { if ( n == 0 || m == 0 || n == ( r - 1 ) || m == ( col - 1 ) ) { return 0 ; } if ( dp [ n ] [ m ] != -1 ) return dp [ n ] [ m ] ; vis [ n ] [ m ] = true ; int ans1 , ans2 , ans3 , ans4 ; ans1 = ans2 = ans3 = ans4 = 1e9 ; if ( mat [ n - 1 ] [ m ] == 0 ) { if ( ! vis [ n - 1 ] [ m ] ) ans1 = 1 + findMinSteps ( mat , n - 1 , m , dp , vis ) ; } if ( mat [ n ] [ m + 1 ] == 0 ) { if ( ! vis [ n ] [ m + 1 ] ) ans2 = 1 + findMinSteps ( mat , n , m + 1 , dp , vis ) ; } if ( mat [ n ] [ m - 1 ] == 0 ) { if ( ! vis [ n ] [ m - 1 ] ) ans3 = 1 + findMinSteps ( mat , n , m - 1 , dp , vis ) ; } if ( mat [ n + 1 ] [ m ] == 0 ) { if ( ! vis [ n + 1 ] [ m ] ) ans4 = 1 + findMinSteps ( mat , n + 1 , m , dp , vis ) ; } dp [ n ] [ m ] = min ( ans1 , min ( ans2 , min ( ans3 , ans4 ) ) ) ; return dp [ n ] [ m ] ; } int minimumSteps ( int mat [ r ] [ col ] , int n , int m ) { int twox = -1 ; int twoy = -1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( mat [ i ] [ j ] == 2 ) { twox = i ; twoy = j ; break ; } } if ( twox != -1 ) break ; } int dp [ r ] [ col ] ; memset ( dp , -1 , sizeof dp ) ; bool vis [ r ] [ col ] ; memset ( vis , false , sizeof vis ) ; int res = findMinSteps ( mat , twox , twoy , dp , vis ) ; if ( res >= 1e9 ) return -1 ; else return res ; } int main ( ) { int mat [ r ] [ col ] = { { 1 , 1 , 1 , 0 , 1 } , { 1 , 0 , 2 , 0 , 1 } , { 0 , 0 , 1 , 0 , 1 } , { 1 , 0 , 1 , 1 , 0 } } ; cout << minimumSteps ( mat , r , col ) ; }
Count the number of special permutations | C ++ program to count the number of required permutations ; Function to return the number of ways to choose r objects out of n objects ; Function to return the number of derangements of n ; Function to return the required number of permutations ; Ways to choose i indices from n indices ; Dearangements of ( n - i ) indices ; Driver Code to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE int nCr ( int n , int r ) { int ans = 1 ; if ( r > n - r ) r = n - r ; for ( int i = 0 ; i < r ; i ++ ) { ans *= ( n - i ) ; ans /= ( i + 1 ) ; } return ans ; } int countDerangements ( int n ) { int der [ n + 1 ] ; der [ 0 ] = 1 ; der [ 1 ] = 0 ; der [ 2 ] = 1 ; for ( int i = 3 ; i <= n ; i ++ ) der [ i ] = ( i - 1 ) * ( der [ i - 1 ] + der [ i - 2 ] ) ; return der [ n ] ; } ll countPermutations ( int n , int k ) { ll ans = 0 ; for ( int i = n - k ; i <= n ; i ++ ) { int ways = nCr ( n , i ) ; ans += ways * countDerangements ( n - i ) ; } return ans ; } int main ( ) { int n = 5 , k = 3 ; cout << countPermutations ( n , k ) ; return 0 ; }
Paths with maximum number of ' a ' from ( 1 , 1 ) to ( X , Y ) vertically or horizontally | C ++ program to find paths with maximum number of ' a ' from ( 1 , 1 ) to ( X , Y ) vertically or horizontally ; Function to answer queries ; Iterate till query ; Decrease to get 0 - based indexing ; Print answer ; Function that pre - computes the dp array ; Check fo the first character ; Iterate in row and columns ; If not first row or not first column ; Not first row ; Not first column ; If it is not ' a ' then increase by 1 ; Driver code ; character N X N array ; queries ; number of queries ; function call to pre - compute ; function call to answer every query
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int n = 3 ; int dp [ n ] [ n ] ; void answerQueries ( pair < int , int > queries [ ] , int q ) { for ( int i = 0 ; i < q ; i ++ ) { int x = queries [ i ] . first ; x -- ; int y = queries [ i ] . second ; y -- ; cout << dp [ x ] [ y ] << endl ; } } void pre_compute ( char a [ ] [ n ] ) { if ( a [ 0 ] [ 0 ] == ' a ' ) dp [ 0 ] [ 0 ] = 0 ; else dp [ 0 ] [ 0 ] = 1 ; for ( int row = 0 ; row < n ; row ++ ) { for ( int col = 0 ; col < n ; col ++ ) { if ( row != 0 col != 0 ) dp [ row ] [ col ] = INT_MAX ; if ( row != 0 ) { dp [ row ] [ col ] = min ( dp [ row ] [ col ] , dp [ row - 1 ] [ col ] ) ; } if ( col != 0 ) { dp [ row ] [ col ] = min ( dp [ row ] [ col ] , dp [ row ] [ col - 1 ] ) ; } if ( a [ row ] [ col ] != ' a ' && ( row != 0 col != 0 ) ) dp [ row ] [ col ] += 1 ; } } } int main ( ) { char a [ ] [ 3 ] = { { ' a ' , ' b ' , ' a ' } , { ' a ' , ' c ' , ' d ' } , { ' b ' , ' a ' , ' b ' } } ; pair < int , int > queries [ ] = { { 1 , 3 } , { 3 , 3 } } ; int q = 2 ; pre_compute ( a ) ; answerQueries ( queries , q ) ; }
Ways to place K bishops on an NÃ — N chessboard so that no two attack | CPP implementation of the approach ; returns the number of squares in diagonal i ; returns the number of ways to fill a n * n chessboard with k bishops so that no two bishops attack each other . ; return 0 if the number of valid places to be filled is less than the number of bishops ; dp table to store the values ; Setting the base conditions ; calculate the required number of ways ; stores the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int squares ( int i ) { if ( ( i & 1 ) == 1 ) return i / 4 * 2 + 1 ; else return ( i - 1 ) / 4 * 2 + 2 ; } long bishop_placements ( int n , int k ) { if ( k > 2 * n - 1 ) return 0 ; long dp [ n * 2 ] [ k + 1 ] ; for ( int i = 0 ; i < n * 2 ; i ++ ) { for ( int j = 0 ; j < k + 1 ; j ++ ) { dp [ i ] [ j ] = 0 ; } } for ( int i = 0 ; i < n * 2 ; i ++ ) dp [ i ] [ 0 ] = 1 ; dp [ 1 ] [ 1 ] = 1 ; for ( int i = 2 ; i < n * 2 ; i ++ ) { for ( int j = 1 ; j <= k ; j ++ ) { dp [ i ] [ j ] = dp [ i - 2 ] [ j ] + dp [ i - 2 ] [ j - 1 ] * ( squares ( i ) - j + 1 ) ; } } long ans = 0 ; for ( int i = 0 ; i <= k ; i ++ ) { ans += dp [ n * 2 - 1 ] [ i ] * dp [ n * 2 - 2 ] [ k - i ] ; } return ans ; } int main ( ) { int n = 2 ; int k = 2 ; long ans = bishop_placements ( n , k ) ; cout << ( ans ) ; }
Number of ways to partition a string into two balanced subsequences | C ++ implementation of the above approach ; For maximum length of input string ; Declaring the DP table ; Declaring the prefix array ; Function to calculate the number of valid assignments ; Return 1 if X is balanced . ; Increment the count if it an opening bracket ; Decrement the count if it a closing bracket ; Driver code ; Initializing the DP table ; Creating the prefix array ; Initial value for c_x and c_y is zero
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 10 ; int F [ MAX ] [ MAX ] ; int C [ MAX ] ; int noOfAssignments ( string & S , int & n , int i , int c_x ) { if ( F [ i ] [ c_x ] != -1 ) return F [ i ] [ c_x ] ; if ( i == n ) { F [ i ] [ c_x ] = ! c_x ; return F [ i ] [ c_x ] ; } int c_y = C [ i ] - c_x ; if ( S [ i ] == ' ( ' ) { F [ i ] [ c_x ] = noOfAssignments ( S , n , i + 1 , c_x + 1 ) + noOfAssignments ( S , n , i + 1 , c_x ) ; return F [ i ] [ c_x ] ; } F [ i ] [ c_x ] = 0 ; if ( c_x ) F [ i ] [ c_x ] += noOfAssignments ( S , n , i + 1 , c_x - 1 ) ; if ( c_y ) F [ i ] [ c_x ] += noOfAssignments ( S , n , i + 1 , c_x ) ; return F [ i ] [ c_x ] ; } int main ( ) { string S = " ( ) " ; int n = S . length ( ) ; memset ( F , -1 , sizeof ( F ) ) ; C [ 0 ] = 0 ; for ( int i = 0 ; i < n ; ++ i ) if ( S [ i ] == ' ( ' ) C [ i + 1 ] = C [ i ] + 1 ; else C [ i + 1 ] = C [ i ] - 1 ; cout << noOfAssignments ( S , n , 0 , 0 ) ; return 0 ; }
Minimum sum falling path in a NxN grid | C ++ Program to minimum required sum ; Function to return minimum path falling sum ; R = Row and C = Column We begin from second last row and keep adding maximum sum . ; best = min ( A [ R + 1 ] [ C - 1 ] , A [ R + 1 ] [ C ] , A [ R + 1 ] [ C + 1 ] ) ; Driver program ; function to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int n = 3 ; int minFallingPathSum ( int ( & A ) [ n ] [ n ] ) { for ( int R = n - 2 ; R >= 0 ; -- R ) { for ( int C = 0 ; C < n ; ++ C ) { int best = A [ R + 1 ] [ C ] ; if ( C > 0 ) best = min ( best , A [ R + 1 ] [ C - 1 ] ) ; if ( C + 1 < n ) best = min ( best , A [ R + 1 ] [ C + 1 ] ) ; A [ R ] [ C ] = A [ R ] [ C ] + best ; } } int ans = INT_MAX ; for ( int i = 0 ; i < n ; ++ i ) ans = min ( ans , A [ 0 ] [ i ] ) ; return ans ; } int main ( ) { int A [ n ] [ n ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; cout << minFallingPathSum ( A ) ; return 0 ; }
Find the maximum sum of Plus shape pattern in a 2 | C ++ program to find the maximum value of a + shaped pattern in 2 - D array ; Function to return maximum Plus value ; Initializing answer with the minimum value ; Initializing all four arrays ; Initializing left and up array . ; Initializing right and down array . ; calculating value of maximum Plus ( + ) sign ; Driver code ; Function call to find maximum value
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100 NEW_LINE const int n = 3 , m = 4 ; int maxPlus ( int ( & arr ) [ n ] [ m ] ) { int ans = INT_MIN ; int left [ N ] [ N ] , right [ N ] [ N ] , up [ N ] [ N ] , down [ N ] [ N ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { left [ i ] [ j ] = max ( 0LL , ( j ? left [ i ] [ j - 1 ] : 0LL ) ) + arr [ i ] [ j ] ; up [ i ] [ j ] = max ( 0LL , ( i ? up [ i - 1 ] [ j ] : 0LL ) ) + arr [ i ] [ j ] ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { right [ i ] [ j ] = max ( 0LL , ( j + 1 == m ? 0LL : right [ i ] [ j + 1 ] ) ) + arr [ i ] [ j ] ; down [ i ] [ j ] = max ( 0LL , ( i + 1 == n ? 0LL : down [ i + 1 ] [ j ] ) ) + arr [ i ] [ j ] ; } } for ( int i = 1 ; i < n - 1 ; ++ i ) for ( int j = 1 ; j < m - 1 ; ++ j ) ans = max ( ans , up [ i - 1 ] [ j ] + down [ i + 1 ] [ j ] + left [ i ] [ j - 1 ] + right [ i ] [ j + 1 ] + arr [ i ] [ j ] ) ; return ans ; } int main ( ) { int arr [ n ] [ m ] = { { 1 , 1 , 1 , 1 } , { -6 , 1 , 1 , -4 } , { 1 , 1 , 1 , 1 } } ; cout << maxPlus ( arr ) ; return 0 ; }
Total number of different staircase that can made from N boxes | C ++ program to find the total number of different staircase that can made from N boxes ; Function to find the total number of different staircase that can made from N boxes ; DP table , there are two states . First describes the number of boxes and second describes the step ; Initialize all the elements of the table to zero ; Base case ; When step is equal to 2 ; When step is greater than 2 ; Count the total staircase from all the steps ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int countStaircases ( int N ) { int memo [ N + 5 ] [ N + 5 ] ; for ( int i = 0 ; i <= N ; i ++ ) { for ( int j = 0 ; j <= N ; j ++ ) { memo [ i ] [ j ] = 0 ; } } memo [ 3 ] [ 2 ] = memo [ 4 ] [ 2 ] = 1 ; for ( int i = 5 ; i <= N ; i ++ ) { for ( int j = 2 ; j <= i ; j ++ ) { if ( j == 2 ) { memo [ i ] [ j ] = memo [ i - j ] [ j ] + 1 ; } else { memo [ i ] [ j ] = memo [ i - j ] [ j ] + memo [ i - j ] [ j - 1 ] ; } } } int answer = 0 ; for ( int i = 1 ; i <= N ; i ++ ) answer = answer + memo [ N ] [ i ] ; return answer ; } int main ( ) { int N = 7 ; cout << countStaircases ( N ) ; return 0 ; }
Find maximum points which can be obtained by deleting elements from array | C ++ program to find maximum cost after deleting all the elements form the array ; function to return maximum cost obtained ; find maximum element of the array . ; initialize count of all elements to zero . ; calculate frequency of all elements of array . ; stores cost of deleted elements . ; selecting minimum range from L and R . ; finds upto which elements are to be deleted when element num is selected . ; get maximum when selecting element num or not . ; Driver program ; size of array ; function call to find maximum cost
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxCost ( int a [ ] , int n , int l , int r ) { int mx = 0 , k ; for ( int i = 0 ; i < n ; ++ i ) mx = max ( mx , a [ i ] ) ; int count [ mx + 1 ] ; memset ( count , 0 , sizeof ( count ) ) ; for ( int i = 0 ; i < n ; i ++ ) count [ a [ i ] ] ++ ; int res [ mx + 1 ] ; res [ 0 ] = 0 ; l = min ( l , r ) ; for ( int num = 1 ; num <= mx ; num ++ ) { k = max ( num - l - 1 , 0 ) ; res [ num ] = max ( res [ num - 1 ] , num * count [ num ] + res [ k ] ) ; } return res [ mx ] ; } int main ( ) { int a [ ] = { 2 , 1 , 2 , 3 , 2 , 2 , 1 } , l = 1 , r = 1 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maxCost ( a , n , l , r ) ; return 0 ; }
Count the number of ways to traverse a Matrix | C ++ program using recursive solution to count number of ways to reach mat [ m - 1 ] [ n - 1 ] from mat [ 0 ] [ 0 ] in a matrix mat [ ] [ ] ; Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Return 1 if it is the first row or first column ; Recursively find the no of way to reach the last cell . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPaths ( int m , int n ) { if ( m == 1 n == 1 ) return 1 ; return countPaths ( m - 1 , n ) + countPaths ( m , n - 1 ) ; } int main ( ) { int n = 5 ; int m = 5 ; cout << countPaths ( n , m ) ; return 0 ; }
Count the number of ways to traverse a Matrix | A simple recursive solution to count number of ways to reach mat [ m - 1 ] [ n - 1 ] from mat [ 0 ] [ 0 ] in a matrix mat [ ] [ ] ; Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPaths ( int m , int n ) { int dp [ m + 1 ] [ n + 1 ] ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( i == 1 j == 1 ) dp [ i ] [ j ] = 1 ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] ; } } return dp [ m ] [ n ] ; } int main ( ) { int n = 5 ; int m = 5 ; cout << countPaths ( n , m ) ; return 0 ; }
Minimum number of palindromes required to express N as a sum | Set 1 | C ++ implementation of above approach ; Declaring the DP table as global variable ; 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 elements in a sorted array A [ i . . j ] such that their sum is N ; Function to find the minimum number of palindromes that N can be expressed as a sum of ; Getting the list of all palindromes upto N ; Sorting the list of palindromes ; Initializing the DP table ; Returning the required value ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < long long > > dp ; 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 ; } long long minimumSubsetSize ( vector < int > & A , int i , int j , int N ) { if ( ! N ) return 0 ; if ( i > j A [ i ] > N ) return INT_MAX ; if ( dp [ i ] [ N ] ) return dp [ i ] [ N ] ; dp [ i ] [ N ] = min ( 1 + minimumSubsetSize ( A , i + 1 , j , N - A [ i ] ) , minimumSubsetSize ( A , i + 1 , j , N ) ) ; return dp [ i ] [ N ] ; } int minimumNoOfPalindromes ( int N ) { vector < int > palindromes = generatePalindromes ( N ) ; sort ( palindromes . begin ( ) , palindromes . end ( ) ) ; dp = vector < vector < long long > > ( palindromes . size ( ) , vector < long long > ( N + 1 , 0 ) ) ; return minimumSubsetSize ( palindromes , 0 , palindromes . size ( ) - 1 , N ) ; } int main ( ) { int N = 65 ; cout << minimumNoOfPalindromes ( N ) ; return 0 ; }
Number of ways a convex polygon of n + 2 sides can split into triangles by connecting vertices | C ++ program to find the nth catalan number ; Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long int binomialCoeff ( unsigned int n , unsigned int k ) { unsigned long int res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } unsigned long int catalan ( unsigned int n ) { unsigned long int c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } int main ( ) { int n = 3 ; cout << catalan ( n ) << endl ; return 0 ; }
Alternate Fibonacci Numbers | Alternate Fibonacci Series using Dynamic Programming ; 0 th and 1 st number of the series are 0 and 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void alternateFib ( int n ) { if ( n < 0 ) return ; int f1 = 0 ; int f2 = 1 ; cout << f1 << " ▁ " ; for ( int i = 2 ; i <= n ; i ++ ) { int f3 = f2 + f1 ; if ( i % 2 == 0 ) cout << f3 << " ▁ " ; f1 = f2 ; f2 = f3 ; } } int main ( ) { int N = 15 ; alternateFib ( N ) ; return 0 ; }
Number of ways to form an array with distinct adjacent elements | C ++ program to count the number of ways to form arrays of N numbers such that the first and last numbers are fixed and all consecutive numbers are distinct ; Returns the total ways to form arrays such that every consecutive element is different and each element except the first and last can take values from 1 to M ; define the dp [ ] [ ] array ; if the first element is 1 ; there is only one way to place a 1 at the first index ; the value at first index needs to be 1 , thus there is no way to place a non - one integer ; if the first element was 1 then at index 1 , only non one integer can be placed thus there are M - 1 ways to place a non one integer at index 2 and 0 ways to place a 1 at the 2 nd index ; Else there is one way to place a one at index 2 and if a non one needs to be placed here , there are ( M - 2 ) options , i . e neither the element at this index should be 1 , neither should it be equal to the previous element ; Build the dp array in bottom up manner ; f ( i , one ) = f ( i - 1 , non - one ) ; f ( i , non - one ) = f ( i - 1 , one ) * ( M - 1 ) + f ( i - 1 , non - one ) * ( M - 2 ) ; last element needs to be one , so return dp [ n - 1 ] [ 0 ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int totalWays ( int N , int M , int X ) { int dp [ N + 1 ] [ 2 ] ; if ( X == 1 ) { dp [ 0 ] [ 0 ] = 1 ; } else { dp [ 0 ] [ 1 ] = 0 ; } if ( X == 1 ) { dp [ 1 ] [ 0 ] = 0 ; dp [ 1 ] [ 1 ] = M - 1 ; } else { dp [ 1 ] [ 0 ] = 1 ; dp [ 1 ] [ 1 ] = ( M - 2 ) ; } for ( int i = 2 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 1 ] ; dp [ i ] [ 1 ] = dp [ i - 1 ] [ 0 ] * ( M - 1 ) + dp [ i - 1 ] [ 1 ] * ( M - 2 ) ; } return dp [ N - 1 ] [ 0 ] ; } int main ( ) { int N = 4 , M = 3 , X = 2 ; cout << totalWays ( N , M , X ) << endl ; return 0 ; }
Memoization ( 1D , 2D and 3D ) | C ++ program to find the Nth term of Fibonacci series ; Fibonacci Series using Recursion ; Base case ; recursive calls ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fib ( int n ) { if ( n <= 1 ) return n ; return fib ( n - 1 ) + fib ( n - 2 ) ; } int main ( ) { int n = 6 ; printf ( " % d " , fib ( n ) ) ; return 0 ; }
Memoization ( 1D , 2D and 3D ) | CPP program to find the Nth term of Fibonacci series ; Fibonacci Series using memoized Recursion ; base case ; if fib ( n ) has already been computed we do not do further recursive calls and hence reduce the number of repeated work ; store the computed value of fib ( n ) in an array term at index n to so that it does not needs to be precomputed again ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int term [ 1000 ] ; int fib ( int n ) { if ( n <= 1 ) return n ; if ( term [ n ] != 0 ) return term [ n ] ; else { term [ n ] = fib ( n - 1 ) + fib ( n - 2 ) ; return term [ n ] ; } } int main ( ) { int n = 6 ; printf ( " % d " , fib ( n ) ) ; return 0 ; }
Memoization ( 1D , 2D and 3D ) | A Naive recursive implementation of LCS problem ; Utility function to get max of 2 integers ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE int max ( int a , int b ) ; int max ( int a , int b ) { return ( a > b ) ? a : b ; } int lcs ( char * X , char * 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 ( ) { char X [ ] = " AGGTAB " ; char Y [ ] = " GXTXAYB " ; int m = strlen ( X ) ; int n = strlen ( Y ) ; printf ( " Length ▁ of ▁ LCS ▁ is ▁ % dn " , lcs ( X , Y , m , n ) ) ; return 0 ; }
Smallest number with given sum of digits and sum of square of digits | CPP program to find the Smallest number with given sum of digits and sum of square of digits ; Top down dp to find minimum number of digits with given sum of dits a and sum of square of digits as b ; Invalid condition ; Number of digits satisfied ; Memoization ; Initialize ans as maximum as we have to find the minimum number of digits ; Check for all possible combinations of digits ; recurrence call ; If the combination of digits cannot give sum as a and sum of square of digits as b ; Returns the minimum number of digits ; Function to print the digits that gives sum as a and sum of square of digits as b ; initialize the dp array as - 1 ; base condition ; function call to get the minimum number of digits ; When there does not exists any number ; Printing the digits from the most significant digit ; Trying all combinations ; checking conditions for minimum digits ; Driver Code ; Function call to print the smallest number
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 901 ] [ 8101 ] ; int minimumNumberOfDigits ( int a , int b ) { if ( a > b a < 0 b < 0 a > 900 b > 8100 ) return -1 ; if ( a == 0 && b == 0 ) return 0 ; if ( dp [ a ] [ b ] != -1 ) return dp [ a ] [ b ] ; int ans = 101 ; for ( int i = 9 ; i >= 1 ; i -- ) { int k = minimumNumberOfDigits ( a - i , b - ( i * i ) ) ; if ( k != -1 ) ans = min ( ans , k + 1 ) ; } return dp [ a ] [ b ] = ans ; } void printSmallestNumber ( int a , int b ) { memset ( dp , -1 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = 0 ; int k = minimumNumberOfDigits ( a , b ) ; if ( k == -1 k > 100 ) cout << " - 1" ; else { while ( a > 0 && b > 0 ) { for ( int i = 1 ; i <= 9 ; i ++ ) { if ( a >= i && b >= i * i && 1 + dp [ a - i ] [ b - i * i ] == dp [ a ] [ b ] ) { cout << i ; a -= i ; b -= i * i ; break ; } } } } } int main ( ) { int a = 18 , b = 162 ; printSmallestNumber ( a , b ) ; }
Sum of product of consecutive Binomial Coefficients | CPP Program to find sum of product of consecutive Binomial Coefficient . ; Find the binomial coefficient up to 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 . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE 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 sumOfproduct ( int n ) { return binomialCoeff ( 2 * n , n - 1 ) ; } int main ( ) { int n = 3 ; cout << sumOfproduct ( n ) << endl ; return 0 ; }
Check if array sum can be made K by three operations on it | C ++ Program to find if Array can have a sum of K by applying three types of possible operations on it ; Check if it is possible to achieve a sum with three operation allowed . ; If sum is negative . ; If going out of bound . ; If sum is achieved . ; If the current state is not evaluated yet . ; Replacing element with negative value of the element . ; Substracting index number from the element . ; Adding index number to the element . ; Wrapper Function ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE int check ( int i , int sum , int n , int k , int a [ ] , int dp [ MAX ] [ MAX ] ) { if ( sum <= 0 ) return false ; if ( i >= n ) { if ( sum == k ) return true ; return false ; } if ( dp [ i ] [ sum ] != -1 ) return dp [ i ] [ sum ] ; dp [ i ] [ sum ] = check ( i + 1 , sum - 2 * a [ i ] , n , k , a , dp ) || check ( i + 1 , sum , n , k , a , dp ) ; dp [ i ] [ sum ] = check ( i + 1 , sum - ( i + 1 ) , n , k , a , dp ) || dp [ i ] [ sum ] ; dp [ i ] [ sum ] = check ( i + 1 , sum + i + 1 , n , k , a , dp ) || dp [ i ] [ sum ] ; return dp [ i ] [ sum ] ; } bool wrapper ( int n , int k , int a [ ] ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += a [ i ] ; int dp [ MAX ] [ MAX ] ; memset ( dp , -1 , sizeof ( dp ) ) ; return check ( 0 , sum , n , k , a , dp ) ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 4 } ; int n = 4 , k = 5 ; ( wrapper ( n , k , a ) ? ( cout << " Yes " ) : ( cout << " No " ) ) ; return 0 ; }
Print Fibonacci sequence using 2 variables | Simple CPP Program to print Fibonacci sequence ; Driver code
#include <iostream> NEW_LINE using std :: cout ; void fib ( int n ) { int a = 0 , b = 1 , c ; if ( n >= 0 ) cout << a << " ▁ " ; if ( n >= 1 ) cout << b << " ▁ " ; for ( int i = 2 ; i <= n ; i ++ ) { c = a + b ; cout << c << " ▁ " ; a = b ; b = c ; } } int main ( ) { fib ( 9 ) ; return 0 ; }
Maximum sum increasing subsequence from a prefix and a given element after prefix is must | C ++ program to find maximum sum increasing subsequence till i - th index and including k - th index . ; Initializing the first row of the dp [ ] [ ] . ; Creating the dp [ ] [ ] matrix . ; To calculate for i = 4 and k = 6. ; Driver code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll pre_compute ( ll a [ ] , ll n , ll index , ll k ) { ll dp [ n ] [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > a [ 0 ] ) dp [ 0 ] [ i ] = a [ i ] + a [ 0 ] ; else dp [ 0 ] [ i ] = a [ i ] ; } for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( a [ j ] > a [ i ] && j > i ) { if ( dp [ i - 1 ] [ i ] + a [ j ] > dp [ i - 1 ] [ j ] ) dp [ i ] [ j ] = dp [ i - 1 ] [ i ] + a [ j ] ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } else dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } } return dp [ index ] [ k ] ; } int main ( ) { ll a [ ] = { 1 , 101 , 2 , 3 , 100 , 4 , 5 } ; ll n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; ll index = 4 , k = 6 ; printf ( " % lld " , pre_compute ( a , n , index , k ) ) ; 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 ( 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 ) { int S [ n + 1 ] ; S [ 0 ] = 0 ; S [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( i % 2 == 0 ) S [ i ] = 4 * S [ i / 2 ] ; else S [ i ] = 4 * S [ i / 2 ] + 1 ; } return S [ n ] ; } 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 ; }
Longest Common Substring ( Space optimized DP solution ) | Space optimized CPP implementation of longest common substring . ; Function to find longest common substring . ; Find length of both the strings . ; Variable to store length of longest common substring . ; Matrix to store result of two consecutive rows at a time . ; Variable to represent which row of matrix is current row . ; For a particular value of i and j , len [ currRow ] [ j ] stores length of longest common substring in string X [ 0. . i ] and Y [ 0. . j ] . ; Make current row as previous row and previous row as new current row . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LCSubStr ( string X , string Y ) { int m = X . length ( ) ; int n = Y . length ( ) ; int result = 0 ; int len [ 2 ] [ n ] ; int currRow = 0 ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) { len [ currRow ] [ j ] = 0 ; } else if ( X [ i - 1 ] == Y [ j - 1 ] ) { len [ currRow ] [ j ] = len [ 1 - currRow ] [ j - 1 ] + 1 ; result = max ( result , len [ currRow ] [ j ] ) ; } else { len [ currRow ] [ j ] = 0 ; } } currRow = 1 - currRow ; } return result ; } int main ( ) { string X = " GeeksforGeeks " ; string Y = " GeeksQuiz " ; cout << LCSubStr ( X , Y ) ; return 0 ; }
Minimal moves to form a string by adding characters or appending string itself | CPP program to print the Minimal moves to form a string by appending string and adding characters ; function to return the minimal number of moves ; initializing dp [ i ] to INT_MAX ; initialize both strings to null ; base case ; check if it can be appended ; addition of character takes one step ; appending takes 1 step , and we directly reach index i * 2 + 1 after appending so the number of steps is stord in i * 2 + 1 ; Driver Code ; function call to return minimal number of moves
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimalSteps ( string s , int n ) { int dp [ n ] ; for ( int i = 0 ; i < n ; i ++ ) dp [ i ] = INT_MAX ; string s1 = " " , s2 = " " ; dp [ 0 ] = 1 ; s1 += s [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { s1 += s [ i ] ; s2 = s . substr ( i + 1 , i + 1 ) ; dp [ i ] = min ( dp [ i ] , dp [ i - 1 ] + 1 ) ; if ( s1 == s2 ) dp [ i * 2 + 1 ] = min ( dp [ i ] + 1 , dp [ i * 2 + 1 ] ) ; } return dp [ n - 1 ] ; } int main ( ) { string s = " aaaaaaaa " ; int n = s . length ( ) ; cout << minimalSteps ( s , n ) ; return 0 ; }
Check if any valid sequence is divisible by M | C ++ program for the above approach ; Function to check if any valid sequence is divisible by M ; DEclare mod array ; Calculate the mod array ; Check if sum is divisible by M ; Check if sum is not divisible by 2 ; Remove the first element from the ModArray since it is not possible to place minus on the first element ; Decrease the size of array ; Sort the array ; Loop until the pointer cross each other ; Check if sum becomes equal ; Increase and decrease the pointer accordingly ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void func ( int n , int m , int A [ ] ) { vector < int > ModArray ( n ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ModArray [ i ] = A [ i ] % m ; sum += ModArray [ i ] ; } sum = sum % m ; if ( sum % m == 0 ) { cout << " True " ; return ; } if ( sum % 2 != 0 ) { cout << " False " ; } else { ModArray . erase ( ModArray . begin ( ) ) ; int i = 0 ; int j = ModArray . size ( ) - 1 ; sort ( ModArray . begin ( ) , ModArray . end ( ) ) ; sum = sum / 2 ; int i1 , i2 ; while ( i <= j ) { int s = ModArray [ i ] + ModArray [ j ] ; if ( s == sum ) { i1 = i ; i2 = j ; cout << " True " ; break ; } else if ( s > sum ) j -- ; else i ++ ; } } } int main ( ) { int m = 2 ; int a [ ] = { 1 , 3 , 9 } ; int n = sizeof a / sizeof a [ 0 ] ; func ( n , m , a ) ; }
Golomb sequence | C ++ Program to find first n terms of Golomb sequence . ; Print the first n term of Golomb Sequence ; base cases ; Finding and printing first n terms of Golomb Sequence . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printGolomb ( int n ) { int dp [ n + 1 ] ; dp [ 1 ] = 1 ; cout << dp [ 1 ] << " ▁ " ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ i ] = 1 + dp [ i - dp [ dp [ i - 1 ] ] ] ; cout << dp [ i ] << " ▁ " ; } } int main ( ) { int n = 9 ; printGolomb ( n ) ; return 0 ; }
Balanced expressions such that given positions have opening brackets | CPP code to find number of ways of arranging bracket with proper expressions ; function to calculate the number of proper bracket sequence ; hash array to mark the positions of opening brackets ; dp 2d array ; mark positions in hash array ; first position marked as 1 ; iterate and formulate the recurrences ; if position has a opening bracket ; return answer ; driver code ; positions where opening braces will be placed
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 1000 NEW_LINE long long arrangeBraces ( int n , int pos [ ] , int k ) { bool h [ N ] ; int dp [ N ] [ N ] ; memset ( h , 0 , sizeof h ) ; memset ( dp , 0 , sizeof dp ) ; for ( int i = 0 ; i < k ; i ++ ) h [ pos [ i ] ] = 1 ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= 2 * n ; i ++ ) { for ( int j = 0 ; j <= 2 * n ; j ++ ) { if ( h [ i ] ) { if ( j != 0 ) dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = 0 ; } else { if ( j != 0 ) dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j + 1 ] ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j + 1 ] ; } } } return dp [ 2 * n ] [ 0 ] ; } int main ( ) { int n = 3 ; int pos [ ] = { 2 } ; int k = sizeof ( pos ) / sizeof ( pos [ 0 ] ) ; cout << arrangeBraces ( n , pos , k ) ; return 0 ; }
Maximum difference of zeros and ones in binary string | Set 2 ( O ( n ) time ) | CPP Program to find the length of substring with maximum difference of zeros and ones in binary string . ; Returns the length of substring with maximum difference of zeroes and ones in binary string ; traverse a binary string from left to right ; add current value to the current_sum according to the Character if it ' s ▁ ' 0 ' add 1 else -1 ; update maximum sum ; return - 1 if string does not contain any zero that means all ones otherwise max_sum ; Driven Program
#include <iostream> NEW_LINE using namespace std ; int findLength ( string str , int n ) { int current_sum = 0 ; int max_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { current_sum += ( str [ i ] == '0' ? 1 : -1 ) ; if ( current_sum < 0 ) current_sum = 0 ; max_sum = max ( current_sum , max_sum ) ; } return max_sum == 0 ? -1 : max_sum ; } int main ( ) { string s = "11000010001" ; int n = 11 ; cout << findLength ( s , n ) << endl ; return 0 ; }
Number of decimal numbers of length k , that are strict monotone | CPP program to count numbers of k digits that are strictly monotone . ; DP [ i ] [ j ] is going to store monotone numbers of length i + 1 considering j + 1 digits ( 1 , 2 , 3 , . .9 ) ; Unit length numbers ; Building dp [ ] in bottom up ; Driver code
#include <cstring> NEW_LINE #include <iostream> NEW_LINE int static const DP_s = 9 ; int getNumStrictMonotone ( int len ) { int DP [ len ] [ DP_s ] ; memset ( DP , 0 , sizeof ( DP ) ) ; for ( int i = 0 ; i < DP_s ; ++ i ) DP [ 0 ] [ i ] = i + 1 ; for ( int i = 1 ; i < len ; ++ i ) for ( int j = 1 ; j < DP_s ; ++ j ) DP [ i ] [ j ] = DP [ i - 1 ] [ j - 1 ] + DP [ i ] [ j - 1 ] ; return DP [ len - 1 ] [ DP_s - 1 ] ; } int main ( ) { std :: cout << getNumStrictMonotone ( 2 ) ; return 0 ; }
Count ways to divide circle using N non | cpp code to count ways to divide circle using N non - intersecting chords . ; n = no of points required ; dp array containing the sum ; returning the required number ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int chordCnt ( int A ) { int n = 2 * A ; int dpArray [ n + 1 ] = { 0 } ; dpArray [ 0 ] = 1 ; dpArray [ 2 ] = 1 ; for ( int i = 4 ; i <= n ; i += 2 ) { for ( int j = 0 ; j < i - 1 ; j += 2 ) { dpArray [ i ] += ( dpArray [ j ] * dpArray [ i - 2 - j ] ) ; } } return dpArray [ n ] ; } int main ( ) { int N ; N = 2 ; cout << chordCnt ( N ) << ' ' ; N = 1 ; cout << chordCnt ( N ) << ' ' ; N = 4 ; cout << chordCnt ( N ) << ' ' ; return 0 ; }
Check for possible path in 2D matrix | C ++ program to find if there is path from top left to right bottom ; to find the path from top left to bottom right ; set arr [ 0 ] [ 0 ] = 1 ; Mark reachable ( from top left ) nodes in first row and first column . ; Mark reachable nodes in remaining matrix . ; return yes if right bottom index is 1 ; Driver Code ; Given array ; path from arr [ 0 ] [ 0 ] to arr [ row ] [ col ]
#include <iostream> NEW_LINE using namespace std ; #define row 5 NEW_LINE #define col 5 NEW_LINE bool isPath ( int arr [ row ] [ col ] ) { arr [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i < row ; i ++ ) if ( arr [ i ] [ 0 ] != -1 ) arr [ i ] [ 0 ] = arr [ i - 1 ] [ 0 ] ; for ( int j = 1 ; j < col ; j ++ ) if ( arr [ 0 ] [ j ] != -1 ) arr [ 0 ] [ j ] = arr [ 0 ] [ j - 1 ] ; for ( int i = 1 ; i < row ; i ++ ) for ( int j = 1 ; j < col ; j ++ ) if ( arr [ i ] [ j ] != -1 ) arr [ i ] [ j ] = max ( arr [ i ] [ j - 1 ] , arr [ i - 1 ] [ j ] ) ; return ( arr [ row - 1 ] [ col - 1 ] == 1 ) ; } int main ( ) { int arr [ row ] [ col ] = { { 0 , 0 , 0 , -1 , 0 } , { -1 , 0 , 0 , -1 , -1 } , { 0 , 0 , 0 , -1 , 0 } , { -1 , 0 , -1 , 0 , -1 } , { 0 , 0 , -1 , 0 , 0 } } ; if ( isPath ( arr ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
NewmanΓ’ β‚¬β€œ ShanksΓ’ β‚¬β€œ Williams prime | CPP Program to find NewmanaShanksaWilliams prime ; return nth NewmanaShanksaWilliams prime ; Base case ; Recursive step ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nswp ( int n ) { if ( n == 0 n == 1 ) return 1 ; return 2 * nswp ( n - 1 ) + nswp ( n - 2 ) ; } int main ( ) { int n = 3 ; cout << nswp ( n ) << endl ; return 0 ; }