text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Longest alternating sub | C ++ program to calculate longest alternating sub - array for each index elements ; Function to calculate alternating sub - array for each index of array elements ; Initialize count variable for storing length of sub - array ; Initialize ' prev ' variable which indicates the previous element while traversing for index ' i ' ; If both elements are same print elements because alternate element is not found for current index ; print count and decrement it . ; Increment count for next element ; Re - initialize previous variable ; If elements are still available after traversing whole array , print it ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void alternateSubarray ( bool arr [ ] , int n ) { int count = 1 ; int prev = arr [ 0 ] ; for ( int i = 1 ; i < n ; ++ i ) { if ( ( arr [ i ] ^ prev ) == 0 ) { while ( count ) cout << count -- << " β " ; } ++ count ; prev = arr [ i ] ; } while ( count ) cout << count -- << " β " ; } int main ( ) { bool arr [ ] = { 1 , 0 , 1 , 0 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; alternateSubarray ( arr , n ) ; return 0 ; } |
Longest Common Subsequence with at most k changes allowed | CPP program to find LCS of two arrays with k changes allowed in first array . ; Return LCS with at most k changes allowed . ; If at most changes is less than 0. ; If any of two array is over . ; Making a reference variable to dp [ n ] [ m ] [ k ] ; If value is already calculated , return that value . ; calculating LCS with no changes made . ; calculating LCS when array element are same . ; calculating LCS with changes made . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 10 NEW_LINE int lcs ( int dp [ MAX ] [ MAX ] [ MAX ] , int arr1 [ ] , int n , int arr2 [ ] , int m , int k ) { if ( k < 0 ) return -1e7 ; if ( n < 0 m < 0 ) return 0 ; int & ans = dp [ n ] [ m ] [ k ] ; if ( ans != -1 ) return ans ; ans = max ( lcs ( dp , arr1 , n - 1 , arr2 , m , k ) , lcs ( dp , arr1 , n , arr2 , m - 1 , k ) ) ; if ( arr1 [ n - 1 ] == arr2 [ m - 1 ] ) ans = max ( ans , 1 + lcs ( dp , arr1 , n - 1 , arr2 , m - 1 , k ) ) ; ans = max ( ans , 1 + lcs ( dp , arr1 , n - 1 , arr2 , m - 1 , k - 1 ) ) ; return ans ; } int main ( ) { int k = 1 ; int arr1 [ ] = { 1 , 2 , 3 , 4 , 5 } ; int arr2 [ ] = { 5 , 3 , 1 , 4 , 2 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int m = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; int dp [ MAX ] [ MAX ] [ MAX ] ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << lcs ( dp , arr1 , n , arr2 , m , k ) << endl ; return 0 ; } |
Count ways to build street under given constraints | C ++ program to count ways to build street under given constraints ; function to count ways of building a street of n rows ; base case ; ways of building houses in both the spots of ith row ; ways of building an office in one of the two spots of ith row ; total ways for n rows ; driver program for checking above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; long countWays ( int n ) { long dp [ 2 ] [ n + 1 ] ; dp [ 0 ] [ 1 ] = 1 ; dp [ 1 ] [ 1 ] = 2 ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + dp [ 1 ] [ i - 1 ] ; dp [ 1 ] [ i ] = dp [ 0 ] [ i - 1 ] * 2 + dp [ 1 ] [ i - 1 ] ; } return dp [ 0 ] [ n ] + dp [ 1 ] [ n ] ; } int main ( ) { int n = 5 ; cout << " Total β no β of β ways β with β n β = β " << n << " β are : β " << countWays ( n ) << endl ; } |
Count ways to build street under given constraints | C ++ program of above approach ; Program to count ways ; Iterate from 2 to n ; Driver code ; Count Ways | #include <iostream> NEW_LINE using namespace std ; int countways ( long long n ) { long long A [ n + 1 ] ; A [ 0 ] = 1 ; A [ 1 ] = 3 ; A [ 2 ] = 7 ; for ( int i = 2 ; i <= n ; i ++ ) { A [ i ] = 2 * A [ i - 1 ] + A [ i - 2 ] ; } return A [ n ] ; } int main ( ) { int n = 5 ; cout << countways ( 5 ) << endl ; return 0 ; } |
Maximum length subsequence with difference between adjacent elements as either 0 or 1 | C ++ implementation to find maximum length subsequence with difference between adjacent elements as either 0 or 1 ; function to find maximum length subsequence with difference between adjacent elements as either 0 or 1 ; Initialize mls [ ] values for all indexes ; Compute optimized maximum length subsequence values in bottom up manner ; Store maximum of all ' mls ' values in ' max ' ; required maximum length subsequence ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLenSub ( int arr [ ] , int n ) { int mls [ n ] , max = 0 ; for ( int i = 0 ; i < n ; i ++ ) mls [ i ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) for ( int j = 0 ; j < i ; j ++ ) if ( abs ( arr [ i ] - arr [ j ] ) <= 1 && mls [ i ] < mls [ j ] + 1 ) mls [ i ] = mls [ j ] + 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( max < mls [ i ] ) max = mls [ i ] ; return max ; } int main ( ) { int arr [ ] = { 2 , 5 , 6 , 3 , 7 , 6 , 5 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum β length β subsequence β = β " << maxLenSub ( arr , n ) ; return 0 ; } |
Unique paths in a Grid with Obstacles | CPP program for the above approach ; If obstacle is at starting position ; Initializing starting position ; first row all are '1' until obstacle ; No ways to reach at this index ; first column all are '1' until obstacle ; No ways to reach at this index ; If current cell has no obstacle ; No ways to reach at this index ; returning the bottom right corner of Grid ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int uniquePathsWithObstacles ( vector < vector < int > > & A ) { int r = A . size ( ) ; int c = A [ 0 ] . size ( ) ; if ( A [ 0 ] [ 0 ] ) return 0 ; A [ 0 ] [ 0 ] = 1 ; for ( int j = 1 ; j < c ; j ++ ) { if ( A [ 0 ] [ j ] == 0 ) { A [ 0 ] [ j ] = A [ 0 ] [ j - 1 ] ; } else { A [ 0 ] [ j ] = 0 ; } } for ( int i = 1 ; i < r ; i ++ ) { if ( A [ i ] [ 0 ] == 0 ) { A [ i ] [ 0 ] = A [ i - 1 ] [ 0 ] ; } else { A [ i ] [ 0 ] = 0 ; } } for ( int i = 1 ; i < r ; i ++ ) { for ( int j = 1 ; j < c ; j ++ ) { if ( A [ i ] [ j ] == 0 ) { A [ i ] [ j ] = A [ i - 1 ] [ j ] + A [ i ] [ j - 1 ] ; } else { A [ i ] [ j ] = 0 ; } } } return A [ r - 1 ] ; } int main ( ) { vector < vector < int > > A = { { 0 , 0 , 0 } , { 0 , 1 , 0 } , { 0 , 0 , 0 } } ; cout << uniquePathsWithObstacles ( A ) << " STRNEWLINE " ; return 0 ; } |
Coin game winner where every player has three choices | C ++ program to find winner of game if player can pick 1 , x , y coins ; To find winner of game ; To store results ; Initial values ; Computing other values . ; If A losses any of i - 1 or i - x or i - y game then he will definitely win game i ; Else A loses game . ; If dp [ n ] is true then A will game otherwise he losses ; Driver program to test findWinner ( ) ; | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool findWinner ( int x , int y , int n ) { int dp [ n + 1 ] ; dp [ 0 ] = false ; dp [ 1 ] = true ; for ( int i = 2 ; i <= n ; i ++ ) { if ( i - 1 >= 0 and ! dp [ i - 1 ] ) dp [ i ] = true ; else if ( i - x >= 0 and ! dp [ i - x ] ) dp [ i ] = true ; else if ( i - y >= 0 and ! dp [ i - y ] ) dp [ i ] = true ; else dp [ i ] = false ; } return dp [ n ] ; } int main ( ) { int x = 3 , y = 4 , n = 5 ; if ( findWinner ( x , y , n ) ) cout << ' A ' ; else cout << ' B ' ; return 0 ; } |
Maximum games played by winner | C / C ++ program to find maximum number of games played by winner ; method returns maximum games a winner needs to play in N - player tournament ; for 0 games , 1 player is needed for 1 game , 2 players are required ; loop until i - th Fibonacci number is less than or equal to N ; result is ( i - 2 ) because i will be incremented one extra in while loop and we want the last value which is smaller than N , so one more decrement ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxGameByWinner ( int N ) { int dp [ N ] ; dp [ 0 ] = 1 ; dp [ 1 ] = 2 ; int i = 2 ; do { dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] ; } while ( dp [ i ++ ] <= N ) ; return ( i - 2 ) ; } int main ( ) { int N = 10 ; cout << maxGameByWinner ( N ) << endl ; return 0 ; } |
Convert to Strictly increasing integer array with minimum changes | CPP program to find min elements to change so array is strictly increasing ; To find min elements to remove from array to make it strictly increasing ; Mark all elements of LIS as 1 ; Find LIS of array ; Return min changes for array to strictly increasing ; Driver program to test minRemove ( ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minRemove ( int arr [ ] , int n ) { int LIS [ n ] , len = 0 ; for ( int i = 0 ; i < n ; i ++ ) LIS [ i ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ i ] > arr [ j ] && ( i - j ) <= ( arr [ i ] - arr [ j ] ) ) { LIS [ i ] = max ( LIS [ i ] , LIS [ j ] + 1 ) ; } } len = max ( len , LIS [ i ] ) ; } return n - len ; } int main ( ) { int arr [ ] = { 1 , 2 , 6 , 5 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minRemove ( arr , n ) ; return 0 ; } |
Ways of transforming one string to other by removing 0 or more characters | C ++ program to count the distinct transformation of one string to other . ; If b = " " i . e . , an empty string . There is only one way to transform ( remove all characters ) ; Fil dp [ ] [ ] in bottom up manner Traverse all character of b [ ] ; Traverse all characters of a [ ] for b [ i ] ; Filling the first row of the dp matrix . ; Filling other rows . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countTransformation ( string a , string b ) { int n = a . size ( ) , m = b . size ( ) ; if ( m == 0 ) return 1 ; int dp [ m ] [ n ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { if ( i == 0 ) { if ( j == 0 ) dp [ i ] [ j ] = ( a [ j ] == b [ i ] ) ? 1 : 0 ; else if ( a [ j ] == b [ i ] ) dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + 1 ; else dp [ i ] [ j ] = dp [ i ] [ j - 1 ] ; } else { if ( a [ j ] == b [ i ] ) dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = dp [ i ] [ j - 1 ] ; } } } return dp [ m - 1 ] [ n - 1 ] ; } int main ( ) { string a = " abcccdf " , b = " abccdf " ; cout << countTransformation ( a , b ) << endl ; return 0 ; } |
n | CPP code to find nth number with digits 0 , 1 , 2 , 3 , 4 , 5 ; function to convert num to base 6 ; Driver code ; initialize an array to 0 ; function calling to convert number n to base 6 ; if size is zero then return zero | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define max 100000 NEW_LINE int baseconversion ( int arr [ ] , int num , int base ) { int i = 0 , rem , j ; if ( num == 0 ) { return 0 ; } while ( num > 0 ) { rem = num % base ; arr [ i ++ ] = rem ; num /= base ; } return i ; } int main ( ) { int arr [ max ] = { 0 } ; int n = 10 ; int size = baseconversion ( arr , n - 1 , 6 ) ; if ( size == 0 ) cout << size ; for ( int i = size - 1 ; i >= 0 ; i -- ) { cout << arr [ i ] ; } return 0 ; } |
Choose maximum weight with given weight and value ratio | C ++ program to choose item with maximum sum of weight under given constraint ; memoized recursive method to return maximum weight with K as ratio of weight and values ; base cases : if no item is remaining ; first make pair with last chosen item and difference between weight and values ; choose maximum value from following two 1 ) not selecting the current item and calling recursively 2 ) selection current item , including the weight and updating the difference before calling recursively ; method returns maximum sum of weight with K as ration of sum of weight and their values ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxWeightRec ( int wt [ ] , int val [ ] , int K , map < pair < int , int > , int > & mp , int last , int diff ) { if ( last == -1 ) { if ( diff == 0 ) return 0 ; else return INT_MIN ; } pair < int , int > tmp = make_pair ( last , diff ) ; if ( mp . find ( tmp ) != mp . end ( ) ) return mp [ tmp ] ; mp [ tmp ] = max ( maxWeightRec ( wt , val , K , mp , last - 1 , diff ) , wt [ last ] + maxWeightRec ( wt , val , K , mp , last - 1 , diff + wt [ last ] - val [ last ] * K ) ) ; return mp [ tmp ] ; } int maxWeight ( int wt [ ] , int val [ ] , int K , int N ) { map < pair < int , int > , int > mp ; return maxWeightRec ( wt , val , K , mp , N - 1 , 0 ) ; } int main ( ) { int wt [ ] = { 4 , 8 , 9 } ; int val [ ] = { 2 , 4 , 6 } ; int N = sizeof ( wt ) / sizeof ( int ) ; int K = 2 ; cout << maxWeight ( wt , val , K , N ) ; return 0 ; } |
Pyramid form ( increasing then decreasing ) consecutive array using reduce operations | Program to find minimum cost for pyramid from given array ; Returns minimum cost to form a pyramid ; Store the maximum possible pyramid height ; Maximum height at start is 1 ; For each position calculate maximum height ; Maximum height at end is 1 ; For each position calculate maximum height ; Find minimum possible among calculated values ; Find maximum height of pyramid ; Calculate cost of this pyramid ; Calculate cost of left half ; Calculate cost of right half ; Driver code | #include <iostream> NEW_LINE using namespace std ; #define ull unsigned long long NEW_LINE ull minPyramidCost ( ull arr [ ] , ull N ) { ull * left = new ull [ N ] ; ull * right = new ull [ N ] ; left [ 0 ] = min ( arr [ 0 ] , ( ull ) 1 ) ; for ( int i = 1 ; i < N ; ++ i ) left [ i ] = min ( arr [ i ] , min ( left [ i - 1 ] + 1 , ( ull ) i + 1 ) ) ; right [ N - 1 ] = min ( arr [ N - 1 ] , ( ull ) 1 ) ; for ( int i = N - 2 ; i >= 0 ; -- i ) right [ i ] = min ( arr [ i ] , min ( right [ i + 1 ] + 1 , N - i ) ) ; ull tot [ N ] ; for ( int i = 0 ; i < N ; ++ i ) tot [ i ] = min ( right [ i ] , left [ i ] ) ; ull max_ind = 0 ; for ( int i = 0 ; i < N ; ++ i ) if ( tot [ i ] > tot [ max_ind ] ) max_ind = i ; ull cost = 0 ; ull height = tot [ max_ind ] ; for ( int x = max_ind ; x >= 0 ; -- x ) { cost += arr [ x ] - height ; if ( height > 0 ) -- height ; } height = tot [ max_ind ] - 1 ; for ( int x = max_ind + 1 ; x < N ; ++ x ) { cost += arr [ x ] - height ; if ( height > 0 ) -- height ; } return cost ; } int main ( ) { ull arr [ ] = { 1 , 2 , 3 , 4 , 2 , 1 } ; ull N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minPyramidCost ( arr , N ) ; return 0 ; } |
Maximum sum in a 2 x n grid such that no two elements are adjacent | C ++ program to find maximum sum in a grid such that no two elements are adjacent . ; Function to find max sum without adjacent ; Sum including maximum element of first column ; Not including first column 's element ; Traverse for further elements ; Update max_sum on including or excluding of previous column ; Include current column . Add maximum element from both row of current column ; If current column doesn 't to be included ; Return maximum of excl and incl As that will be the maximum sum ; Driver code | #include <bits/stdc++.h> NEW_LINE #define MAX 1000 NEW_LINE using namespace std ; int maxSum ( int grid [ 2 ] [ MAX ] , int n ) { int incl = max ( grid [ 0 ] [ 0 ] , grid [ 1 ] [ 0 ] ) ; int excl = 0 , excl_new ; for ( int i = 1 ; i < n ; i ++ ) { excl_new = max ( excl , incl ) ; incl = excl + max ( grid [ 0 ] [ i ] , grid [ 1 ] [ i ] ) ; excl = excl_new ; } return max ( excl , incl ) ; } int main ( ) { int grid [ 2 ] [ MAX ] = { { 1 , 2 , 3 , 4 , 5 } , { 6 , 7 , 8 , 9 , 10 } } ; int n = 5 ; cout << maxSum ( grid , n ) ; return 0 ; } |
Minimum insertions to sort an array | C ++ program to get minimum number of insertion steps to sort an array ; method returns min steps of insertion we need to perform to sort array ' arr ' ; lis [ i ] is going to store length of lis that ends with i . ; Initialize lis values for all indexes ; Compute optimized lis values in bottom up manner ; The overall LIS must end with of the array elements . Pick maximum of all lis values ; return size of array minus length of LIS as final result ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minInsertionStepToSortArray ( int arr [ ] , int N ) { int lis [ N ] ; for ( int i = 0 ; i < N ; i ++ ) lis [ i ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) for ( int j = 0 ; j < i ; j ++ ) if ( arr [ i ] >= arr [ j ] && lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; int max = 0 ; for ( int i = 0 ; i < N ; i ++ ) if ( max < lis [ i ] ) max = lis [ i ] ; return ( N - max ) ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 1 , 4 , 7 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minInsertionStepToSortArray ( arr , N ) ; return 0 ; } |
Print all distinct characters of a string in order ( 3 Methods ) | ; checking if two charactors are equal | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { string str = " GeeksforGeeks " ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) { int flag = 0 ; for ( int j = 0 ; j < str . size ( ) ; j ++ ) { if ( str [ i ] == str [ j ] and i != j ) { flag = 1 ; break ; } } if ( flag == 0 ) cout << str [ i ] ; } return 0 ; } |
Print all distinct characters of a string in order ( 3 Methods ) | C ++ program to print distinct characters of a string . ; Print duplicates present in the passed string ; Create an array of size 256 and count of every character in it ; Count array with frequency of characters ; Print characters having count more than 0 ; Driver program | # include <iostream> NEW_LINE using namespace std ; # define NO_OF_CHARS 256 NEW_LINE void printDistinct ( char * str ) { int count [ NO_OF_CHARS ] ; int i ; for ( i = 0 ; * ( str + i ) ; i ++ ) if ( * ( str + i ) != ' β ' ) count [ * ( str + i ) ] ++ ; int n = i ; for ( i = 0 ; i < n ; i ++ ) if ( count [ * ( str + i ) ] == 1 ) cout << str [ i ] ; } int main ( ) { char str [ ] = " GeeksforGeeks " ; printDistinct ( str ) ; return 0 ; } |
Shortest Uncommon Subsequence | A simple recursive C ++ program to find shortest uncommon subsequence . ; A recursive function to find the length of shortest uncommon subsequence ; S string is empty ; T string is empty ; Loop to search for current character ; char not found in T ; Return minimum of following two Not including current char in answer Including current char ; Driver program to test the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1005 NEW_LINE int shortestSeq ( char * S , char * T , int m , int n ) { if ( m == 0 ) return MAX ; if ( n <= 0 ) return 1 ; int k ; for ( k = 0 ; k < n ; k ++ ) if ( T [ k ] == S [ 0 ] ) break ; if ( k == n ) return 1 ; return min ( shortestSeq ( S + 1 , T , m - 1 , n ) , 1 + shortestSeq ( S + 1 , T + k + 1 , m - 1 , n - k - 1 ) ) ; } int main ( ) { char S [ ] = " babab " ; char T [ ] = " babba " ; int m = strlen ( S ) , n = strlen ( T ) ; int ans = shortestSeq ( S , T , m , n ) ; if ( ans >= MAX ) ans = -1 ; cout << " Length β of β shortest β subsequence β is : β " << ans << endl ; return 0 ; } |
Shortest Uncommon Subsequence | A dynamic programming based C ++ program to find shortest uncommon subsequence . ; Returns length of shortest common subsequence ; declaring 2D array of m + 1 rows and n + 1 columns dynamically ; T string is empty ; S string is empty ; char not present in T ; Driver program to test the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1005 NEW_LINE int shortestSeq ( char * S , char * T ) { int m = strlen ( S ) , n = strlen ( T ) ; int dp [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) dp [ i ] [ 0 ] = 1 ; for ( int i = 0 ; i <= n ; i ++ ) dp [ 0 ] [ i ] = MAX ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { char ch = S [ i - 1 ] ; int k ; for ( k = j - 1 ; k >= 0 ; k -- ) if ( T [ k ] == ch ) break ; if ( k == -1 ) dp [ i ] [ j ] = 1 ; else dp [ i ] [ j ] = min ( dp [ i - 1 ] [ j ] , dp [ i - 1 ] [ k ] + 1 ) ; } } int ans = dp [ m ] [ n ] ; if ( ans >= MAX ) ans = -1 ; return ans ; } int main ( ) { char S [ ] = " babab " ; char T [ ] = " babba " ; int m = strlen ( S ) , n = strlen ( T ) ; cout << " Length β of β shortest β subsequence β is β : β " << shortestSeq ( S , T ) << endl ; } |
Count number of ways to jump to reach end | C ++ implementation to count number of ways to jump to reach end ; function to count ways to jump to reach end for each array element ; count_jump [ i ] store number of ways arr [ i ] can reach to the end ; Last element does not require to jump . Count ways to jump for remaining elements ; if the element can directly jump to the end ; add the count of all the elements that can reach to end and arr [ i ] can reach to them ; if element can reach to end then add its count to count_jump [ i ] ; if arr [ i ] cannot reach to the end ; print count_jump for each array element ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countWaysToJump ( int arr [ ] , int n ) { int count_jump [ n ] ; memset ( count_jump , 0 , sizeof ( count_jump ) ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] >= n - i - 1 ) count_jump [ i ] ++ ; for ( int j = i + 1 ; j < n - 1 && j <= arr [ i ] + i ; j ++ ) if ( count_jump [ j ] != -1 ) count_jump [ i ] += count_jump [ j ] ; if ( count_jump [ i ] == 0 ) count_jump [ i ] = -1 ; } for ( int i = 0 ; i < n ; i ++ ) cout << count_jump [ i ] << " β " ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 8 , 9 , 1 , 0 , 7 , 6 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countWaysToJump ( arr , n ) ; return 0 ; } |
Minimum steps to delete a string after repeated deletion of palindrome substrings | C ++ program to find minimum step to delete a string ; method returns minimum step for deleting the string , where in one step a palindrome is removed ; declare dp array and initialize it with 0 s ; loop for substring length we are considering ; loop with two variables i and j , denoting starting and ending of substrings ; If substring length is 1 , then 1 step will be needed ; delete the ith char individually and assign result for subproblem ( i + 1 , j ) ; if current and next char are same , choose min from current and subproblem ( i + 2 , j ) ; loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char ; Uncomment below snippet to print actual dp tablex for ( int i = 0 ; i < N ; i ++ , cout << endl ) for ( int j = 0 ; j < N ; j ++ ) cout << dp [ i ] [ j ] << " β " ; ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minStepToDeleteString ( string str ) { int N = str . length ( ) ; int dp [ N + 1 ] [ N + 1 ] ; for ( int i = 0 ; i <= N ; i ++ ) for ( int j = 0 ; j <= N ; j ++ ) dp [ i ] [ j ] = 0 ; for ( int len = 1 ; len <= N ; len ++ ) { for ( int i = 0 , j = len - 1 ; j < N ; i ++ , j ++ ) { if ( len == 1 ) dp [ i ] [ j ] = 1 ; else { dp [ i ] [ j ] = 1 + dp [ i + 1 ] [ j ] ; if ( str [ i ] == str [ i + 1 ] ) dp [ i ] [ j ] = min ( 1 + dp [ i + 2 ] [ j ] , dp [ i ] [ j ] ) ; for ( int K = i + 2 ; K <= j ; K ++ ) if ( str [ i ] == str [ K ] ) dp [ i ] [ j ] = min ( dp [ i + 1 ] [ K - 1 ] + dp [ K + 1 ] [ j ] , dp [ i ] [ j ] ) ; } } } return dp [ 0 ] [ N - 1 ] ; } int main ( ) { string str = "2553432" ; cout << minStepToDeleteString ( str ) << endl ; return 0 ; } |
Clustering / Partitioning an array such that sum of square differences is minimum | C ++ program to find minimum cost k partitions of array . ; Initialize answer as infinite . ; function to generate all possible answers . and compute minimum of all costs . i -- > is index of previous partition par -- > is current number of partitions a [ ] and n -- > Input array and its size current_ans -- > Cost of partitions made so far . ; If number of partitions is more than k ; If we have mad k partitions and have reached last element ; 1 ) Partition array at different points 2 ) For every point , increase count of partitions , " par " by 1. 3 ) Before recursive call , add cost of the partition to current_ans ; Driver code | #include <iostream> NEW_LINE using namespace std ; const int inf = 1000000000 ; int ans = inf ; void solve ( int i , int par , int a [ ] , int n , int k , int current_ans ) { if ( par > k ) return ; if ( par == k && i == n - 1 ) { ans = min ( ans , current_ans ) ; return ; } for ( int j = i + 1 ; j < n ; j ++ ) solve ( j , par + 1 , a , n , k , current_ans + ( a [ j ] - a [ i + 1 ] ) * ( a [ j ] - a [ i + 1 ] ) ) ; } int main ( ) { int k = 2 ; int a [ ] = { 1 , 5 , 8 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; solve ( -1 , 0 , a , n , k , 0 ) ; cout << ans << endl ; return 0 ; } |
Minimum steps to minimize n as per given condition | CPP program to minimize n to 1 by given rule in minimum steps ; function to calculate min steps ; base case ; store temp value for n as min ( f ( n - 1 ) , f ( n / 2 ) , f ( n / 3 ) ) + 1 ; store memo [ n ] and return ; This function mainly initializes memo [ ] and calls getMinSteps ( n , memo ) ; initialize memoized array ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinSteps ( int n , int * memo ) { if ( n == 1 ) return 0 ; if ( memo [ n ] != -1 ) return memo [ n ] ; int res = getMinSteps ( n - 1 , memo ) ; if ( n % 2 == 0 ) res = min ( res , getMinSteps ( n / 2 , memo ) ) ; if ( n % 3 == 0 ) res = min ( res , getMinSteps ( n / 3 , memo ) ) ; memo [ n ] = 1 + res ; return memo [ n ] ; } int getMinSteps ( int n ) { int memo [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) memo [ i ] = -1 ; return getMinSteps ( n , memo ) ; } int main ( ) { int n = 10 ; cout << getMinSteps ( n ) ; return 0 ; } |
Count of arrays in which all adjacent elements are such that one of them divide the another | C ++ program to count number of arrays of size n such that every element is in range [ 1 , m ] and adjacen are divisible ; For storing factors . ; For storing multiples . ; calculating the factors and multiples of elements [ 1. . . m ] . ; Initialising for size 1 array for each i <= m . ; Calculating the number of array possible of size i and starting with j . ; For all previous possible values . Adding number of factors . ; Adding number of multiple . ; Calculating the total count of array which start from [ 1. . . m ] . ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define MAX 1000 NEW_LINE using namespace std ; int numofArray ( int n , int m ) { int dp [ MAX ] [ MAX ] ; vector < int > di [ MAX ] ; vector < int > mu [ MAX ] ; memset ( dp , 0 , sizeof dp ) ; memset ( di , 0 , sizeof di ) ; memset ( mu , 0 , sizeof mu ) ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 2 * i ; j <= m ; j += i ) { di [ j ] . push_back ( i ) ; mu [ i ] . push_back ( j ) ; } di [ i ] . push_back ( i ) ; } for ( int i = 1 ; i <= m ; i ++ ) dp [ 1 ] [ i ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { dp [ i ] [ j ] = 0 ; for ( auto x : di [ j ] ) dp [ i ] [ j ] += dp [ i - 1 ] [ x ] ; for ( auto x : mu [ j ] ) dp [ i ] [ j ] += dp [ i - 1 ] [ x ] ; } } int ans = 0 ; for ( int i = 1 ; i <= m ; i ++ ) { ans += dp [ n ] [ i ] ; di [ i ] . clear ( ) ; mu [ i ] . clear ( ) ; } return ans ; } int main ( ) { int n = 3 , m = 3 ; cout << numofArray ( n , m ) << " STRNEWLINE " ; return 0 ; } |
Temple Offerings | C ++ Program to find total offerings required ; To store count of increasing order temples on left and right ( including current temple ) ; Returns count of minimum offerings for n temples of given heights . ; Initialize counts for all temples ; Values corner temples ; Filling left and right values using same values of previous ( or next ) ; Computing max of left and right for all temples and returning sum . ; Driver function | #include <iostream> NEW_LINE using namespace std ; struct Temple { int L ; int R ; } ; int offeringNumber ( int n , int templeHeight [ ] ) { Temple chainSize [ n ] ; for ( int i = 0 ; i < n ; ++ i ) { chainSize [ i ] . L = -1 ; chainSize [ i ] . R = -1 ; } chainSize [ 0 ] . L = 1 ; chainSize [ n - 1 ] . R = 1 ; for ( int i = 1 ; i < n ; ++ i ) { if ( templeHeight [ i - 1 ] < templeHeight [ i ] ) chainSize [ i ] . L = chainSize [ i - 1 ] . L + 1 ; else chainSize [ i ] . L = 1 ; } for ( int i = n - 2 ; i >= 0 ; -- i ) { if ( templeHeight [ i + 1 ] < templeHeight [ i ] ) chainSize [ i ] . R = chainSize [ i + 1 ] . R + 1 ; else chainSize [ i ] . R = 1 ; } int sum = 0 ; for ( int i = 0 ; i < n ; ++ i ) sum += max ( chainSize [ i ] . L , chainSize [ i ] . R ) ; return sum ; } int main ( ) { int arr1 [ 3 ] = { 1 , 2 , 2 } ; cout << offeringNumber ( 3 , arr1 ) << " STRNEWLINE " ; int arr2 [ 6 ] = { 1 , 4 , 3 , 6 , 2 , 1 } ; cout << offeringNumber ( 6 , arr2 ) << " STRNEWLINE " ; return 0 ; } |
Smallest length string with repeated replacement of two distinct adjacent | C ++ program to find smallest possible length of a string of only three characters ; Returns smallest possible length with given operation allowed . ; Counint occurrences of three different characters ' a ' , ' b ' and ' c ' in str ; If all characters are same . ; If all characters are present even number of times or all are present odd number of times . ; Answer is 1 for all other cases . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int stringReduction ( string str ) { int n = str . length ( ) ; int count [ 3 ] = { 0 } ; for ( int i = 0 ; i < n ; ++ i ) count [ str [ i ] - ' a ' ] ++ ; if ( count [ 0 ] == n count [ 1 ] == n count [ 2 ] == n ) return n ; if ( ( count [ 0 ] % 2 ) == ( count [ 1 ] % 2 ) && ( count [ 1 ] % 2 ) == ( count [ 2 ] % 2 ) ) return 2 ; return 1 ; } int main ( ) { string str = " abcbbaacb " ; cout << stringReduction ( str ) ; return 0 ; } |
Largest sum Zigzag sequence in a matrix | Memoization based C ++ program to find the largest sum zigzag sequence ; Returns largest sum of a Zigzag sequence starting from ( i , j ) and ending at a bottom cell . ; If we have reached bottom ; Find the largest sum by considering all possible next elements in sequence . ; Returns largest possible sum of a Zizag sequence starting from top and ending at bottom . ; Consider all cells of top row as starting point ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; int dp [ MAX ] [ MAX ] ; int largestZigZagSumRec ( int mat [ ] [ MAX ] , int i , int j , int n ) { if ( dp [ i ] [ j ] != -1 ) return dp [ i ] [ j ] ; if ( i == n - 1 ) return ( dp [ i ] [ j ] = mat [ i ] [ j ] ) ; int zzs = 0 ; for ( int k = 0 ; k < n ; k ++ ) if ( k != j ) zzs = max ( zzs , largestZigZagSumRec ( mat , i + 1 , k , n ) ) ; return ( dp [ i ] [ j ] = ( zzs + mat [ i ] [ j ] ) ) ; } int largestZigZag ( int mat [ ] [ MAX ] , int n ) { memset ( dp , -1 , sizeof ( dp ) ) ; int res = 0 ; for ( int j = 0 ; j < n ; j ++ ) res = max ( res , largestZigZagSumRec ( mat , 0 , j , n ) ) ; return res ; } int main ( ) { int n = 3 ; int mat [ ] [ MAX ] = { { 4 , 2 , 1 } , { 3 , 9 , 6 } , { 11 , 3 , 15 } } ; cout << " Largest β zigzag β sum : β " << largestZigZag ( mat , n ) ; return 0 ; } |
Number of subsequences of the form a ^ i b ^ j c ^ k | C ++ program to count subsequences of the form a ^ i b ^ j c ^ k ; Returns count of subsequences of the form a ^ i b ^ j c ^ k ; Initialize counts of different subsequences caused by different combination of ' a ' ; Initialize counts of different subsequences caused by different combination of ' a ' and different combination of ' b ' ; Initialize counts of different subsequences caused by different combination of ' a ' , ' b ' and ' c ' . ; Traverse all characters of given string ; If current character is ' a ' , then there are the following possibilities : a ) Current character begins a new subsequence . b ) Current character is part of aCount subsequences . c ) Current character is not part of aCount subsequences . ; If current character is ' b ' , then there are following possibilities : a ) Current character begins a new subsequence of b 's with aCount subsequences. b) Current character is part of bCount subsequences. c) Current character is not part of bCount subsequences. ; If current character is ' c ' , then there are following possibilities : a ) Current character begins a new subsequence of c 's with bCount subsequences. b) Current character is part of cCount subsequences. c) Current character is not part of cCount subsequences. ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubsequences ( string s ) { int aCount = 0 ; int bCount = 0 ; int cCount = 0 ; for ( unsigned int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == ' a ' ) aCount = ( 1 + 2 * aCount ) ; else if ( s [ i ] == ' b ' ) bCount = ( aCount + 2 * bCount ) ; else if ( s [ i ] == ' c ' ) cCount = ( bCount + 2 * cCount ) ; } return cCount ; } int main ( ) { string s = " abbc " ; cout << countSubsequences ( s ) << endl ; return 0 ; } |
Highway Billboard Problem | C ++ program to find maximum revenue by placing billboard on the highway with given constraints . ; Array to store maximum revenue at each miles . ; actual minimum distance between 2 billboards . ; check if all billboards are already placed . ; check if we have billboard for that particular mile . If not , copy the previous maximum revenue . ; we do have billboard for this mile . ; If current position is less than or equal to t , then we can have only one billboard . ; Else we may have to remove previously placed billboard ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxRevenue ( int m , int x [ ] , int revenue [ ] , int n , int t ) { int maxRev [ m + 1 ] ; memset ( maxRev , 0 , sizeof ( maxRev ) ) ; int nxtbb = 0 ; for ( int i = 1 ; i <= m ; i ++ ) { if ( nxtbb < n ) { if ( x [ nxtbb ] != i ) maxRev [ i ] = maxRev [ i - 1 ] ; else { if ( i <= t ) maxRev [ i ] = max ( maxRev [ i - 1 ] , revenue [ nxtbb ] ) ; else maxRev [ i ] = max ( maxRev [ i - t - 1 ] + revenue [ nxtbb ] , maxRev [ i - 1 ] ) ; nxtbb ++ ; } } else maxRev [ i ] = maxRev [ i - 1 ] ; } return maxRev [ m ] ; } int main ( ) { int m = 20 ; int x [ ] = { 6 , 7 , 12 , 13 , 14 } ; int revenue [ ] = { 5 , 6 , 5 , 3 , 1 } ; int n = sizeof ( x ) / sizeof ( x [ 0 ] ) ; int t = 5 ; cout << maxRevenue ( m , x , revenue , n , t ) << endl ; return 0 ; } |
Finding the maximum square sub | C ++ program to find maximum K such that K x K is a submatrix with equal elements . ; Returns size of the largest square sub - matrix with all same elements . ; If elements is at top row or first column , it wont form a square matrix 's bottom-right ; Check if adjacent elements are equal ; If not equal , then it will form a 1 x1 submatrix ; Update result at each ( i , j ) ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define Row 6 NEW_LINE #define Col 6 NEW_LINE using namespace std ; int largestKSubmatrix ( int a [ ] [ Col ] ) { int dp [ Row ] [ Col ] ; memset ( dp , sizeof ( dp ) , 0 ) ; int result = 0 ; for ( int i = 0 ; i < Row ; i ++ ) { for ( int j = 0 ; j < Col ; j ++ ) { if ( i == 0 j == 0 ) dp [ i ] [ j ] = 1 ; else { if ( a [ i ] [ j ] == a [ i - 1 ] [ j ] && a [ i ] [ j ] == a [ i ] [ j - 1 ] && a [ i ] [ j ] == a [ i - 1 ] [ j - 1 ] ) dp [ i ] [ j ] = min ( min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) , dp [ i - 1 ] [ j - 1 ] ) + 1 ; else dp [ i ] [ j ] = 1 ; } result = max ( result , dp [ i ] [ j ] ) ; } } return result ; } int main ( ) { int a [ Row ] [ Col ] = { 2 , 2 , 3 , 3 , 4 , 4 , 5 , 5 , 7 , 7 , 7 , 4 , 1 , 2 , 7 , 7 , 7 , 4 , 4 , 4 , 7 , 7 , 7 , 4 , 5 , 5 , 5 , 1 , 2 , 7 , 8 , 7 , 9 , 4 , 4 , 4 } ; cout << largestKSubmatrix ( a ) << endl ; return 0 ; } |
Number of subsequences in a string divisible by n | C ++ program to count subsequences of a string divisible by n . ; Returns count of subsequences of str divisible by n . ; division by n can leave only n remainder [ 0. . n - 1 ] . dp [ i ] [ j ] indicates number of subsequences in string [ 0. . i ] which leaves remainder j after division by n . ; Filling value for first digit in str ; start a new subsequence with index i ; exclude i 'th character from all the current subsequences of string [0...i-1] ; include i 'th character in all the current subsequences of string [0...i-1] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDivisibleSubseq ( string str , int n ) { int len = str . length ( ) ; int dp [ len ] [ n ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ ( str [ 0 ] - '0' ) % n ] ++ ; for ( int i = 1 ; i < len ; i ++ ) { dp [ i ] [ ( str [ i ] - '0' ) % n ] ++ ; for ( int j = 0 ; j < n ; j ++ ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j ] ; dp [ i ] [ ( j * 10 + ( str [ i ] - '0' ) ) % n ] += dp [ i - 1 ] [ j ] ; } } return dp [ len - 1 ] [ 0 ] ; } int main ( ) { string str = "1234" ; int n = 4 ; cout << countDivisibleSubseq ( str , n ) ; return 0 ; } |
Size of array after repeated deletion of LIS | C ++ program to find size of array after repeated deletion of LIS ; Function to construct Maximum Sum LIS ; L [ i ] - The Maximum Sum Increasing Subsequence that ends with arr [ i ] ; L [ 0 ] is equal to arr [ 0 ] ; start from index 1 ; for every j less than i ; L [ i ] = { MaxSum ( L [ j ] ) } + arr [ i ] where j < i and arr [ j ] < arr [ i ] ; L [ i ] ends with arr [ i ] ; set lis = LIS whose size is max among all ; The > sign makes sure that the LIS ending first is chose . ; Function to minimize array ; Find LIS of current array ; If all elements are in decreasing order ; Remove lis elements from current array . Note that both lis [ ] and arr [ ] are sorted in increasing order . ; If first element of lis [ ] is found ; Remove lis element from arr [ ] ; Erase first element of lis [ ] ; print remaining element of array ; print - 1 for empty array ; Driver function ; minimize array after deleting LIS | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findLIS ( vector < int > arr , int n ) { vector < vector < int > > L ( n ) ; L [ 0 ] . push_back ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ i ] > arr [ j ] && ( L [ i ] . size ( ) < L [ j ] . size ( ) ) ) L [ i ] = L [ j ] ; } L [ i ] . push_back ( arr [ i ] ) ; } int maxSize = 1 ; vector < int > lis ; for ( vector < int > x : L ) { if ( x . size ( ) > maxSize ) { lis = x ; maxSize = x . size ( ) ; } } return lis ; } void minimize ( int input [ ] , int n ) { vector < int > arr ( input , input + n ) ; while ( arr . size ( ) ) { vector < int > lis = findLIS ( arr , arr . size ( ) ) ; if ( lis . size ( ) < 2 ) break ; for ( int i = 0 ; i < arr . size ( ) && lis . size ( ) > 0 ; i ++ ) { if ( arr [ i ] == lis [ 0 ] ) { arr . erase ( arr . begin ( ) + i ) ; i -- ; lis . erase ( lis . begin ( ) ) ; } } } int i ; for ( i = 0 ; i < arr . size ( ) ; i ++ ) cout << arr [ i ] << " β " ; if ( i == 0 ) cout << " - 1" ; } int main ( ) { int input [ ] = { 3 , 2 , 6 , 4 , 5 , 1 } ; int n = sizeof ( input ) / sizeof ( input [ 0 ] ) ; minimize ( input , n ) ; return 0 ; } |
Probability of getting at least K heads in N tosses of Coins | Naive approach in C ++ to find probability of at least k heads ; Returns probability of getting at least k heads in n tosses . ; Probability of getting exactly i heads out of n heads ; Note : 1 << n = pow ( 2 , n ) ; Preprocess all factorial only upto 19 , as after that it will overflow ; Driver code ; Probability of getting 2 head out of 3 coins ; Probability of getting 3 head out of 6 coins ; Probability of getting 12 head out of 18 coins | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 21 NEW_LINE double fact [ MAX ] ; double probability ( int k , int n ) { double ans = 0 ; for ( int i = k ; i <= n ; ++ i ) ans += fact [ n ] / ( fact [ i ] * fact [ n - i ] ) ; ans = ans / ( 1LL << n ) ; return ans ; } void precompute ( ) { fact [ 0 ] = fact [ 1 ] = 1 ; for ( int i = 2 ; i < 20 ; ++ i ) fact [ i ] = fact [ i - 1 ] * i ; } int main ( ) { precompute ( ) ; cout << probability ( 2 , 3 ) << " STRNEWLINE " ; cout << probability ( 3 , 6 ) << " STRNEWLINE " ; cout << probability ( 12 , 18 ) ; return 0 ; } |
Count binary strings with k times appearing adjacent two set bits | C ++ program to count number of binary strings with k times appearing consecutive 1 's. ; dp [ i ] [ j ] [ 0 ] stores count of binary strings of length i with j consecutive 1 ' s β and β ending β at β 0 . β β dp [ i ] [ j ] [1 ] β stores β count β of β binary β β strings β of β length β i β with β j β consecutive β β 1' s and ending at 1. ; If n = 1 and k = 0. ; number of adjacent 1 's can not exceed i-1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countStrings ( int n , int k ) { int dp [ n + 1 ] [ k + 1 ] [ 2 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 1 ] [ 0 ] [ 0 ] = 1 ; dp [ 1 ] [ 0 ] [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= k ; j ++ ) { dp [ i ] [ j ] [ 0 ] = dp [ i - 1 ] [ j ] [ 0 ] + dp [ i - 1 ] [ j ] [ 1 ] ; dp [ i ] [ j ] [ 1 ] = dp [ i - 1 ] [ j ] [ 0 ] ; if ( j - 1 >= 0 ) dp [ i ] [ j ] [ 1 ] += dp [ i - 1 ] [ j - 1 ] [ 1 ] ; } } return dp [ n ] [ k ] [ 0 ] + dp [ n ] [ k ] [ 1 ] ; } int main ( ) { int n = 5 , k = 2 ; cout << countStrings ( n , k ) ; return 0 ; } |
Check if all people can vote on two machines | C ++ program to check if all people can vote using two machines within limited time ; Returns true if n people can vote using two machines in x time . ; calculate total sum i . e total time taken by all people ; if total time is less than x then all people can definitely vote hence return true ; sort the vector ; declare a vector presum of same size as that of a and initialize it with 0 ; prefixsum for first element will be element itself ; fill the array ; Set i and j and check if array from i to j - 1 gives sum <= x ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canVote ( vector < int > a , int n , int x ) { int total_sum = 0 ; for ( auto x : a ) { total_sum += x ; } if ( total_sum <= x ) return true ; sort ( a . begin ( ) , a . end ( ) ) ; vector < int > presum ( a . size ( ) , 0 ) ; presum [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < presum . size ( ) ; i ++ ) { presum [ i ] = presum [ i - 1 ] + a [ i ] ; } for ( int i = 0 ; i < presum . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < presum . size ( ) ; j ++ ) { int arr1_sum = ( presum [ i ] + ( total_sum - presum [ j ] ) ) ; if ( ( arr1_sum <= x ) && ( total_sum - arr1_sum ) <= x ) return true ; } } return false ; } int main ( ) { int n = 3 , x = 4 ; vector < int > a = { 2 , 4 , 2 } ; canVote ( a , n , x ) ? cout << " YES STRNEWLINE " : cout << " NO STRNEWLINE " ; return 0 ; } |
Friends Pairing Problem | C ++ program for solution of friends pairing problem Using Recursion ; Returns count of ways n people can remain single or paired up . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 1000 ] ; int countFriendsPairings ( int n ) { if ( dp [ n ] != -1 ) return dp [ n ] ; if ( n > 2 ) return dp [ n ] = countFriendsPairings ( n - 1 ) + ( n - 1 ) * countFriendsPairings ( n - 2 ) ; else return dp [ n ] = n ; } int main ( ) { memset ( dp , -1 , sizeof ( dp ) ) ; int n = 4 ; cout << countFriendsPairings ( n ) << endl ; } |
Friends Pairing Problem | C ++ soln using mathematical approach ; Returns count of ways n people can remain single or paired up . ; pow of 1 will always be one ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void preComputeFact ( vector < long long int > & fact , int n ) { for ( int i = 1 ; i <= n ; i ++ ) fact . push_back ( fact [ i - 1 ] * i ) ; } int countFriendsPairings ( vector < long long int > fact , int n ) { int ones = n , twos = 1 , ans = 0 ; while ( ones >= 0 ) { ans += fact [ n ] / ( twos * fact [ ones ] * fact [ ( n - ones ) / 2 ] ) ; ones -= 2 ; twos *= 2 ; } return ans ; } int main ( ) { vector < long long int > fact ; fact . push_back ( 1 ) ; preComputeFact ( fact , 100 ) ; int n = 4 ; cout << countFriendsPairings ( fact , n ) << endl ; return 0 ; } |
Minimum Sum Path In 3 | C ++ program for Min path sum of 3D - array ; A utility function that returns minimum of 3 integers ; function to calculate MIN path sum of 3D array ; Initialize first row of tSum array ; Initialize first column of tSum array ; Initialize first width of tSum array ; Initialize first row - First column of tSum array ; Initialize first row - First width of tSum array ; Initialize first width - First column of tSum array ; Construct rest of the tSum array ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define l 3 NEW_LINE #define m 3 NEW_LINE #define n 3 NEW_LINE int min ( int x , int y , int z ) { return ( x < y ) ? ( ( x < z ) ? x : z ) : ( ( y < z ) ? y : z ) ; } int minPathSum ( int arr [ ] [ m ] [ n ] ) { int i , j , k ; int tSum [ l ] [ m ] [ n ] ; tSum [ 0 ] [ 0 ] [ 0 ] = arr [ 0 ] [ 0 ] [ 0 ] ; for ( i = 1 ; i < l ; i ++ ) tSum [ i ] [ 0 ] [ 0 ] = tSum [ i - 1 ] [ 0 ] [ 0 ] + arr [ i ] [ 0 ] [ 0 ] ; for ( j = 1 ; j < m ; j ++ ) tSum [ 0 ] [ j ] [ 0 ] = tSum [ 0 ] [ j - 1 ] [ 0 ] + arr [ 0 ] [ j ] [ 0 ] ; for ( k = 1 ; k < n ; k ++ ) tSum [ 0 ] [ 0 ] [ k ] = tSum [ 0 ] [ 0 ] [ k - 1 ] + arr [ 0 ] [ 0 ] [ k ] ; for ( i = 1 ; i < l ; i ++ ) for ( j = 1 ; j < m ; j ++ ) tSum [ i ] [ j ] [ 0 ] = min ( tSum [ i - 1 ] [ j ] [ 0 ] , tSum [ i ] [ j - 1 ] [ 0 ] , INT_MAX ) + arr [ i ] [ j ] [ 0 ] ; for ( i = 1 ; i < l ; i ++ ) for ( k = 1 ; k < n ; k ++ ) tSum [ i ] [ 0 ] [ k ] = min ( tSum [ i - 1 ] [ 0 ] [ k ] , tSum [ i ] [ 0 ] [ k - 1 ] , INT_MAX ) + arr [ i ] [ 0 ] [ k ] ; for ( k = 1 ; k < n ; k ++ ) for ( j = 1 ; j < m ; j ++ ) tSum [ 0 ] [ j ] [ k ] = min ( tSum [ 0 ] [ j ] [ k - 1 ] , tSum [ 0 ] [ j - 1 ] [ k ] , INT_MAX ) + arr [ 0 ] [ j ] [ k ] ; for ( i = 1 ; i < l ; i ++ ) for ( j = 1 ; j < m ; j ++ ) for ( k = 1 ; k < n ; k ++ ) tSum [ i ] [ j ] [ k ] = min ( tSum [ i - 1 ] [ j ] [ k ] , tSum [ i ] [ j - 1 ] [ k ] , tSum [ i ] [ j ] [ k - 1 ] ) + arr [ i ] [ j ] [ k ] ; return tSum [ l - 1 ] [ m - 1 ] [ n - 1 ] ; } int main ( ) { int arr [ l ] [ m ] [ n ] = { { { 1 , 2 , 4 } , { 3 , 4 , 5 } , { 5 , 2 , 1 } } , { { 4 , 8 , 3 } , { 5 , 2 , 1 } , { 3 , 4 , 2 } } , { { 2 , 4 , 1 } , { 3 , 1 , 4 } , { 6 , 3 , 8 } } } ; cout << minPathSum ( arr ) ; return 0 ; } |
Printing brackets in Matrix Chain Multiplication Problem | C ++ program to print optimal parenthesization in matrix chain multiplication . ; Function for printing the optimal parenthesization of a matrix chain product ; If only one matrix left in current segment ; Recursively put brackets around subexpression from i to bracket [ i ] [ j ] . Note that " * ( ( bracket + i * n ) + j ) " is similar to bracket [ i ] [ j ] ; Recursively put brackets around subexpression from bracket [ i ] [ j ] + 1 to j . ; Matrix Ai has dimension p [ i - 1 ] x p [ i ] for i = 1. . n Please refer below article for details of this function https : goo . gl / k6EYKj ; For simplicity of the program , one extra row and one extra column are allocated in m [ ] [ ] . 0 th row and 0 th column of m [ ] [ ] are not used ; bracket [ i ] [ j ] stores optimal break point in subexpression from i to j . ; cost is zero when multiplying one matrix . ; L is chain length . ; q = cost / scalar multiplications ; Each entry bracket [ i , j ] = k shows where to split the product arr i , i + 1. . . . j for the minimum cost . ; The first matrix is printed as ' A ' , next as ' B ' , and so on ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printParenthesis ( int i , int j , int n , int * bracket , char & name ) { if ( i == j ) { cout << name ++ ; return ; } cout << " ( " ; printParenthesis ( i , * ( ( bracket + i * n ) + j ) , n , bracket , name ) ; printParenthesis ( * ( ( bracket + i * n ) + j ) + 1 , j , n , bracket , name ) ; cout << " ) " ; } void matrixChainOrder ( int p [ ] , int n ) { int m [ n ] [ n ] ; int bracket [ n ] [ n ] ; for ( int i = 1 ; i < n ; i ++ ) m [ i ] [ i ] = 0 ; for ( int L = 2 ; L < n ; L ++ ) { for ( int i = 1 ; i < n - L + 1 ; i ++ ) { int j = i + L - 1 ; m [ i ] [ j ] = INT_MAX ; for ( int k = i ; k <= j - 1 ; k ++ ) { int q = m [ i ] [ k ] + m [ k + 1 ] [ j ] + p [ i - 1 ] * p [ k ] * p [ j ] ; if ( q < m [ i ] [ j ] ) { m [ i ] [ j ] = q ; bracket [ i ] [ j ] = k ; } } } } char name = ' A ' ; cout << " Optimal β Parenthesization β is β : β " ; printParenthesis ( 1 , n - 1 , n , ( int * ) bracket , name ) ; cout << " nOptimal β Cost β is β : β " << m [ 1 ] [ n - 1 ] ; } int main ( ) { int arr [ ] = { 40 , 20 , 30 , 10 , 30 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; matrixChainOrder ( arr , n ) ; return 0 ; } |
Maximum path sum in a triangle . | C ++ program for Dynamic Programming 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 right to the number add the maximum of them to it ; return the top element which stores the maximum sum ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 3 NEW_LINE int maxPathSum ( int tri [ ] [ N ] , int m , int n ) { for ( int i = m - 1 ; i >= 0 ; i -- ) { for ( int j = 0 ; j <= i ; j ++ ) { if ( tri [ i + 1 ] [ j ] > tri [ i + 1 ] [ j + 1 ] ) tri [ i ] [ j ] += tri [ i + 1 ] [ j ] ; else tri [ i ] [ j ] += tri [ i + 1 ] [ j + 1 ] ; } } return tri [ 0 ] [ 0 ] ; } int main ( ) { int tri [ N ] [ N ] = { { 1 , 0 , 0 } , { 4 , 8 , 0 } , { 1 , 5 , 3 } } ; cout << maxPathSum ( tri , 2 , 2 ) ; return 0 ; } |
Find Maximum dot product of two arrays with insertion of 0 's | C ++ program to find maximum dot product of two array ; Function compute Maximum Dot Product and return it ; Create 2D Matrix that stores dot product dp [ i + 1 ] [ j + 1 ] stores product considering B [ 0. . i ] and A [ 0. . . j ] . Note that since all m > n , we fill values in upper diagonal of dp [ ] [ ] ; Traverse through all elements of B [ ] ; Consider all values of A [ ] with indexes greater than or equal to i and compute dp [ i ] [ j ] ; Two cases arise 1 ) Include A [ j ] 2 ) Exclude A [ j ] ( insert 0 in B [ ] ) ; return Maximum Dot Product ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int MaxDotProduct ( int A [ ] , int B [ ] , int m , int n ) { long long int dp [ n + 1 ] [ m + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = i ; j <= m ; j ++ ) dp [ i ] [ j ] = max ( ( dp [ i - 1 ] [ j - 1 ] + ( A [ j - 1 ] * B [ i - 1 ] ) ) , dp [ i ] [ j - 1 ] ) ; return dp [ n ] [ m ] ; } int main ( ) { int A [ ] = { 2 , 3 , 1 , 7 , 8 } ; int B [ ] = { 3 , 6 , 7 } ; int m = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int n = sizeof ( B ) / sizeof ( B [ 0 ] ) ; cout << MaxDotProduct ( A , B , m , n ) ; return 0 ; } |
LCS ( Longest Common Subsequence ) of three strings | C ++ program to find LCS of three strings ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] and Z [ 0. . o - 1 ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string X = " AGGT12" ; string Y = "12TXAYB " ; string Z = "12XBA " ; int dp [ 100 ] [ 100 ] [ 100 ] ; int lcsOf3 ( int i , int j , int k ) { if ( i == -1 j == -1 k == -1 ) return 0 ; if ( dp [ i ] [ j ] [ k ] != -1 ) return dp [ i ] [ j ] [ k ] ; if ( X [ i ] == Y [ j ] && Y [ j ] == Z [ k ] ) return dp [ i ] [ j ] [ k ] = 1 + lcsOf3 ( i - 1 , j - 1 , k - 1 ) ; else return dp [ i ] [ j ] [ k ] = max ( max ( lcsOf3 ( i - 1 , j , k ) , lcsOf3 ( i , j - 1 , k ) ) , lcsOf3 ( i , j , k - 1 ) ) ; } int main ( ) { memset ( dp , -1 , sizeof ( dp ) ) ; int m = X . length ( ) ; int n = Y . length ( ) ; int o = Z . length ( ) ; cout << " Length β of β LCS β is β " << lcsOf3 ( m - 1 , n - 1 , o - 1 ) ; } |
Minimum number of elements which are not part of Increasing or decreasing subsequence in array | C ++ program to return minimum number of elements which are not part of increasing or decreasing subsequences . ; Return minimum number of elements which is not part of any of the sequence . ; If already calculated , return value . ; If whole array is traversed . ; calculating by considering element as part of decreasing sequence . ; calculating by considering element as part of increasing sequence . ; If cannot be calculated for decreasing sequence . ; After considering once by decreasing sequence , now try for increasing sequence . ; If element cannot be part of any of the sequence . ; After considering element as part of increasing and decreasing sequence trying as not part of any of the sequence . ; Wrapper Function ; Adding two number at the end of array , so that increasing and decreasing sequence can be made . MAX - 2 index is assigned INT_MAX for decreasing sequence because / next number of sequence must be less than it . Similarly , for Increasing sequence INT_MIN is assigned to MAX - 1 index . ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define MAX 102 NEW_LINE using namespace std ; int countMin ( int arr [ ] , int dp [ MAX ] [ MAX ] [ MAX ] , int n , int dec , int inc , int i ) { if ( dp [ dec ] [ inc ] [ i ] != -1 ) return dp [ dec ] [ inc ] [ i ] ; if ( i == n ) return 0 ; if ( arr [ i ] < arr [ dec ] ) dp [ dec ] [ inc ] [ i ] = countMin ( arr , dp , n , i , inc , i + 1 ) ; if ( arr [ i ] > arr [ inc ] ) { if ( dp [ dec ] [ inc ] [ i ] == -1 ) dp [ dec ] [ inc ] [ i ] = countMin ( arr , dp , n , dec , i , i + 1 ) ; else dp [ dec ] [ inc ] [ i ] = min ( countMin ( arr , dp , n , dec , i , i + 1 ) , dp [ dec ] [ inc ] [ i ] ) ; } if ( dp [ dec ] [ inc ] [ i ] == -1 ) dp [ dec ] [ inc ] [ i ] = 1 + countMin ( arr , dp , n , dec , inc , i + 1 ) ; else dp [ dec ] [ inc ] [ i ] = min ( 1 + countMin ( arr , dp , n , dec , inc , i + 1 ) , dp [ dec ] [ inc ] [ i ] ) ; return dp [ dec ] [ inc ] [ i ] ; } int wrapper ( int arr [ ] , int n ) { arr [ MAX - 2 ] = INT_MAX ; arr [ MAX - 1 ] = INT_MIN ; int dp [ MAX ] [ MAX ] [ MAX ] ; memset ( dp , -1 , sizeof dp ) ; return countMin ( arr , dp , n , MAX - 2 , MAX - 1 , 0 ) ; } int main ( ) { int n = 12 ; int arr [ MAX ] = { 7 , 8 , 1 , 2 , 4 , 6 , 3 , 5 , 2 , 1 , 8 , 7 } ; cout << wrapper ( arr , n ) << endl ; return 0 ; } |
Find all distinct subset ( or subsequence ) sums of an array | C ++ program to print distinct subset sums of a given array . ; sum denotes the current sum of the subset currindex denotes the index we have reached in the given array ; This function mainly calls recursive function distSumRec ( ) to generate distinct sum subsets . And finally prints the generated subsets . ; Print the result ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void distSumRec ( int arr [ ] , int n , int sum , int currindex , unordered_set < int > & s ) { if ( currindex > n ) return ; if ( currindex == n ) { s . insert ( sum ) ; return ; } distSumRec ( arr , n , sum + arr [ currindex ] , currindex + 1 , s ) ; distSumRec ( arr , n , sum , currindex + 1 , s ) ; } void printDistSum ( int arr [ ] , int n ) { unordered_set < int > s ; distSumRec ( arr , n , 0 , 0 , s ) ; for ( auto i = s . begin ( ) ; i != s . end ( ) ; i ++ ) cout << * i << " β " ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printDistSum ( arr , n ) ; return 0 ; } |
Find all distinct subset ( or subsequence ) sums of an array | C ++ program to print distinct subset sums of a given array . ; Uses Dynamic Programming to find distinct subset sums ; dp [ i ] [ j ] would be true if arr [ 0. . i - 1 ] has a subset with sum equal to j . ; There is always a subset with 0 sum ; Fill dp [ ] [ ] in bottom up manner ; Sums that were achievable without current array element ; Print last row elements ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printDistSum ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; bool dp [ n + 1 ] [ sum + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 0 ; i <= n ; i ++ ) dp [ i ] [ 0 ] = true ; for ( int i = 1 ; i <= n ; i ++ ) { dp [ i ] [ arr [ i - 1 ] ] = true ; for ( int j = 1 ; j <= sum ; j ++ ) { if ( dp [ i - 1 ] [ j ] == true ) { dp [ i ] [ j ] = true ; dp [ i ] [ j + arr [ i - 1 ] ] = true ; } } } for ( int j = 0 ; j <= sum ; j ++ ) if ( dp [ n ] [ j ] == true ) cout << j << " β " ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printDistSum ( arr , n ) ; return 0 ; } |
Super Ugly Number ( Number whose prime factors are in given set ) | C ++ program for super ugly number ; function will return the nth super ugly number ; n cannot be negative hence return - 1 if n is 0 or - ve ; Declare a min heap priority queue ; Push all the array elements to priority queue ; once count = n we return no ; Get the minimum value from priority_queue ; If top of pq is no then don 't increment count. This to avoid duplicate counting of same no. ; Push all the multiples of no . to priority_queue ; cnt += 1 ; ; Return nth super ugly number ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ugly ( int a [ ] , int size , int n ) { if ( n <= 0 ) return -1 ; if ( n == 1 ) return 1 ; priority_queue < int , vector < int > , greater < int > > pq ; for ( int i = 0 ; i < size ; i ++ ) { pq . push ( a [ i ] ) ; } int count = 1 , no ; while ( count < n ) { no = pq . top ( ) ; pq . pop ( ) ; if ( no != pq . top ( ) ) { count ++ ; for ( int i = 0 ; i < size ; i ++ ) { pq . push ( no * a [ i ] ) ; } } } return no ; } int main ( ) { int a [ 3 ] = { 2 , 3 , 5 } ; int size = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << ugly ( a , size , 10 ) << endl ; return 0 ; } |
Count number of ways to reach destination in a Maze | C ++ program to count number of paths in a maze with obstacles . ; Returns count of possible paths in a maze [ R ] [ C ] from ( 0 , 0 ) to ( R - 1 , C - 1 ) ; If the initial cell is blocked , there is no way of moving anywhere ; Initializing the leftmost column ; If we encounter a blocked cell in leftmost row , there is no way of visiting any cell directly below it . ; Similarly initialize the topmost row ; If we encounter a blocked cell in bottommost row , there is no way of visiting any cell directly below it . ; The only difference is that if a cell is - 1 , simply ignore it else recursively compute count value maze [ i ] [ j ] ; If blockage is found , ignore this cell ; If we can reach maze [ i ] [ j ] from maze [ i - 1 ] [ j ] then increment count . ; If we can reach maze [ i ] [ j ] from maze [ i ] [ j - 1 ] then increment count . ; If the final cell is blocked , output 0 , otherwise the answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 4 NEW_LINE #define C 4 NEW_LINE int countPaths ( int maze [ ] [ C ] ) { if ( maze [ 0 ] [ 0 ] == -1 ) return 0 ; for ( int i = 0 ; i < R ; i ++ ) { if ( maze [ i ] [ 0 ] == 0 ) maze [ i ] [ 0 ] = 1 ; else break ; } for ( int i = 1 ; i < C ; i ++ ) { if ( maze [ 0 ] [ i ] == 0 ) maze [ 0 ] [ i ] = 1 ; else break ; } for ( int i = 1 ; i < R ; i ++ ) { for ( int j = 1 ; j < C ; j ++ ) { if ( maze [ i ] [ j ] == -1 ) continue ; if ( maze [ i - 1 ] [ j ] > 0 ) maze [ i ] [ j ] = ( maze [ i ] [ j ] + maze [ i - 1 ] [ j ] ) ; if ( maze [ i ] [ j - 1 ] > 0 ) maze [ i ] [ j ] = ( maze [ i ] [ j ] + maze [ i ] [ j - 1 ] ) ; } } return ( maze [ R - 1 ] [ C - 1 ] > 0 ) ? maze [ R - 1 ] [ C - 1 ] : 0 ; } int main ( ) { int maze [ R ] [ C ] = { { 0 , 0 , 0 , 0 } , { 0 , -1 , 0 , 0 } , { -1 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; cout << countPaths ( maze ) ; return 0 ; } |
Minimum sum subsequence such that at least one of every four consecutive elements is picked | C ++ program to find minimum sum subsequence of an array such that one of every four consecutive elements is picked . ; Returns sum of minimum sum subsequence such that one of every four consecutive elements is picked from arr [ ] . ; dp [ i ] is going to store minimum sum subsequence of arr [ 0. . i ] such that arr [ i ] is part of the solution . Note that this may not be the best solution for subarray arr [ 0. . i ] ; If there is single value , we get the minimum sum equal to arr [ 0 ] ; If there are two values , we get the minimum sum equal to the minimum of two values ; If there are three values , return minimum of the three elements of array ; If there are four values , return minimum of the four elements of array ; Return the minimum of last 4 index ; Driver code | #include <iostream> NEW_LINE using namespace std ; int minSum ( int arr [ ] , int n ) { int dp [ n ] ; if ( n == 1 ) return arr [ 0 ] ; if ( n == 2 ) return min ( arr [ 0 ] , arr [ 1 ] ) ; if ( n == 3 ) return min ( arr [ 0 ] , min ( arr [ 1 ] , arr [ 2 ] ) ) ; if ( n == 4 ) return min ( min ( arr [ 0 ] , arr [ 1 ] ) , min ( arr [ 2 ] , arr [ 3 ] ) ) ; dp [ 0 ] = arr [ 0 ] ; dp [ 1 ] = arr [ 1 ] ; dp [ 2 ] = arr [ 2 ] ; dp [ 3 ] = arr [ 3 ] ; for ( int i = 4 ; i < n ; i ++ ) dp [ i ] = arr [ i ] + min ( min ( dp [ i - 1 ] , dp [ i - 2 ] ) , min ( dp [ i - 3 ] , dp [ i - 4 ] ) ) ; return min ( min ( dp [ n - 1 ] , dp [ n - 2 ] ) , min ( dp [ n - 4 ] , dp [ n - 3 ] ) ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 3 , 4 , 5 , 6 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minSum ( arr , n ) ; return 0 ; } |
Maximum decimal value path in a binary matrix | C ++ program to find maximum decimal value path in binary matrix ; Returns maximum decimal value in binary matrix . Here p indicate power of 2 ; Out of matrix boundary ; If current matrix value is 1 then return result + power ( 2 , p ) else result ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE long long int maxDecimalValue ( int mat [ ] [ N ] , int i , int j , int p ) { if ( i >= N j >= N ) return 0 ; int result = max ( maxDecimalValue ( mat , i , j + 1 , p + 1 ) , maxDecimalValue ( mat , i + 1 , j , p + 1 ) ) ; if ( mat [ i ] [ j ] == 1 ) return pow ( 2 , p ) + result ; else return result ; } int main ( ) { int mat [ ] [ 4 ] = { { 1 , 1 , 0 , 1 } , { 0 , 1 , 1 , 0 } , { 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 1 } , } ; cout << maxDecimalValue ( mat , 0 , 0 , 0 ) << endl ; return 0 ; } |
Maximum decimal value path in a binary matrix | C ++ program to find Maximum decimal value Path in Binary matrix ; Returns maximum decimal value in binary matrix . Here p indicate power of 2 ; Compute binary stream of first row of matrix and store result in dp [ 0 ] [ i ] ; indicate 1 * ( 2 ^ i ) + result of previous ; indicate 0 * ( 2 ^ i ) + result of previous ; Compute binary stream of first column of matrix and store result in dp [ i ] [ 0 ] ; indicate 1 * ( 2 ^ i ) + result of previous ; indicate 0 * ( 2 ^ i ) + result of previous ; Traversal rest Binary matrix and Compute maximum decimal value ; Here ( i + j ) indicate the current power of 2 in path that is 2 ^ ( i + j ) ; Return maximum decimal value in binary matrix ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE long long int MaximumDecimalValue ( int mat [ ] [ N ] , int n ) { int dp [ n ] [ n ] ; memset ( dp , 0 , sizeof ( dp ) ) ; if ( mat [ 0 ] [ 0 ] == 1 ) for ( int i = 1 ; i < n ; i ++ ) { if ( mat [ 0 ] [ i ] == 1 ) dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + pow ( 2 , i ) ; else dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] ; } for ( int i = 1 ; i < n ; i ++ ) { if ( mat [ i ] [ 0 ] == 1 ) dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + pow ( 2 , i ) ; else dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] ; } for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) dp [ i ] [ j ] = max ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j ] ) + pow ( 2 , i + j ) ; else dp [ i ] [ j ] = max ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j ] ) ; } } return dp [ n - 1 ] [ n - 1 ] ; } int main ( ) { int mat [ ] [ 4 ] = { { 1 , 1 , 0 , 1 } , { 0 , 1 , 1 , 0 } , { 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 1 } , } ; cout << MaximumDecimalValue ( mat , 4 ) << endl ; return 0 ; } |
Count All Palindrome Sub | C ++ program to find palindromic substrings of a string ; Returns total number of palindrome substring of length greater then equal to 2 ; create empty 2 - D matrix that counts all palindrome substring . dp [ i ] [ j ] stores counts of palindromic substrings in st [ i . . j ] ; P [ i ] [ j ] = true if substring str [ i . . j ] is palindrome , else false ; palindrome of single length ; palindrome of length 2 ; Palindromes of length more than 2. This loop is similar to Matrix Chain Multiplication . We start with a gap of length 2 and fill the DP table in a way that gap between starting and ending indexes increases one by one by outer loop . ; Pick starting point for current gap ; Set ending point ; If current string is palindrome ; Add current palindrome substring ( + 1 ) and rest palindrome substring ( dp [ i ] [ j - 1 ] + dp [ i + 1 ] [ j ] ) remove common palindrome substrings ( - dp [ i + 1 ] [ j - 1 ] ) ; return total palindromic substrings ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountPS ( char str [ ] , int n ) { int dp [ n ] [ n ] ; memset ( dp , 0 , sizeof ( dp ) ) ; bool P [ n ] [ n ] ; memset ( P , false , sizeof ( P ) ) ; for ( int i = 0 ; i < n ; i ++ ) P [ i ] [ i ] = true ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( str [ i ] == str [ i + 1 ] ) { P [ i ] [ i + 1 ] = true ; dp [ i ] [ i + 1 ] = 1 ; } } for ( int gap = 2 ; gap < n ; gap ++ ) { for ( int i = 0 ; i < n - gap ; i ++ ) { int j = gap + i ; if ( str [ i ] == str [ j ] && P [ i + 1 ] [ j - 1 ] ) P [ i ] [ j ] = true ; if ( P [ i ] [ j ] == true ) dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + dp [ i + 1 ] [ j ] + 1 - dp [ i + 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + dp [ i + 1 ] [ j ] - dp [ i + 1 ] [ j - 1 ] ; } } return dp [ 0 ] [ n - 1 ] ; } int main ( ) { char str [ ] = " abaab " ; int n = strlen ( str ) ; cout << CountPS ( str , n ) << endl ; return 0 ; } |
Maximum subsequence sum such that no three are consecutive | C ++ program to find the maximum sum such that no three are consecutive ; Returns maximum subsequence sum such that no three elements are consecutive ; Stores result for subarray arr [ 0. . i ] , i . e . , maximum possible sum in subarray arr [ 0. . i ] such that no three elements are consecutive . ; Base cases ( process first three elements ) ; Process rest of the elements We have three cases 1 ) Exclude arr [ i ] , i . e . , sum [ i ] = sum [ i - 1 ] 2 ) Exclude arr [ i - 1 ] , i . e . , sum [ i ] = sum [ i - 2 ] + arr [ i ] 3 ) Exclude arr [ i - 2 ] , i . e . , sum [ i - 3 ] + arr [ i ] + arr [ i - 1 ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumWO3Consec ( int arr [ ] , int n ) { int sum [ n ] ; if ( n >= 1 ) sum [ 0 ] = arr [ 0 ] ; if ( n >= 2 ) sum [ 1 ] = arr [ 0 ] + arr [ 1 ] ; if ( n > 2 ) sum [ 2 ] = max ( sum [ 1 ] , max ( arr [ 1 ] + arr [ 2 ] , arr [ 0 ] + arr [ 2 ] ) ) ; for ( int i = 3 ; i < n ; i ++ ) sum [ i ] = max ( max ( sum [ i - 1 ] , sum [ i - 2 ] + arr [ i ] ) , arr [ i ] + arr [ i - 1 ] + sum [ i - 3 ] ) ; return sum [ n - 1 ] ; } int main ( ) { int arr [ ] = { 100 , 1000 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSumWO3Consec ( arr , n ) ; return 0 ; } |
Maximum sum of pairs with specific difference | C ++ program to find maximum pair sum whose difference is less than K ; method to return maximum sum we can get by finding less than K difference pair ; Sort input array in ascending order . ; dp [ i ] denotes the maximum disjoint pair sum we can achieve using first i elements ; if no element then dp value will be 0 ; first give previous value to dp [ i ] i . e . no pairing with ( i - 1 ) th element ; if current and previous element can form a pair ; update dp [ i ] by choosing maximum between pairing and not pairing ; last index will have the result ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumPairWithDifferenceLessThanK ( int arr [ ] , int N , int K ) { sort ( arr , arr + N ) ; int dp [ N ] ; dp [ 0 ] = 0 ; for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] = dp [ i - 1 ] ; if ( arr [ i ] - arr [ i - 1 ] < K ) { if ( i >= 2 ) dp [ i ] = max ( dp [ i ] , dp [ i - 2 ] + arr [ i ] + arr [ i - 1 ] ) ; else dp [ i ] = max ( dp [ i ] , arr [ i ] + arr [ i - 1 ] ) ; } } return dp [ N - 1 ] ; } int main ( ) { int arr [ ] = { 3 , 5 , 10 , 15 , 17 , 12 , 9 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int K = 4 ; cout << maxSumPairWithDifferenceLessThanK ( arr , N , K ) ; return 0 ; } |
Lucas Numbers | Recursive C / C ++ program to find n 'th Lucas number ; recursive function ; Base cases ; recurrence relation ; Driver Code | #include <stdio.h> NEW_LINE int lucas ( int n ) { if ( n == 0 ) return 2 ; if ( n == 1 ) return 1 ; return lucas ( n - 1 ) + lucas ( n - 2 ) ; } int main ( ) { int n = 9 ; printf ( " % d " , lucas ( n ) ) ; return 0 ; } |
Recursively break a number in 3 parts to get maximum sum | A simple recursive C ++ program to find maximum sum by recursively breaking a number in 3 parts . ; Function to find the maximum sum ; base conditions ; recursively break the number and return what maximum you can get ; Driver program to run the case | #include <bits/stdc++.h> NEW_LINE using namespace std ; int breakSum ( int n ) { if ( n == 0 n == 1 ) return n ; return max ( ( breakSum ( n / 2 ) + breakSum ( n / 3 ) + breakSum ( n / 4 ) ) , n ) ; } int main ( ) { int n = 12 ; cout << breakSum ( n ) ; return 0 ; } |
Count All Palindromic Subsequence in a given String | Counts Palindromic Subsequence in a given String ; Function return the total palindromic subsequence ; create a 2D array to store the count of palindromic subsequence ; palindromic subsequence of length 1 ; check subsequence of length L is palindrome or not ; return total palindromic subsequence ; Driver program | #include <cstring> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int countPS ( string str ) { int N = str . length ( ) ; int cps [ N + 1 ] [ N + 1 ] ; memset ( cps , 0 , sizeof ( cps ) ) ; for ( int i = 0 ; i < N ; i ++ ) cps [ i ] [ i ] = 1 ; for ( int L = 2 ; L <= N ; L ++ ) { for ( int i = 0 ; i <= N - L ; i ++ ) { int k = L + i - 1 ; if ( str [ i ] == str [ k ] ) cps [ i ] [ k ] = cps [ i ] [ k - 1 ] + cps [ i + 1 ] [ k ] + 1 ; else cps [ i ] [ k ] = cps [ i ] [ k - 1 ] + cps [ i + 1 ] [ k ] - cps [ i + 1 ] [ k - 1 ] ; } } return cps [ 0 ] [ N - 1 ] ; } int main ( ) { string str = " abcb " ; cout << " Total β palindromic β subsequence β are β : β " << countPS ( str ) << endl ; return 0 ; } |
Count All Palindromic Subsequence in a given String | C ++ program to counts Palindromic Subsequence in a given String using recursion ; Function return the total palindromic subsequence ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int n , dp [ 1000 ] [ 1000 ] ; string str = " abcb " ; int countPS ( int i , int j ) { if ( i > j ) return 0 ; if ( dp [ i ] [ j ] != -1 ) return dp [ i ] [ j ] ; if ( i == j ) return dp [ i ] [ j ] = 1 ; else if ( str [ i ] == str [ j ] ) return dp [ i ] [ j ] = countPS ( i + 1 , j ) + countPS ( i , j - 1 ) + 1 ; else return dp [ i ] [ j ] = countPS ( i + 1 , j ) + countPS ( i , j - 1 ) - countPS ( i + 1 , j - 1 ) ; } int main ( ) { memset ( dp , -1 , sizeof ( dp ) ) ; n = str . size ( ) ; cout << " Total β palindromic β subsequence β are β : β " << countPS ( 0 , n - 1 ) << endl ; return 0 ; } |
Count all increasing subsequences | C ++ program to count increasing subsequences in an array of digits . ; Function To Count all the sub - sequences possible in which digit is greater than all previous digits arr [ ] is array of n digits ; count [ ] array is used to store all sub - sequences possible using that digit count [ ] array covers all the digit from 0 to 9 ; scan each digit in arr [ ] ; count all possible sub - sequences by the digits less than arr [ i ] digit ; store sum of all sub - sequences plus 1 in count [ ] array ; now sum up the all sequences possible in count [ ] array ; Driver program to run the test case | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSub ( int arr [ ] , int n ) { int count [ 10 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = arr [ i ] - 1 ; j >= 0 ; j -- ) count [ arr [ i ] ] += count [ j ] ; count [ arr [ i ] ] ++ ; } int result = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) result += count [ i ] ; return result ; } int main ( ) { int arr [ ] = { 3 , 2 , 4 , 5 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSub ( arr , n ) ; return 0 ; } |
Find minimum sum such that one of every three consecutive elements is taken | A Dynamic Programming based C ++ program to find minimum possible sum of elements of array such that an element out of every three consecutive is picked . ; A utility function to find minimum of 3 elements ; Returns minimum possible sum of elements such that an element out of every three consecutive elements is picked . ; Create a DP table to store results of subproblems . sum [ i ] is going to store minimum possible sum when arr [ i ] is part of the solution . ; When there are less than or equal to 3 elements ; Iterate through all other elements ; Driver code | #include <iostream> NEW_LINE using namespace std ; int minimum ( int a , int b , int c ) { return min ( min ( a , b ) , c ) ; } int findMinSum ( int arr [ ] , int n ) { int sum [ n ] ; sum [ 0 ] = arr [ 0 ] ; sum [ 1 ] = arr [ 1 ] ; sum [ 2 ] = arr [ 2 ] ; for ( int i = 3 ; i < n ; i ++ ) sum [ i ] = arr [ i ] + minimum ( sum [ i - 3 ] , sum [ i - 2 ] , sum [ i - 1 ] ) ; return minimum ( sum [ n - 1 ] , sum [ n - 2 ] , sum [ n - 3 ] ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 20 , 2 , 10 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Min β Sum β is β " << findMinSum ( arr , n ) ; return 0 ; } |
Count Distinct Subsequences | C ++ program to print distinct subsequences of a given string ; Create an empty set to store the subsequences ; Function for generating the subsequences ; Base Case ; Insert each generated subsequence into the set ; Recursive Case ; When a particular character is taken ; When a particular character isn 't taken ; Driver Code ; Function Call ; Output will be the number of elements in the set | #include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_set < string > sn ; void subsequences ( char s [ ] , char op [ ] , int i , int j ) { if ( s [ i ] == ' \0' ) { op [ j ] = ' \0' ; sn . insert ( op ) ; return ; } else { op [ j ] = s [ i ] ; subsequences ( s , op , i + 1 , j + 1 ) ; subsequences ( s , op , i + 1 , j ) ; return ; } } int main ( ) { char str [ ] = " ggg " ; int m = sizeof ( str ) / sizeof ( char ) ; int n = pow ( 2 , m ) + 1 ; subsequences ( str , op , 0 , 0 ) ; cout << sn . size ( ) ; sn . clear ( ) ; return 0 ; } |
Count Distinct Subsequences | C ++ program for above approach ; Returns count of distinct subsequences of str . ; Iterate from 0 to s . length ( ) ; Iterate from 0 to s . length ( ) ; Check if i equal to 0 ; Replace levelCount withe allCount + 1 ; If map is less than 0 ; Return answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSub ( string s ) { map < char , int > Map ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { Map [ s [ i ] ] = -1 ; } int allCount = 0 ; int levelCount = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s [ i ] ; if ( i == 0 ) { allCount = 1 ; Map = 1 ; levelCount = 1 ; continue ; } levelCount = allCount + 1 ; if ( Map < 0 ) { allCount = allCount + levelCount ; } else { allCount = allCount + levelCount - Map ; } Map = levelCount ; } return allCount ; } int main ( ) { string list [ ] = { " abab " , " gfg " } ; for ( string s : list ) { int cnt = countSub ( s ) ; int withEmptyString = cnt + 1 ; cout << " With β empty β string β count β for β " << s << " β is β " << withEmptyString << endl ; cout << " Without β empty β string β count β for β " << s << " β is β " << cnt << endl ; } return 0 ; } |
Minimum cost to fill given weight in a bag | C ++ program to find minimum cost to get exactly W Kg with given packets ; cost [ ] initial cost array including unavailable packet W capacity of bag ; val [ ] and wt [ ] arrays val [ ] array to store cost of ' i ' kg packet of orange wt [ ] array weight of packet of orange ; traverse the original cost [ ] array and skip unavailable packets and make val [ ] and wt [ ] array . size variable tells the available number of distinct weighted packets ; fill 0 th row with infinity ; fill 0 'th column with 0 ; now check for each weight one by one and fill the matrix according to the condition ; wt [ i - 1 ] > j means capacity of bag is less then weight of item ; here we check we get minimum cost either by including it or excluding it ; exactly weight W can not be made by given weights ; Driver program to run the test case | #include <bits/stdc++.h> NEW_LINE #define INF 1000000 NEW_LINE using namespace std ; int MinimumCost ( int cost [ ] , int n , int W ) { vector < int > val , wt ; int size = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( cost [ i ] != -1 ) { val . push_back ( cost [ i ] ) ; wt . push_back ( i + 1 ) ; size ++ ; } } n = size ; int min_cost [ n + 1 ] [ W + 1 ] ; for ( int i = 0 ; i <= W ; i ++ ) min_cost [ 0 ] [ i ] = INF ; for ( int i = 1 ; i <= n ; i ++ ) min_cost [ i ] [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= W ; j ++ ) { if ( wt [ i - 1 ] > j ) min_cost [ i ] [ j ] = min_cost [ i - 1 ] [ j ] ; else min_cost [ i ] [ j ] = min ( min_cost [ i - 1 ] [ j ] , min_cost [ i ] [ j - wt [ i - 1 ] ] + val [ i - 1 ] ) ; } } return ( min_cost [ n ] [ W ] == INF ) ? -1 : min_cost [ n ] [ W ] ; } int main ( ) { int cost [ ] = { 1 , 2 , 3 , 4 , 5 } , W = 5 ; int n = sizeof ( cost ) / sizeof ( cost [ 0 ] ) ; cout << MinimumCost ( cost , n , W ) ; return 0 ; } |
Find number of times a string occurs as a subsequence in given string | A Naive recursive C ++ program to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; Recursive function to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; If both first and second string is empty , or if second string is empty , return 1 ; If only first string is empty and second string is not empty , return 0 ; If last characters are same Recur for remaining strings by 1. considering last characters of both strings 2. ignoring last character of first string ; If last characters are different , ignore last char of first string and recur for remaining string ; Driver code | #include <iostream> NEW_LINE using namespace std ; int count ( string a , string b , int m , int n ) { if ( ( m == 0 && n == 0 ) n == 0 ) return 1 ; if ( m == 0 ) return 0 ; if ( a [ m - 1 ] == b [ n - 1 ] ) return count ( a , b , m - 1 , n - 1 ) + count ( a , b , m - 1 , n ) ; else return count ( a , b , m - 1 , n ) ; } int main ( ) { string a = " GeeksforGeeks " ; string b = " Gks " ; cout << count ( a , b , a . size ( ) , b . size ( ) ) << endl ; return 0 ; } |
Minimum Cost To Make Two Strings Identical | C ++ code to find minimum cost to make two strings identical ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; Returns cost of making X [ ] and Y [ ] identical . costX is cost of removing a character from X [ ] and costY is cost of removing a character from Y [ ] / ; Find LCS of X [ ] and Y [ ] ; Cost of making two strings identical is SUM of following two 1 ) Cost of removing extra characters from first string 2 ) Cost of removing extra characters from second string ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lcs ( char * X , char * Y , int m , int n ) { int L [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; else L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } return L [ m ] [ n ] ; } int findMinCost ( char X [ ] , char Y [ ] , int costX , int costY ) { int m = strlen ( X ) , n = strlen ( Y ) ; int len_LCS = lcs ( X , Y , m , n ) ; return costX * ( m - len_LCS ) + costY * ( n - len_LCS ) ; } int main ( ) { char X [ ] = " ef " ; char Y [ ] = " gh " ; cout << " Minimum β Cost β to β make β two β strings β " << " β identical β is β = β " << findMinCost ( X , Y , 10 , 20 ) ; return 0 ; } |
Weighted Job Scheduling | Set 2 ( Using LIS ) | C ++ program for weighted job scheduling using LIS ; A job has start time , finish time and profit . ; Utility function to calculate sum of all vector elements ; comparator function for sort function ; The main function that finds the maximum possible profit from given array of jobs ; Sort arr [ ] by start time . ; L [ i ] stores stores Weighted Job Scheduling of job [ 0. . i ] that ends with job [ i ] ; L [ 0 ] is equal to arr [ 0 ] ; start from index 1 ; for every j less than i ; L [ i ] = { MaxSum ( L [ j ] ) } + arr [ i ] where j < i and arr [ j ] . finish <= arr [ i ] . start ; find one with max profit ; Driver Function | #include <iostream> NEW_LINE #include <vector> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; struct Job { int start , finish , profit ; } ; int findSum ( vector < Job > arr ) { int sum = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) sum += arr [ i ] . profit ; return sum ; } int compare ( Job x , Job y ) { return x . start < y . start ; } void findMaxProfit ( vector < Job > & arr ) { sort ( arr . begin ( ) , arr . end ( ) , compare ) ; vector < vector < Job > > L ( arr . size ( ) ) ; L [ 0 ] . push_back ( arr [ 0 ] ) ; for ( int i = 1 ; i < arr . size ( ) ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( ( arr [ j ] . finish <= arr [ i ] . start ) && ( findSum ( L [ j ] ) > findSum ( L [ i ] ) ) ) L [ i ] = L [ j ] ; } L [ i ] . push_back ( arr [ i ] ) ; } vector < Job > maxChain ; for ( int i = 0 ; i < L . size ( ) ; i ++ ) if ( findSum ( L [ i ] ) > findSum ( maxChain ) ) maxChain = L [ i ] ; for ( int i = 0 ; i < maxChain . size ( ) ; i ++ ) cout << " ( " << maxChain [ i ] . start << " , β " << maxChain [ i ] . finish << " , β " << maxChain [ i ] . profit << " ) β " ; } int main ( ) { Job a [ ] = { { 3 , 10 , 20 } , { 1 , 2 , 50 } , { 6 , 19 , 100 } , { 2 , 100 , 200 } } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; vector < Job > arr ( a , a + n ) ; findMaxProfit ( arr ) ; return 0 ; } |
Printing Longest Common Subsequence | Set 2 ( Printing All ) | Dynamic Programming implementation of LCS problem ; Maximum string length ; Returns set containing all LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; construct a set to store possible LCS ; If we reaches end of either string , return a empty set ; If the last characters of X and Y are same ; recurse for X [ 0. . m - 2 ] and Y [ 0. . n - 2 ] in the matrix ; append current character to all possible LCS of substring X [ 0. . m - 2 ] and Y [ 0. . n - 2 ] . ; If the last characters of X and Y are not same ; If LCS can be constructed from top side of the matrix , recurse for X [ 0. . m - 2 ] and Y [ 0. . n - 1 ] ; If LCS can be constructed from left side of the matrix , recurse for X [ 0. . m - 1 ] and Y [ 0. . n - 2 ] ; merge two sets if L [ m - 1 ] [ n ] == L [ m ] [ n - 1 ] Note s will be empty if L [ m - 1 ] [ n ] != L [ m ] [ n - 1 ] ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Build L [ m + 1 ] [ n + 1 ] in bottom up fashion ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100 NEW_LINE int L [ N ] [ N ] ; set < string > findLCS ( string X , string Y , int m , int n ) { set < string > s ; if ( m == 0 n == 0 ) { s . insert ( " " ) ; return s ; } if ( X [ m - 1 ] == Y [ n - 1 ] ) { set < string > tmp = findLCS ( X , Y , m - 1 , n - 1 ) ; for ( string str : tmp ) s . insert ( str + X [ m - 1 ] ) ; } else { if ( L [ m - 1 ] [ n ] >= L [ m ] [ n - 1 ] ) s = findLCS ( X , Y , m - 1 , n ) ; if ( L [ m ] [ n - 1 ] >= L [ m - 1 ] [ n ] ) { set < string > tmp = findLCS ( X , Y , m , n - 1 ) ; s . insert ( tmp . begin ( ) , tmp . end ( ) ) ; } } return s ; } int LCS ( string X , string Y , int m , int n ) { for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; else L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } return L [ m ] [ n ] ; } int main ( ) { string X = " AGTGATG " ; string Y = " GTTAG " ; int m = X . length ( ) ; int n = Y . length ( ) ; cout << " LCS β length β is β " << LCS ( X , Y , m , n ) << endl ; set < string > s = findLCS ( X , Y , m , n ) ; for ( string str : s ) cout << str << endl ; return 0 ; } |
Number of non | A naive C ++ solution to count solutions of a + b + c = n ; Returns count of solutions of a + b + c = n ; Initialize result ; Consider all triplets and increment result whenever sum of a triplet is n . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countIntegralSolutions ( int n ) { int result = 0 ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= n - i ; j ++ ) for ( int k = 0 ; k <= ( n - i - j ) ; k ++ ) if ( i + j + k == n ) result ++ ; return result ; } int main ( ) { int n = 3 ; cout << countIntegralSolutions ( n ) ; return 0 ; } |
Number of non | A naive C ++ solution to count solutions of a + b + c = n ; Returns count of solutions of a + b + c = n ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countIntegralSolutions ( int n ) { return ( ( n + 1 ) * ( n + 2 ) ) / 2 ; } int main ( ) { int n = 3 ; cout << countIntegralSolutions ( n ) ; return 0 ; } |
Maximum absolute difference between sum of two contiguous sub | C ++ program to find two non - overlapping contiguous sub - arrays such that the absolute difference between the sum of two sub - array is maximum . ; Find maximum subarray sum for subarray [ 0. . i ] using standard Kadane ' s β algorithm . β This β version β of β Kadane ' s Algorithm will work if all numbers are negative . ; Find maximum subarray sum for subarray [ i . . n ] using Kadane ' s β algorithm . β This β version β of β Kadane ' s Algorithm will work if all numbers are negative ; The function finds two non - overlapping contiguous sub - arrays such that the absolute difference between the sum of two sub - array is maximum . ; create and build an array that stores maximum sums of subarrays that lie in arr [ 0. . . i ] ; create and build an array that stores maximum sums of subarrays that lie in arr [ i + 1. . . n - 1 ] ; Invert array ( change sign ) to find minumum sum subarrays . ; create and build an array that stores minimum sums of subarrays that lie in arr [ 0. . . i ] ; create and build an array that stores minimum sums of subarrays that lie in arr [ i + 1. . . n - 1 ] ; For each index i , take maximum of 1. abs ( max sum subarray that lies in arr [ 0. . . i ] - min sum subarray that lies in arr [ i + 1. . . n - 1 ] ) 2. abs ( min sum subarray that lies in arr [ 0. . . i ] - max sum subarray that lies in arr [ i + 1. . . n - 1 ] ) ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLeftSubArraySum ( int a [ ] , int size , int sum [ ] ) { int max_so_far = a [ 0 ] ; int curr_max = a [ 0 ] ; sum [ 0 ] = max_so_far ; for ( int i = 1 ; i < size ; i ++ ) { curr_max = max ( a [ i ] , curr_max + a [ i ] ) ; max_so_far = max ( max_so_far , curr_max ) ; sum [ i ] = max_so_far ; } return max_so_far ; } int maxRightSubArraySum ( int a [ ] , int n , int sum [ ] ) { int max_so_far = a [ n ] ; int curr_max = a [ n ] ; sum [ n ] = max_so_far ; for ( int i = n - 1 ; i >= 0 ; i -- ) { curr_max = max ( a [ i ] , curr_max + a [ i ] ) ; max_so_far = max ( max_so_far , curr_max ) ; sum [ i ] = max_so_far ; } return max_so_far ; } int findMaxAbsDiff ( int arr [ ] , int n ) { int leftMax [ n ] ; maxLeftSubArraySum ( arr , n , leftMax ) ; int rightMax [ n ] ; maxRightSubArraySum ( arr , n - 1 , rightMax ) ; int invertArr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) invertArr [ i ] = - arr [ i ] ; int leftMin [ n ] ; maxLeftSubArraySum ( invertArr , n , leftMin ) ; for ( int i = 0 ; i < n ; i ++ ) leftMin [ i ] = - leftMin [ i ] ; int rightMin [ n ] ; maxRightSubArraySum ( invertArr , n - 1 , rightMin ) ; for ( int i = 0 ; i < n ; i ++ ) rightMin [ i ] = - rightMin [ i ] ; int result = INT_MIN ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int absValue = max ( abs ( leftMax [ i ] - rightMin [ i + 1 ] ) , abs ( leftMin [ i ] - rightMax [ i + 1 ] ) ) ; if ( absValue > result ) result = absValue ; } return result ; } int main ( ) { int a [ ] = { -2 , -3 , 4 , -1 , -2 , 1 , 5 , -3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findMaxAbsDiff ( a , n ) ; return 0 ; } |
Find maximum length Snake sequence | C ++ program to find maximum length Snake sequence and print it ; Function to find maximum length Snake sequence path ( i , j ) corresponds to tail of the snake ; Function to find maximum length Snake sequence ; table to store results of subproblems ; initialize by 0 ; stores maximum length of Snake sequence ; store coordinates to snake 's tail ; fill the table in bottom - up fashion ; do except for ( 0 , 0 ) cell ; look above ; look left ; find maximum length Snake sequence path ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 4 NEW_LINE #define N 4 NEW_LINE struct Point { int x , y ; } ; list < Point > findPath ( int grid [ M ] [ N ] , int mat [ M ] [ N ] , int i , int j ) { list < Point > path ; Point pt = { i , j } ; path . push_front ( pt ) ; while ( grid [ i ] [ j ] != 0 ) { if ( i > 0 && grid [ i ] [ j ] - 1 == grid [ i - 1 ] [ j ] ) { pt = { i - 1 , j } ; path . push_front ( pt ) ; i -- ; } else if ( j > 0 && grid [ i ] [ j ] - 1 == grid [ i ] [ j - 1 ] ) { pt = { i , j - 1 } ; path . push_front ( pt ) ; j -- ; } } return path ; } void findSnakeSequence ( int mat [ M ] [ N ] ) { int lookup [ M ] [ N ] ; memset ( lookup , 0 , sizeof lookup ) ; int max_len = 0 ; int max_row = 0 ; int max_col = 0 ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i j ) { if ( i > 0 && abs ( mat [ i - 1 ] [ j ] - mat [ i ] [ j ] ) == 1 ) { lookup [ i ] [ j ] = max ( lookup [ i ] [ j ] , lookup [ i - 1 ] [ j ] + 1 ) ; if ( max_len < lookup [ i ] [ j ] ) { max_len = lookup [ i ] [ j ] ; max_row = i , max_col = j ; } } if ( j > 0 && abs ( mat [ i ] [ j - 1 ] - mat [ i ] [ j ] ) == 1 ) { lookup [ i ] [ j ] = max ( lookup [ i ] [ j ] , lookup [ i ] [ j - 1 ] + 1 ) ; if ( max_len < lookup [ i ] [ j ] ) { max_len = lookup [ i ] [ j ] ; max_row = i , max_col = j ; } } } } } cout << " Maximum β length β of β Snake β sequence β is : β " << max_len << endl ; list < Point > path = findPath ( lookup , mat , max_row , max_col ) ; cout << " Snake β sequence β is : " ; for ( auto it = path . begin ( ) ; it != path . end ( ) ; it ++ ) cout << endl << mat [ it -> x ] [ it -> y ] << " β ( " << it -> x << " , β " << it -> y << " ) " ; } int main ( ) { int mat [ M ] [ N ] = { { 9 , 6 , 5 , 2 } , { 8 , 7 , 6 , 5 } , { 7 , 3 , 1 , 6 } , { 1 , 1 , 1 , 7 } , } ; findSnakeSequence ( mat ) ; return 0 ; } |
Ways to arrange Balls such that adjacent balls are of different types | C ++ program to count number of ways to arrange three types of balls such that no two balls of same color are adjacent to each other ; Returns count of arrangements where last placed ball is ' last ' . ' last ' is 0 for ' p ' , 1 for ' q ' and 2 for ' r ' ; if number of balls of any color becomes less than 0 the number of ways arrangements is 0. ; If last ball required is of type P and the number of balls of P type is 1 while number of balls of other color is 0 the number of ways is 1. ; Same case as above for ' q ' and ' r ' ; if last ball required is P and the number of ways is the sum of number of ways to form sequence with ' p - 1' P balls , q Q Balls and r R balls ending with Q and R . ; Same as above case for ' q ' and ' r ' ; Returns count of required arrangements ; Three cases arise : return countWays ( p , q , r , 0 ) + Last required balls is type P countWays ( p , q , r , 1 ) + Last required balls is type Q countWays ( p , q , r , 2 ) ; Last required balls is type R ; Driver code to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int p , int q , int r , int last ) { if ( p < 0 q < 0 r < 0 ) return 0 ; if ( p == 1 && q == 0 && r == 0 && last == 0 ) return 1 ; if ( p == 0 && q == 1 && r == 0 && last == 1 ) return 1 ; if ( p == 0 && q == 0 && r == 1 && last == 2 ) return 1 ; if ( last == 0 ) return countWays ( p - 1 , q , r , 1 ) + countWays ( p - 1 , q , r , 2 ) ; if ( last == 1 ) return countWays ( p , q - 1 , r , 0 ) + countWays ( p , q - 1 , r , 2 ) ; if ( last == 2 ) return countWays ( p , q , r - 1 , 0 ) + countWays ( p , q , r - 1 , 1 ) ; } int countUtil ( int p , int q , int r ) { } int main ( ) { int p = 1 , q = 1 , r = 1 ; printf ( " % d " , countUtil ( p , q , r ) ) ; return 0 ; } |
Partition a set into two subsets such that the difference of subset sums is minimum | A Recursive C ++ program to solve minimum sum partition problem . ; Function to find the minimum sum ; If we have reached last element . Sum of one subset is sumCalculated , sum of other subset is sumTotal - sumCalculated . Return absolute difference of two sums . ; For every item arr [ i ] , we have two choices ( 1 ) We do not include it first set ( 2 ) We include it in first set We return minimum of two choices ; Returns minimum possible difference between sums of two subsets ; Compute total sum of elements ; Compute result using recursive function ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinRec ( int arr [ ] , int i , int sumCalculated , int sumTotal ) { if ( i == 0 ) return abs ( ( sumTotal - sumCalculated ) - sumCalculated ) ; return min ( findMinRec ( arr , i - 1 , sumCalculated + arr [ i - 1 ] , sumTotal ) , findMinRec ( arr , i - 1 , sumCalculated , sumTotal ) ) ; } int findMin ( int arr [ ] , int n ) { int sumTotal = 0 ; for ( int i = 0 ; i < n ; i ++ ) sumTotal += arr [ i ] ; return findMinRec ( arr , n , 0 , sumTotal ) ; } int main ( ) { int arr [ ] = { 3 , 1 , 4 , 2 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " The β minimum β difference β between β two β sets β is β " << findMin ( arr , n ) ; return 0 ; } |
Partition a set into two subsets such that the difference of subset sums is minimum | ; dp [ i ] gives whether is it possible to get i as sum of elements dd is helper variable we use dd to ignoring duplicates ; Initialising dp and dd ; sum = 0 is possible ; updating dd [ k ] as true if k can be formed using elements from 1 to i + 1 ; updating dd ; dd [ j ] = false ; reset dd ; checking the number from sum / 2 to 1 which is possible to get as sum ; since i is possible to form then another number is sum - i so mindifference is sum - i - i | #include <iostream> NEW_LINE using namespace std ; int minDifference ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; int y = sum / 2 + 1 ; bool dp [ y ] , dd [ y ] ; for ( int i = 0 ; i < y ; i ++ ) { dp [ i ] = dd [ i ] = false ; } dd [ 0 ] = true ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j + arr [ i ] < y ; j ++ ) { if ( dp [ j ] ) dd [ j + arr [ i ] ] = true ; } for ( int j = 0 ; j < y ; j ++ ) { if ( dd [ j ] ) dp [ j ] = true ; } } for ( int i = y - 1 ; i >= 0 ; i -- ) { if ( dp [ i ] ) return ( sum - 2 * i ) ; } } int main ( ) { int arr [ ] = { 1 , 6 , 11 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " The β Minimum β difference β of β 2 β sets β is β " << minDifference ( arr , n ) << ' ' ; return 0 ; } |
Count number of ways to partition a set into k subsets | A C ++ program to count number of partitions of a set with n elements into k subsets ; Returns count of different partitions of n elements in k subsets ; Base cases ; S ( n + 1 , k ) = k * S ( n , k ) + S ( n , k - 1 ) ; Driver program | #include <iostream> NEW_LINE using namespace std ; int countP ( int n , int k ) { if ( n == 0 k == 0 k > n ) return 0 ; if ( k == 1 k == n ) return 1 ; return k * countP ( n - 1 , k ) + countP ( n - 1 , k - 1 ) ; } int main ( ) { cout << countP ( 3 , 2 ) ; return 0 ; } |
Count number of ways to partition a set into k subsets | A Dynamic Programming based C ++ program to count number of partitions of a set with n elements into k subsets ; Returns count of different partitions of n elements in k subsets ; Table to store results of subproblems ; Base cases ; Fill rest of the entries in dp [ ] [ ] in bottom up manner ; Driver program | #include <iostream> NEW_LINE using namespace std ; int countP ( int n , int k ) { int dp [ n + 1 ] [ k + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) dp [ i ] [ 0 ] = 0 ; for ( int i = 0 ; i <= k ; i ++ ) dp [ 0 ] [ k ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = 1 ; j <= i ; j ++ ) if ( j == 1 i == j ) dp [ i ] [ j ] = 1 ; else dp [ i ] [ j ] = j * dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j - 1 ] ; return dp [ n ] [ k ] ; } int main ( ) { cout << countP ( 5 , 2 ) ; return 0 ; } |
Count number of ways to cover a distance | A naive recursive C ++ program to count number of ways to cover a distance with 1 , 2 and 3 steps ; Returns count of ways to cover ' dist ' ; Base cases ; Recur for all previous 3 and add the results ; driver program | #include <iostream> NEW_LINE using namespace std ; int printCountRec ( int dist ) { if ( dist < 0 ) return 0 ; if ( dist == 0 ) return 1 ; return printCountRec ( dist - 1 ) + printCountRec ( dist - 2 ) + printCountRec ( dist - 3 ) ; } int main ( ) { int dist = 4 ; cout << printCountRec ( dist ) ; return 0 ; } |
Count number of ways to cover a distance | A Dynamic Programming based C ++ program to count number of ways ; Create the array of size 3. ; Initialize the bases cases ; Run a loop from 3 to n Bottom up approach to fill the array ; driver program | #include <iostream> NEW_LINE using namespace std ; int printCountDP ( int dist ) { int ways [ 3 ] , n = dist ; ways [ 0 ] = 1 ; ways [ 1 ] = 1 ; ways [ 2 ] = 2 ; for ( int i = 3 ; i <= n ; i ++ ) ways [ i % 3 ] = ways [ ( i - 1 ) % 3 ] + ways [ ( i - 2 ) % 3 ] + ways [ ( i - 3 ) % 3 ] ; return ways [ n % 3 ] ; } int main ( ) { int dist = 4 ; cout << printCountDP ( dist ) ; return 0 ; } |
Count numbers from 1 to n that have 4 as a digit | A Simple C ++ program to compute sum of digits in numbers from 1 to n ; Returns sum of all digits in numbers from 1 to n ; One by one compute sum of digits in every number from 1 to n ; A utility function to compute sum of digits in a given number x ; Driver Program | #include <iostream> NEW_LINE using namespace std ; bool has4 ( int x ) ; int countNumbersWith4 ( int n ) { for ( int x = 1 ; x <= n ; x ++ ) result += has4 ( x ) ? 1 : 0 ; return result ; } bool has4 ( int x ) { while ( x != 0 ) { if ( x % 10 == 4 ) return true ; x = x / 10 ; } return false ; } int main ( ) { int n = 328 ; cout << " Count β of β numbers β from β 1 β to β " << n << " β that β have β 4 β as β a β a β digit β is β " << countNumbersWith4 ( n ) << endl ; return 0 ; } |
Count numbers from 1 to n that have 4 as a digit | C ++ program to count numbers having 4 as a digit ; Function to count numbers from 1 to n that have 4 as a digit ; Base case ; d = number of digits minus one in n . For 328 , d is 2 ; computing count of numbers from 1 to 10 ^ d - 1 , d = 0 a [ 0 ] = 0 ; d = 1 a [ 1 ] = count of numbers from 0 to 9 = 1 d = 2 a [ 2 ] = count of numbers from 0 to 99 = a [ 1 ] * 9 + 10 = 19 d = 3 a [ 3 ] = count of numbers from 0 to 999 = a [ 2 ] * 19 + 100 = 171 ; Computing 10 ^ d ; Most significant digit ( msd ) of n , For 328 , msd is 3 which can be obtained using 328 / 100 ; If MSD is 4. For example if n = 428 , then count of numbers is sum of following . 1 ) Count of numbers from 1 to 399 2 ) Count of numbers from 400 to 428 which is 29. ; IF MSD > 4. For example if n is 728 , then count of numbers is sum of following . 1 ) Count of numbers from 1 to 399 and count of numbers from 500 to 699 , i . e . , " a [ 2 ] β * β 6" 2 ) Count of numbers from 400 to 499 , i . e . 100 3 ) Count of numbers from 700 to 728 , recur for 28 ; IF MSD < 4. For example if n is 328 , then count of numbers is sum of following . 1 ) Count of numbers from 1 to 299 a 2 ) Count of numbers from 300 to 328 , recur for 28 ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countNumbersWith4 ( int n ) { if ( n < 4 ) return 0 ; int d = log10 ( n ) ; int * a = new int [ d + 1 ] ; a [ 0 ] = 0 , a [ 1 ] = 1 ; for ( int i = 2 ; i <= d ; i ++ ) a [ i ] = a [ i - 1 ] * 9 + ceil ( pow ( 10 , i - 1 ) ) ; int p = ceil ( pow ( 10 , d ) ) ; int msd = n / p ; if ( msd == 4 ) return ( msd ) * a [ d ] + ( n % p ) + 1 ; if ( msd > 4 ) return ( msd - 1 ) * a [ d ] + p + countNumbersWith4 ( n % p ) ; return ( msd ) * a [ d ] + countNumbersWith4 ( n % p ) ; } int main ( ) { int n = 328 ; cout << " Count β of β numbers β from β 1 β to β " << n << " β that β have β 4 β as β a β a β digit β is β " << countNumbersWith4 ( n ) << endl ; return 0 ; } |
Remove minimum elements from either side such that 2 * min becomes more than max | A O ( n * n ) solution to find the minimum of elements to be removed ; Returns the minimum number of removals from either end in arr [ l . . h ] so that 2 * min becomes greater than max . ; Initialize starting and ending indexes of the maximum sized subarray with property 2 * min > max ; Choose different elements as starting point ; Initialize min and max for the current start ; Choose different ending points for current start ; Update min and max if necessary ; If the property is violated , then no point to continue for a bigger array ; Update longest_start and longest_end if needed ; If not even a single element follow the property , then return n ; Return the number of elements to be removed ; Driver program to test above functions | #include <iostream> NEW_LINE #include <climits> NEW_LINE using namespace std ; int minRemovalsDP ( int arr [ ] , int n ) { int longest_start = -1 , longest_end = 0 ; for ( int start = 0 ; start < n ; start ++ ) { int min = INT_MAX , max = INT_MIN ; for ( int end = start ; end < n ; end ++ ) { int val = arr [ end ] ; if ( val < min ) min = val ; if ( val > max ) max = val ; if ( 2 * min <= max ) break ; if ( end - start > longest_end - longest_start longest_start == -1 ) { longest_start = start ; longest_end = end ; } } } if ( longest_start == -1 ) return n ; return ( n - ( longest_end - longest_start + 1 ) ) ; } int main ( ) { int arr [ ] = { 4 , 5 , 100 , 9 , 10 , 11 , 12 , 15 , 200 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minRemovalsDP ( arr , n ) ; return 0 ; } |
Optimal Strategy for a Game | DP | C ++ program to find out maximum value from a given sequence of coins ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Create a table to store solutions of subproblems ; Fill table using above recursive formula . Note that the table is filled in diagonal fashion ( similar to http : goo . gl / PQqoS ) , from diagonal elements to table [ 0 ] [ n - 1 ] which is the result . ; Here x is value of F ( i + 2 , j ) , y is F ( i + 1 , j - 1 ) and z is F ( i , j - 2 ) in above recursive formula ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int optimalStrategyOfGame ( int * arr , int n ) { int table [ n ] [ n ] ; for ( int gap = 0 ; gap < n ; ++ gap ) { for ( int i = 0 , j = gap ; j < n ; ++ i , ++ j ) { int x = ( ( i + 2 ) <= j ) ? table [ i + 2 ] [ j ] : 0 ; int y = ( ( i + 1 ) <= ( j - 1 ) ) ? table [ i + 1 ] [ j - 1 ] : 0 ; int z = ( i <= ( j - 2 ) ) ? table [ i ] [ j - 2 ] : 0 ; table [ i ] [ j ] = max ( arr [ i ] + min ( x , y ) , arr [ j ] + min ( y , z ) ) ; } } return table [ 0 ] [ n - 1 ] ; } 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 ; } |
Maximum Sum Increasing Subsequence | DP | Dynamic Programming implementation of Maximum Sum Increasing Subsequence ( MSIS ) problem ; maxSumIS ( ) returns the maximum sum of increasing subsequence in arr [ ] of size n ; Initialize msis values for all indexes ; Compute maximum sum values in bottom up manner ; Pick maximum of all msis values ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumIS ( int arr [ ] , int n ) { int i , j , max = 0 ; int msis [ n ] ; for ( i = 0 ; i < n ; i ++ ) msis [ i ] = arr [ i ] ; for ( i = 1 ; i < n ; i ++ ) for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && msis [ i ] < msis [ j ] + arr [ i ] ) msis [ i ] = msis [ j ] + arr [ i ] ; for ( i = 0 ; i < n ; i ++ ) if ( max < msis [ i ] ) max = msis [ i ] ; return max ; } int main ( ) { int arr [ ] = { 1 , 101 , 2 , 3 , 100 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Sum β of β maximum β sum β increasing β " " subsequence β is β " << maxSumIS ( arr , n ) << endl ; return 0 ; } |
C / C ++ Program for Longest Increasing Subsequence | A Naive C ++ recursive implementation of LIS problem ; To make use of recursive calls , this function must return two things : 1 ) Length of LIS ending with element arr [ n - 1 ] . We use max_ending_here for this purpose 2 ) Overall maximum as the LIS may end with an element before arr [ n - 1 ] max_ref is used this purpose . The value of LIS of full array of size n is stored in * max_ref which is our final result ; Base case ; ' max _ ending _ here ' is length of LIS ending with arr [ n - 1 ] ; Recursively get all LIS ending with arr [ 0 ] , arr [ 1 ] ... arr [ n - 2 ] . If arr [ i - 1 ] is smaller than arr [ n - 1 ] , and max ending with arr [ n - 1 ] needs to be updated , then update it ; Compare max_ending_here with the overall max . And update the overall max if needed ; Return length of LIS ending with arr [ n - 1 ] ; The wrapper function for _lis ( ) ; The max variable holds the result ; The function _lis ( ) stores its result in max ; returns max ; Driver code | #include <iostream> NEW_LINE using namespace std ; int _lis ( int arr [ ] , int n , int * max_ref ) { if ( n == 1 ) return 1 ; int res , max_ending_here = 1 ; for ( int i = 1 ; i < n ; i ++ ) { res = _lis ( arr , i , max_ref ) ; if ( arr [ i - 1 ] < arr [ n - 1 ] && res + 1 > max_ending_here ) max_ending_here = res + 1 ; } if ( * max_ref < max_ending_here ) * max_ref = max_ending_here ; return max_ending_here ; } int lis ( int arr [ ] , int n ) { int max = 1 ; _lis ( arr , n , & max ) ; return max ; } int main ( ) { int arr [ ] = { 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Length β of β lis β is β " << lis ( arr , n ) << " STRNEWLINE " ; return 0 ; } |
Find palindromic path of given length K in a complete Binary Weighted Graph | C ++ implementation for the above approach ; Function to print the left path ; j -> i -> j -> i -> j -> k -> j -> k -> j ; i -> j -> i -> j -> k -> j -> k ; Function to print the right path ; j -> i -> j -> i -> j -> k -> j -> k -> j ; i -> j -> i -> j -> k -> j -> k ; Function to check that if there exists a palindromic path in a binary graoh ; Create adjacency matrix ; If K is odd then print the path directly by choosing node 1 and 2 repeatedly ; If K is even Try to find an edge such that weight of edge i -> j and j -> i is equal ; Same weight edges are found ; Store their indexes ; Print the path ; If nodes i , j having equal weight on edges i -> j and j -> i can not be found then try to find three nodes i , j , k such that weights of edges i -> j and j -> k are equal ; To store edges with weight '0' ; To store edges with weight '1' ; Try to find edges i -> j and j -> k having weight 0 ; Print left Path ; Print centre ; Print right path ; Try to find edges i -> j and j -> k which having weight 1 ; cout << k ; ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printLeftPath ( int i , int j , int K ) { if ( K & 1 ) { for ( int p = 0 ; p < K ; p ++ ) { if ( p & 1 ) { cout << i << " β " ; } else { cout << j << " β " ; } } } else { for ( int p = 0 ; p < K ; p ++ ) { if ( p & 1 ) { cout << j << " β " ; } else { cout << i << " β " ; } } } } void printRightPath ( int j , int k , int K ) { if ( K & 1 ) { for ( int p = 0 ; p < K ; p ++ ) { if ( p & 1 ) { cout << k << " β " ; } else { cout << j << " β " ; } } } else { for ( int p = 0 ; p < K ; p ++ ) { if ( p & 1 ) { cout << k << " β " ; } else { cout << j << " β " ; } } } } void constructPalindromicPath ( vector < pair < pair < int , int > , char > > edges , int n , int K ) { vector < vector < char > > adj ( n + 1 , vector < char > ( n + 1 ) ) ; for ( int i = 0 ; i < edges . size ( ) ; i ++ ) { adj [ edges [ i ] . first . first ] [ edges [ i ] . first . second ] = edges [ i ] . second ; } if ( K & 1 ) { cout << " YES " << endl ; for ( int i = 1 ; i <= K + 1 ; i ++ ) { cout << ( i & 1 ) + 1 << " β " ; } return ; } bool found = 0 ; int idx1 , idx2 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( i == j ) { continue ; } if ( adj [ i ] [ j ] == adj [ j ] [ i ] ) { found = 1 ; idx1 = i , idx2 = j ; } } } if ( found ) { cout << " YES " << endl ; for ( int i = 1 ; i <= K + 1 ; i ++ ) { if ( i & 1 ) { cout << idx1 << " β " ; } else { cout << idx2 << " β " ; } } return ; } else { vector < int > mp1 [ n + 1 ] ; vector < int > mp2 [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( i == j ) { continue ; } if ( adj [ i ] [ j ] == '0' ) { mp1 [ i ] . push_back ( j ) ; } else { mp2 [ i ] . push_back ( j ) ; } } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( j == i ) { continue ; } if ( adj [ i ] [ j ] == '0' ) { if ( mp1 [ j ] . size ( ) ) { int k = mp1 [ j ] [ 0 ] ; if ( k == i k == j ) { continue ; } cout << " YES " << endl ; K -= 2 ; K /= 2 ; printLeftPath ( i , j , K ) ; cout << i << " β " << j << " β " << k << " β " ; printRightPath ( j , k , K ) ; return ; } } } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( j == i ) { continue ; } if ( adj [ i ] [ j ] == '1' ) { if ( mp1 [ j ] . size ( ) ) { int k = mp1 [ j ] [ 0 ] ; if ( k == i k == j ) { continue ; } cout << " YES " << endl ; K -= 2 ; K /= 2 ; printLeftPath ( i , j , K ) ; cout << i << " β " << j << " β " << k << " β " ; printRightPath ( j , k , K ) ; return ; } } } } } cout << " NO " ; } int main ( ) { int N = 3 , K = 4 ; vector < pair < pair < int , int > , char > > edges = { { { 1 , 2 } , '1' } , { { 1 , 3 } , '1' } , { { 2 , 1 } , '1' } , { { 2 , 3 } , '1' } , { { 3 , 1 } , '0' } , { { 3 , 2 } , '0' } } ; constructPalindromicPath ( edges , N , K ) ; } |
Find position i to split Array such that prefix sum till i | C ++ program for the above approach ; Function to check if there is an element forming G . P . series having common ratio k ; If size of array is less than three then return - 1 ; Initialize the variables ; Calculate total sum of array ; Calculate Middle element of G . P . series ; Iterate over the range ; Store the first element of G . P . series in the variable temp ; Return position of middle element of the G . P . series if the first element is in G . P . of common ratio k ; Else return 0 ; if middle element is not found in arr [ ] ; Driver Code ; Given array | #include <iostream> NEW_LINE using namespace std ; int checkArray ( int arr [ ] , int N , int k ) { if ( N < 3 ) return -1 ; int i , Sum = 0 , temp = 0 ; for ( i = 0 ; i < N ; i ++ ) Sum += arr [ i ] ; int R = ( k * k + k + 1 ) ; if ( Sum % R != 0 ) return 0 ; int Mid = k * ( Sum / R ) ; for ( i = 1 ; i < N - 1 ; i ++ ) { temp += arr [ i - 1 ] ; if ( arr [ i ] == Mid ) { if ( temp == Mid / k ) return i + 1 ; else return 0 ; } } return 0 ; } int main ( ) { int arr [ ] = { 5 , 1 , 4 , 20 , 6 , 15 , 9 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << checkArray ( arr , N , K ) << endl ; return 0 ; } |
Repeat last occurrence of each alphanumeric character to their position in character family times | C ++ program for the above approach ; Function to encode the given string ; Variable string to store the result ; Arrays to store the last occuring index of every character in the string ; Length of the string ; Iterate over the range ; If str [ i ] is between 0 and 9 ; If str [ i ] is between a and z ; If str [ i ] is between A and Z ; Iterate over the range ; If str [ i ] is between a and z and i is the last occurence in str ; If str [ i ] is between A and Z and i is the last occurence in str ; If str [ i ] is between 0 and 9 and i is the last occurence in str ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void encodeString ( string str ) { string res = " " ; int small [ 26 ] = { 0 } , capital [ 26 ] = { 0 } , num [ 10 ] = { 0 } ; int n = str . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] >= '0' && str [ i ] <= '9' ) { num [ str [ i ] - 48 ] = i ; } else if ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) { small [ str [ i ] - 97 ] = i ; } else if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) { capital [ str [ i ] - 65 ] = i ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) && small [ str [ i ] - 97 ] == i ) { int occ = str [ i ] - 96 ; while ( occ -- ) { res += str [ i ] ; } } else if ( ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) && capital [ str [ i ] - 65 ] == i ) { int occ = str [ i ] - 64 ; while ( occ -- ) { res += str [ i ] ; } } else if ( ( str [ i ] >= '0' && str [ i ] <= '9' ) && num [ str [ i ] - 48 ] == i ) { int occ = str [ i ] - 48 ; while ( occ -- ) { res += str [ i ] ; } } else { res += str [ i ] ; } } cout << res ; } int main ( ) { string str = " Ea2 , β 0 , β E " ; encodeString ( str ) ; return 0 ; } |
Form minimum number of Palindromic Strings from a given string | C ++ Program to implement the above approach ; Function to return minimum palindromic strings formed ; Store the length of string ; Iterate over the string and store the frequency of all charactrs A vector to store the frequency ; Store the odd frequency characters ; Iterate through all possible characters and check the parity of frequency ; store answer in a vector ; if there are no odd Frequency characters then print the string with even characters ; store the left part of the palindromic string ; reverse the right part of the string ; store the string in ans vector ; take any character from off frequency element ; repeat the above step to form left and right strings ; reverse the right part of the string ; store the string in ans vector ; store all other odd frequency strings ; Print the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumPalindromicStrings ( string S ) { int N = S . length ( ) ; vector < int > freq ( 26 ) ; for ( int i = 0 ; i < N ; i ++ ) { freq [ S [ i ] - ' a ' ] ++ ; } vector < int > oddFreqCharacters ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] & 1 ) { oddFreqCharacters . push_back ( i ) ; freq [ i ] -- ; } freq [ i ] /= 2 ; } vector < string > ans ; if ( oddFreqCharacters . empty ( ) ) { string left = " " ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < freq [ i ] ; j ++ ) { left += char ( i + ' a ' ) ; } } string right = left ; reverse ( right . begin ( ) , right . end ( ) ) ; ans . push_back ( left + right ) ; } else { string middle = " " ; int c = oddFreqCharacters . back ( ) ; oddFreqCharacters . pop_back ( ) ; middle += char ( c + ' a ' ) ; string left = " " ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < freq [ i ] ; j ++ ) { left += char ( i + ' a ' ) ; } } string right = left ; reverse ( right . begin ( ) , right . end ( ) ) ; ans . push_back ( left + middle + right ) ; while ( ! oddFreqCharacters . empty ( ) ) { int c = oddFreqCharacters . back ( ) ; oddFreqCharacters . pop_back ( ) ; string middle = " " ; middle += char ( c + ' a ' ) ; ans . push_back ( middle ) ; } } cout << " [ " ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { cout << ans [ i ] ; if ( i != ans . size ( ) - 1 ) { cout << " , β " ; } } cout << " ] " ; return 0 ; } int main ( ) { string S = " geeksforgeeks " ; minimumPalindromicStrings ( S ) ; } |
Make Array elements equal by replacing adjacent elements with their XOR | C ++ Program of the above approach ; Function to check if it is possible to make all the array elements equal using the given operation ; Stores the prefix XOR array ; Calculate prefix [ i ] ; Case 1 , check if the XOR of the input array is 0 ; Case 2 Iterate over all the ways to divide the array into three non empty subarrays ; XOR of Middle Block ; XOR of Left Block ; XOR of Right Block ; Not Possible ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void possibleEqualArray ( int A [ ] , int N ) { vector < int > pref ( N ) ; pref [ 0 ] = A [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { pref [ i ] = pref [ i - 1 ] ^ A [ i ] ; } if ( pref [ N - 1 ] == 0 ) { cout << " YES " ; return ; } int cur_xor = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { cur_xor ^= A [ i ] ; for ( int j = 0 ; j < i ; j ++ ) { if ( j ) { int middle_xor = pref [ j - 1 ] ^ pref [ i - 1 ] ; int left_xor = pref [ j - 1 ] ; int right_xor = cur_xor ; if ( left_xor == middle_xor && middle_xor == right_xor ) { cout << " YES " ; return ; } } } } cout << " NO " ; } int main ( ) { int A [ ] = { 0 , 2 , 2 } ; int N = sizeof ( A ) / sizeof ( int ) ; possibleEqualArray ( A , N ) ; return 0 ; } |
Construct an array whose Prefix XOR array starting from X is an N | C ++ program for the above approach ; Function to print the required array ; Iteratie from 1 to N ; Print the i - th element ; Update prev_xor to i ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void GenerateArray ( int N , int X ) { int prev_xor = X ; for ( int i = 1 ; i <= N ; i ++ ) { cout << ( i ^ prev_xor ) ; if ( i != N ) { cout << " β " ; } prev_xor = i ; } } int main ( ) { int N = 4 , X = 3 ; cout << " The β generated β array β is β " ; GenerateArray ( N , X ) ; return 0 ; } |
Check if elements of a Binary Matrix can be made alternating | C ++ program for the above approach ; Function to create the possible grids ; Function to test if any one of them matches with the given 2 - D array ; Function to print the grid , if possible ; Function to check if the grid can be made alternating or not ; Grids to store the possible grids ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void createGrid ( char grid [ ] [ 1001 ] , bool is1 , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( is1 ) { grid [ i ] [ j ] = '0' ; is1 = false ; } else { grid [ i ] [ j ] = '1' ; is1 = true ; } } if ( M % 2 == 0 ) is1 = ! is1 ; } } bool testGrid ( char testGrid [ ] [ 1001 ] , char Grid [ ] [ 1001 ] , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( Grid [ i ] [ j ] != ' * ' ) { if ( Grid [ i ] [ j ] != testGrid [ i ] [ j ] ) { return false ; } } } } return true ; } void printGrid ( char grid [ ] [ 1001 ] , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { cout << grid [ i ] [ j ] << " β " ; } cout << endl ; } } void findPossibleGrid ( int N , int M , char grid [ ] [ 1001 ] ) { char gridTest1 [ N ] [ 1001 ] , gridTest2 [ N ] [ 1001 ] ; createGrid ( gridTest1 , true , N , M ) ; createGrid ( gridTest2 , false , N , M ) ; if ( testGrid ( gridTest1 , grid , N , M ) ) { cout << " Yes STRNEWLINE " ; printGrid ( gridTest1 , N , M ) ; } else if ( testGrid ( gridTest2 , grid , N , M ) ) { cout << " Yes STRNEWLINE " ; printGrid ( gridTest2 , N , M ) ; } else { cout << " No STRNEWLINE " ; } } int main ( ) { int N = 4 , M = 4 ; char grid [ ] [ 1001 ] = { { ' * ' , ' * ' , '1' , '0' } , { ' * ' , ' * ' , ' * ' , ' * ' } , { ' * ' , ' * ' , ' * ' , ' * ' } , { ' * ' , ' * ' , '0' , '1' } } ; findPossibleGrid ( N , M , grid ) ; return 0 ; } |
Find non | C ++ program for the above approach . ; Function to find the possible output array ; Base case for the recursion ; If ind becomes half of the size then print the array . ; Exit the function . ; Iterate in the range . ; Put the values in the respective indices . ; Call the function to find values for other indices . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const long long INF64 = 1000000000000000000ll ; const int N = 200 * 1000 + 13 ; int n ; long long arr [ N ] , brr [ N ] ; void brute ( int ind , long long l , long long r ) { if ( ind == n / 2 ) { for ( int i = 0 ; i < int ( n ) ; i ++ ) printf ( " % lld β " , brr [ i ] ) ; puts ( " " ) ; exit ( 0 ) ; } for ( long long i = l ; i <= arr [ ind ] / 2 ; ++ i ) if ( arr [ ind ] - i <= r ) { brr [ ind ] = i ; brr [ n - ind - 1 ] = arr [ ind ] - i ; brute ( ind + 1 , i , arr [ ind ] - i ) ; } } int main ( ) { n = 2 ; n *= 2 ; arr [ 0 ] = 5 ; arr [ 1 ] = 6 ; brute ( 0 , 0 , INF64 ) ; return 0 ; } |
Find and Replace all occurrence of a substring in the given String | C ++ program for the above approach ; Function to replace all the occurrences of the substring S1 to S2 in string S ; Stores the resultant string ; Traverse the string s ; If the first character of string s1 matches with the current character in string s ; If the complete string matches or not ; If complete string matches then replace it with the string s2 ; Otherwise ; Otherwise ; Print the resultant string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void modifyString ( string & s , string & s1 , string & s2 ) { string ans = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int k = 0 ; if ( s [ i ] == s1 [ k ] && i + s1 . length ( ) <= s . length ( ) ) { int j ; for ( j = i ; j < i + s1 . length ( ) ; j ++ ) { if ( s [ j ] != s1 [ k ] ) { break ; } else { k = k + 1 ; } } if ( j == i + s1 . length ( ) ) { ans . append ( s2 ) ; i = j - 1 ; } else { ans . push_back ( s [ i ] ) ; } } else { ans . push_back ( s [ i ] ) ; } } cout << ans ; } int main ( ) { string S = " geeksforgeeks " ; string S1 = " eek " ; string S2 = " ok " ; modifyString ( S , S1 , S2 ) ; return 0 ; } |
Count of minimum numbers having K as the last digit required to obtain sum N | C ++ program for the above approach ; Stores the smallest number that ends with digit i ( 0 , 9 ) ; Stores the minimum number of steps to create a number ending with digit i ; Initialize elements as infinity ; Minimum number ending with digit i ; Minimum steps to create a number ending with digit i ; If N < SmallestNumber then , return - 1 ; Otherwise , return answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCount ( int N , int K ) { int SmallestNumber [ 10 ] ; int MinimumSteps [ 10 ] ; for ( int i = 0 ; i <= 9 ; i ++ ) { SmallestNumber [ i ] = INT_MAX ; MinimumSteps [ i ] = INT_MAX ; } for ( int i = 1 ; i <= 10 ; i ++ ) { int num = K * i ; SmallestNumber [ num % 10 ] = min ( SmallestNumber [ num % 10 ] , num ) ; MinimumSteps [ num % 10 ] = min ( MinimumSteps [ num % 10 ] , i ) ; } if ( N < SmallestNumber [ N % 10 ] ) { return -1 ; } else { return MinimumSteps [ N % 10 ] ; } } int main ( ) { int N = 42 , K = 7 ; cout << minCount ( N , K ) ; return 0 ; } |
Minimum number of operations required to make an array non | C ++ program for the above approach ; Function to count the minimum number of steps required to make arr non - decreasing ; Stores differences ; Stores the max number ; Traverse the array arr [ ] ; Update mx ; Update val ; Stores the result ; Iterate until 2 ^ res - 1 is less than val ; Return the answer ; Driver Code ; Given input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinSteps ( int arr [ ] , int N ) { int val = 0 ; int mx = INT_MIN ; for ( int i = 0 ; i < N ; i ++ ) { int curr = arr [ i ] ; mx = max ( mx , curr ) ; val = max ( val , mx - curr ) ; } long long res = 0 ; while ( ( 1LL << res ) - 1 < val ) { ++ res ; } return res ; } int main ( ) { int arr [ ] = { 1 , 7 , 6 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countMinSteps ( arr , N ) ; return 0 ; } |
Minimum XOR of at most K elements in range [ L , R ] | C ++ program for the above approach ; Function for K = 2 ; Function for K = 2 ; Function for K = 2 ; Function to calculate the minimum XOR of at most K elements in [ L , R ] ; Driver code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int func2 ( int L , int R , int K ) { if ( R - L >= 2 ) return 1 ; return min ( L , L ^ R ) ; } int func3 ( int L , int R , int K ) { if ( ( R ^ L ) > L && ( R ^ L ) < R ) return 0 ; return func2 ( L , R , K ) ; } int func4 ( int L , int R , int K ) { if ( R - L >= 4 ) return 0 ; int minval = L ^ ( L + 1 ) ^ ( L + 2 ) ^ ( L + 3 ) ; return min ( minval , func3 ( L , R , K ) ) ; } int minimumXor ( int L , int R , int K ) { if ( K > 4 ) return 0 ; else if ( K == 4 ) return func4 ( L , R , K ) ; else if ( K == 3 ) return func3 ( L , R , K ) ; else if ( K == 2 ) return func2 ( L , R , K ) ; else return L ; } int main ( ) { int L = 1 , R = 3 , K = 3 ; cout << minimumXor ( L , R , K ) << endl ; return 0 ; } |
Nth term of Ruler Function Series | C ++ program for the above approach ; Function to count the number of set bits in the number N ; Store the number of setbits ; Update the value of n ; Update the count ; Return the total count ; Function to find the Nth term of the Ruler Function Series ; Store the result ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int setBits ( long n ) { int count = 0 ; while ( n > 0 ) { n = n & ( n - 1 ) ; count ++ ; } return count ; } void findNthTerm ( int N ) { int x = setBits ( N ^ ( N - 1 ) ) ; cout << x ; } int main ( ) { int N = 8 ; findNthTerm ( N ) ; return 0 ; } |
Quadratic equation whose roots are reciprocal to the roots of given equation | C ++ program for the above approach ; Function to find the quadratic equation having reciprocal roots ; Print quadratic equation ; Driver Code ; Given coefficients ; Function call to find the quadratic equation having reciprocal roots | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findEquation ( int A , int B , int C ) { cout << " ( " << C << " ) " << " x ^ 2 β + ( " << B << " ) x β + β ( " << A << " ) β = β 0" ; } int main ( ) { int A = 1 , B = -5 , C = 6 ; findEquation ( A , B , C ) ; return 0 ; } |
Minimize subtraction followed by increments of adjacent elements required to make all array elements equal | C ++ program for the above approach ; Function to find the minimum number of moves required to make all array elements equal ; Store the total sum of the array ; Calculate total sum of the array ; If the sum is not divisible by N , then print " - 1" ; Stores the average ; Stores the count of operations ; Traverse the array arr [ ] ; Update number of moves required to make current element equal to avg ; Update the overall count ; Return the minimum operations required ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinMoves ( int arr [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; if ( sum % N != 0 ) return -1 ; int avg = sum / N ; int total = 0 ; int needCount = 0 ; for ( int i = 0 ; i < N ; i ++ ) { needCount += ( arr [ i ] - avg ) ; total = max ( max ( abs ( needCount ) , arr [ i ] - avg ) , total ) ; } return total ; } int main ( ) { int arr [ ] = { 1 , 0 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMinMoves ( arr , N ) ; return 0 ; } |
Maximum amount of money that can be collected by a player in a game of coins | CPP Program to implement the above approach ; Function to calculate the maximum amount collected by A ; Stores the money obtained by A ; Stores mid elements of odd sized rows ; Size of current row ; Increase money collected by A ; Add coins at even indices to the amount collected by A ; Print the amount ; Driver Code ; Function call to calculate the amount of coins collected by A | #include <bits/stdc++.h> NEW_LINE using namespace std ; void find ( int N , vector < vector < int > > Arr ) { int amount = 0 ; vector < int > mid_odd ; for ( int i = 0 ; i < N ; i ++ ) { int siz = Arr [ i ] . size ( ) ; for ( int j = 0 ; j < siz / 2 ; j ++ ) amount = amount + Arr [ i ] [ j ] ; if ( siz % 2 == 1 ) mid_odd . push_back ( Arr [ i ] [ siz / 2 ] ) ; } sort ( mid_odd . begin ( ) , mid_odd . end ( ) ) ; for ( int i = 0 ; i < mid_odd . size ( ) ; i ++ ) if ( i % 2 == 0 ) amount = amount + mid_odd [ i ] ; cout << amount << endl ; } int main ( ) { int N = 2 ; vector < vector < int > > Arr { { 5 , 2 , 3 , 4 } , { 1 , 6 } } ; find ( N , Arr ) ; } |
Check if an array can be split into K consecutive non | C ++ program for the above approach ; Function to check if array can be split into K consecutive and non - overlapping subarrays of length M consisting of a single distinct element ; Traverse over the range [ 0 , N - M - 1 ] ; Check if arr [ i ] is the same as arr [ i + m ] ; Increment current length t of pattern matched by 1 ; Check if t is equal to m , increment count of total repeated pattern ; Return true if length of total repeated pattern is k ; Update length of the current pattern ; Update count to 1 ; Finally return false if no pattern found ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string checkPattern ( int arr [ ] , int m , int k , int n ) { int count = 1 , t = 0 ; for ( int i = 0 ; i < n - m ; i ++ ) { if ( arr [ i ] == arr [ i + m ] ) { t ++ ; if ( t == m ) { t = 0 ; count ++ ; if ( count == k ) { return " Yes " ; } } } else { t = 0 ; count = 1 ; } } return " No " ; } int main ( ) { int arr [ ] = { 6 , 1 , 3 , 3 , 3 , 3 } ; int M = 1 , K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << checkPattern ( arr , M , K , N ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.