text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Minimum length of the reduced Array formed using given operations | C ++ implementation to find the minimum length of the array ; Function to find the length of minimized array ; Creating the required dp tables ; Initialising the dp table by - 1 ; base case ; Check if the two subarray can be combined ; Initialising dp1 table with max value ; Check if the subarray can be reduced to a single element ; Minimal partition of [ 1 : j - 1 ] + 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimalLength ( int a [ ] , int n ) { int dp [ n + 1 ] [ n + 1 ] , dp1 [ n ] ; int i , j , k ; memset ( dp , -1 , sizeof ( dp ) ) ; for ( int size = 1 ; size <= n ; size ++ ) { for ( i = 0 ; i < n - size + 1 ; i ++ ) { j = i + size - 1 ; if ( i == j ) dp [ i ] [ j ] = a [ i ] ; else { for ( k = i ; k < j ; k ++ ) { if ( dp [ i ] [ k ] != -1 && dp [ i ] [ k ] == dp [ k + 1 ] [ j ] ) dp [ i ] [ j ] = dp [ i ] [ k ] + 1 ; } } } } for ( i = 0 ; i < n ; i ++ ) dp1 [ i ] = 1e7 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j <= i ; j ++ ) { if ( dp [ j ] [ i ] != -1 ) { if ( j == 0 ) dp1 [ i ] = 1 ; else dp1 [ i ] = min ( dp1 [ i ] , dp1 [ j - 1 ] + 1 ) ; } } } return dp1 [ n - 1 ] ; } int main ( ) { int n = 7 ; int a [ n ] = { 3 , 3 , 4 , 4 , 4 , 3 , 3 } ; cout << minimalLength ( a , n ) ; return 0 ; }
Maximum score possible after performing given operations on an Array | C ++ program to find the maximum Score after given operations ; Memoizing by the use of a table ; Function to calculate maximum score ; Bse case ; If the same state has already been computed ; Sum of array in range ( l , r ) ; If the operation is even - numbered the score is decremented ; Exploring all paths , and storing maximum value in DP table to avoid further repetitive recursive calls ; Function to find the max score ; Prefix sum array ; Calculating prefix_sum ; Initialising the DP table , - 1 represents the subproblem hasn 't been solved yet ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100 ] [ 100 ] [ 100 ] ; int MaximumScoreDP ( int l , int r , int prefix_sum [ ] , int num ) { if ( l > r ) return 0 ; if ( dp [ l ] [ r ] [ num ] != -1 ) return dp [ l ] [ r ] [ num ] ; int current_sum = prefix_sum [ r ] - ( l - 1 >= 0 ? prefix_sum [ l - 1 ] : 0 ) ; if ( num % 2 == 0 ) current_sum *= -1 ; dp [ l ] [ r ] [ num ] = current_sum + max ( MaximumScoreDP ( l + 1 , r , prefix_sum , num + 1 ) , MaximumScoreDP ( l , r - 1 , prefix_sum , num + 1 ) ) ; return dp [ l ] [ r ] [ num ] ; } int findMaxScore ( int a [ ] , int n ) { int prefix_sum [ n ] = { 0 } ; prefix_sum [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { prefix_sum [ i ] = prefix_sum [ i - 1 ] + a [ i ] ; } memset ( dp , -1 , sizeof ( dp ) ) ; return MaximumScoreDP ( 0 , n - 1 , prefix_sum , 1 ) ; } int main ( ) { int n = 6 ; int A [ n ] = { 1 , 2 , 3 , 4 , 2 , 6 } ; cout << findMaxScore ( A , n ) ; return 0 ; }
Count number of binary strings without consecutive 1 Γ’ €ℒ s : Set 2 | C ++ program to count number of binary strings without consecutive 1 aTMs ; Table to store the solution of every sub problem ; Here , pos : keeps track of current position . f1 : is the flag to check if current number is less than N or not . pr : represents the previous digit ; Base case ; Check if this subproblem has already been solved ; Placing 0 at the current position as it does not violate the condition ; Here flag will be 1 for the next recursive call ; Placing 1 at this position only if the previously inserted number is 0 ; If the number is smaller than N ; If the digit at current position is 1 ; Storing the solution to this subproblem ; Function to find the number of integers less than or equal to N with no consecutive 1 aTMs in binary representation ; Convert N to binary form ; Loop to convert N from Decimal to binary ; Initialising the table with - 1. ; Calling the function ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int memo [ 32 ] [ 2 ] [ 2 ] ; int dp ( int pos , int fl , int pr , string & bin ) { if ( pos == bin . length ( ) ) return 1 ; if ( memo [ pos ] [ fl ] [ pr ] != -1 ) return memo [ pos ] [ fl ] [ pr ] ; int val = 0 ; if ( bin [ pos ] == '0' ) val = val + dp ( pos + 1 , fl , 0 , bin ) ; else if ( bin [ pos ] == '1' ) val = val + dp ( pos + 1 , 1 , 0 , bin ) ; if ( pr == 0 ) { if ( fl == 1 ) { val += dp ( pos + 1 , fl , 1 , bin ) ; } else if ( bin [ pos ] == '1' ) { val += dp ( pos + 1 , fl , 1 , bin ) ; } } return memo [ pos ] [ fl ] [ pr ] = val ; } int findIntegers ( int num ) { string bin ; while ( num > 0 ) { if ( num % 2 ) bin += "1" ; else bin += "0" ; num /= 2 ; } reverse ( bin . begin ( ) , bin . end ( ) ) ; memset ( memo , -1 , sizeof ( memo ) ) ; return dp ( 0 , 0 , 0 , bin ) ; } int main ( ) { int N = 12 ; cout << findIntegers ( N ) ; return 0 ; }
Count ways to reach end from start stone with at most K jumps at each step | C ++ program to find total no . of ways to reach nth step ; Function which returns total no . of ways to reach nth step from sth steps ; Initialize dp array ; filling all the elements with 0 ; Initialize ( s - 1 ) th index to 1 ; Iterate a loop from s to n ; starting range for counting ranges ; Calculate Maximum moves to Reach ith step ; For nth step return dp [ n - 1 ] ; Driver Code ; no of steps ; Atmost steps allowed ; starting range
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int TotalWays ( int n , int s , int k ) { int dp [ n ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ s - 1 ] = 1 ; for ( int i = s ; i < n ; i ++ ) { int idx = max ( s - 1 , i - k ) ; for ( int j = idx ; j < i ; j ++ ) { dp [ i ] += dp [ j ] ; } } return dp [ n - 1 ] ; } int main ( ) { int n = 5 ; int k = 2 ; int s = 2 ; cout << " Total ▁ Ways ▁ = ▁ " << TotalWays ( n , s , k ) ; }
Maximum subsequence sum with adjacent elements having atleast K difference in index | C ++ implementation to find the maximum sum subsequence such that two adjacent element have atleast difference of K in their indices ; Function to find the maximum sum subsequence such that two adjacent element have atleast difference of K in their indices ; DP Array to store the maximum sum obtained till now ; Either select the first element or Nothing ; Either Select the ( i - 1 ) element or let the previous best answer be the current best answer ; Either select the best sum till previous_index or select the current element + best_sum till index - k ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max_sum ( int arr [ ] , int n , int k ) { int dp [ n ] ; dp [ 0 ] = maxi ( 0 , arr [ 0 ] ) ; int i = 1 ; while ( i < k ) { dp [ i ] = maxi ( dp [ i - 1 ] , arr [ i ] ) ; i ++ ; } i = k ; while ( i < n ) { dp [ i ] = maxi ( dp [ i - 1 ] , arr [ i ] + dp [ i - k ] ) ; i ++ ; } return dp [ n - 1 ] ; } int main ( ) { int arr [ ] = { 1 , 2 , -2 , 4 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 4 ; cout << max_sum ( arr , n , k ) ; return 0 ; }
Number of binary strings such that there is no substring of length Γ’ ‰Β₯ 3 | C ++ implementation of the approach ; Function to return the count of all possible binary strings ; Fill 0 's in the dp array ; Base cases ; dp [ i ] [ j ] is the number of possible strings such that '1' just appeared consecutively j times upto ith index ; Taking previously calculated value ; Taking all the possible cases that can appear at the Nth position ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const long MOD = 1000000007 ; long countStr ( long N ) { long dp [ N + 1 ] [ 3 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 1 ] [ 0 ] = 1 ; dp [ 1 ] [ 1 ] = 1 ; dp [ 1 ] [ 2 ] = 0 ; for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] + dp [ i - 1 ] [ 2 ] ) % MOD ; dp [ i ] [ 1 ] = dp [ i - 1 ] [ 0 ] % MOD ; dp [ i ] [ 2 ] = dp [ i - 1 ] [ 1 ] % MOD ; } long ans = ( dp [ N ] [ 0 ] + dp [ N ] [ 1 ] + dp [ N ] [ 2 ] ) % MOD ; return ans ; } int main ( ) { long N = 8 ; cout << countStr ( N ) ; return 0 ; }
Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | C ++ program to find the maximum count of 1 s ; If arr [ i - 2 ] = = 1 then we increment the count of occurences of 1 's ; else we initialise the count with 0 ; If arr [ i + 2 ] = = 1 then we increment the count of occurences of 1 's ; else we initialise the count with 0 ; We get the maximum count by skipping the current and the next element . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxLengthOf1s ( vector < int > arr , int n ) { vector < int > prefix ( n , 0 ) ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i - 2 ] == 1 ) prefix [ i ] = prefix [ i - 1 ] + 1 ; else prefix [ i ] = 0 ; } vector < int > suffix ( n , 0 ) ; for ( int i = n - 3 ; i >= 0 ; i -- ) { if ( arr [ i + 2 ] == 1 ) suffix [ i ] = suffix [ i + 1 ] + 1 ; else suffix [ i ] = 0 ; } int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { ans = max ( ans , prefix [ i + 1 ] + suffix [ i ] ) ; } cout << ans << " STRNEWLINE " ; } int main ( ) { int n = 6 ; vector < int > arr = { 1 , 1 , 1 , 0 , 1 , 1 } ; maxLengthOf1s ( arr , n ) ; return 0 ; }
Count number of ways to get Odd Sum | C ++ implementation ; Count the ways to sum up with odd by choosing one element form each pair ; Initialize two array with 0 ; if element is even ; store count of even number in i 'th pair ; if the element is odd ; store count of odd number in i 'th pair ; Initial state of dp array ; dp [ i ] [ 0 ] = total number of ways to get even sum upto i 'th pair ; dp [ i ] [ 1 ] = total number of ways to odd even sum upto i 'th pair ; dp [ n - 1 ] [ 1 ] = total number of ways to get odd sum upto n 'th pair ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountOfOddSum ( int a [ ] [ 2 ] , int n ) { int dp [ n ] [ 2 ] , cnt [ n ] [ 2 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; memset ( cnt , 0 , sizeof ( cnt ) ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < 2 ; j ++ ) { if ( a [ i ] [ j ] % 2 == 0 ) { cnt [ i ] [ 0 ] ++ ; } else { cnt [ i ] [ 1 ] ++ ; } } } dp [ 0 ] [ 0 ] = cnt [ 0 ] [ 0 ] , dp [ 0 ] [ 1 ] = cnt [ 0 ] [ 1 ] ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] * cnt [ i ] [ 0 ] + dp [ i - 1 ] [ 1 ] * cnt [ i ] [ 1 ] ) ; dp [ i ] [ 1 ] = ( dp [ i - 1 ] [ 0 ] * cnt [ i ] [ 1 ] + dp [ i - 1 ] [ 1 ] * cnt [ i ] [ 0 ] ) ; } return dp [ n - 1 ] [ 1 ] ; } int main ( ) { int a [ ] [ 2 ] = { { 1 , 2 } , { 3 , 6 } } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int ans = CountOfOddSum ( a , n ) ; cout << ans << " STRNEWLINE " ; return 0 ; }
Longest Consecuetive Subsequence when only one insert operation is allowed | C ++ implementation of above approach ; Function to return the length of longest consecuetive subsequence after inserting an element ; Variable to find maximum value of the array ; Calculating maximum value of the array ; Declaring the DP table ; Variable to store the maximum length ; Iterating for every value present in the array ; Recurrence for dp [ val ] [ 0 ] ; No value can be inserted before 1 , hence the element value should be greater than 1 for this recurrance relation ; Recurrence for dp [ val ] [ 1 ] ; Maximum length of consecutive sequence ending at 1 is equal to 1 ; Update the ans variable with the new maximum length possible ; Return the ans ; Driver code ; Input array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestConsSeq ( int arr [ ] , int N ) { int maxval = 1 ; for ( int i = 0 ; i < N ; i += 1 ) { maxval = max ( maxval , arr [ i ] ) ; } int dp [ maxval + 1 ] [ 2 ] = { 0 } ; int ans = 1 ; for ( int i = 0 ; i < N ; i += 1 ) { dp [ arr [ i ] ] [ 0 ] = ( 1 + dp [ arr [ i ] - 1 ] [ 0 ] ) ; if ( arr [ i ] >= 2 ) dp [ arr [ i ] ] [ 1 ] = max ( 1 + dp [ arr [ i ] - 1 ] [ 1 ] , 2 + dp [ arr [ i ] - 2 ] [ 0 ] ) ; else dp [ arr [ i ] ] [ 1 ] = 1 ; ans = max ( ans , dp [ arr [ i ] ] [ 1 ] ) ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 1 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << LongestConsSeq ( arr , N ) ; return 0 ; }
Stepping Numbers | A C ++ program to find all the Stepping Number in [ n , m ] ; This function checks if an integer n is a Stepping Number ; Initalize prevDigit with - 1 ; Iterate through all digits of n and compare difference between value of previous and current digits ; Get Current digit ; Single digit is consider as a Stepping Number ; Check if absolute difference between prev digit and current digit is 1 ; A brute force approach based function to find all stepping numbers . ; Iterate through all the numbers from [ N , M ] and check if its a stepping number . ; Driver program to test above function ; Display Stepping Numbers in the range [ n , m ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isStepNum ( int n ) { int prevDigit = -1 ; while ( n ) { int curDigit = n % 10 ; if ( prevDigit == -1 ) prevDigit = curDigit ; else { if ( abs ( prevDigit - curDigit ) != 1 ) return false ; } prevDigit = curDigit ; n /= 10 ; } return true ; } void displaySteppingNumbers ( int n , int m ) { for ( int i = n ; i <= m ; i ++ ) if ( isStepNum ( i ) ) cout << i << " ▁ " ; } int main ( ) { int n = 0 , m = 21 ; displaySteppingNumbers ( n , m ) ; return 0 ; }
Count numbers in given range such that sum of even digits is greater than sum of odd digits | C ++ code to count number in the range having the sum of even digits greater than the sum of odd digits ; Base Case ; check if condition satisfied or not ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 0 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; if current digit is odd ; if current digit is even ; Function to convert n into its digit vector and uses memo ( ) function to return the required count ; Initialize DP ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define int long long NEW_LINE using namespace std ; vector < int > v ; int dp [ 18 ] [ 180 ] [ 180 ] [ 2 ] ; int memo ( int index , int evenSum , int oddSum , int tight ) { if ( index == v . size ( ) ) { if ( evenSum > oddSum ) return 1 ; else return 0 ; } if ( dp [ index ] [ evenSum ] [ oddSum ] [ tight ] != -1 ) return dp [ index ] [ evenSum ] [ oddSum ] [ tight ] ; int limit = ( tight ) ? v [ index ] : 9 ; int ans = 0 ; for ( int d = 0 ; d <= limit ; d ++ ) { int currTight = 0 ; if ( d == v [ index ] ) currTight = tight ; if ( d % 2 != 0 ) ans += memo ( index + 1 , evenSum , oddSum + d , currTight ) ; else ans += memo ( index + 1 , evenSum + d , oddSum , currTight ) ; } dp [ index ] [ evenSum ] [ oddSum ] [ tight ] = ans ; return ans ; } int CountNum ( int n ) { v . clear ( ) ; while ( n ) { v . push_back ( n % 10 ) ; n = n / 10 ; } reverse ( v . begin ( ) , v . end ( ) ) ; memset ( dp , -1 , sizeof ( dp ) ) ; return memo ( 0 , 0 , 0 , 1 ) ; } int32_t main ( ) { int L , R ; L = 2 ; R = 10 ; cout << CountNum ( R ) - CountNum ( L - 1 ) << " STRNEWLINE " ; return 0 ; }
Maximum sub | C ++ implementation of the approach ; Function to return the maximum sum of the sub - sequence such that two consecutive elements have a difference of at least 3 in their indices in the given array ; If there is a single element in the array ; Either select it or don 't ; If there are two elements ; Either select the first element or don 't ; Either select the first or the second element or don 't select any element ; Either select the first element or don 't ; Either select the first or the second element or don 't select any element ; Either select first , second , third or nothing ; For the rest of the elements ; Either select the best sum till previous_index or select the current element + best_sum till index - 3 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max_sum ( int a [ ] , int n ) { int dp [ n ] ; if ( n == 1 ) { dp [ 0 ] = max ( 0 , a [ 0 ] ) ; } else if ( n == 2 ) { dp [ 0 ] = max ( 0 , a [ 0 ] ) ; dp [ 1 ] = max ( a [ 1 ] , dp [ 0 ] ) ; } else if ( n >= 3 ) { dp [ 0 ] = max ( 0 , a [ 0 ] ) ; dp [ 1 ] = max ( a [ 1 ] , max ( 0 , a [ 0 ] ) ) ; dp [ 2 ] = max ( a [ 2 ] , max ( a [ 1 ] , max ( 0 , a [ 0 ] ) ) ) ; int i = 3 ; while ( i < n ) { dp [ i ] = max ( dp [ i - 1 ] , a [ i ] + dp [ i - 3 ] ) ; i ++ ; } } return dp [ n - 1 ] ; } int main ( ) { int arr [ ] = { 1 , 2 , -2 , 4 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << max_sum ( arr , n ) ; return 0 ; }
Minimum count of elements that sums to a given number | C ++ implementation of the above approach ; we will only store min counts of sum upto 100 ; initialize with INT_MAX ; memo [ 0 ] = 0 as 0 is made from 0 elements ; fill memo array with min counts of elements that will constitute sum upto 100 ; min_count will store min count of elements chosen ; starting from end iterate over each 2 digits and add min count of elements to min_count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCount ( int K ) { int memo [ 100 ] ; for ( int i = 0 ; i < 100 ; i ++ ) { memo [ i ] = INT_MAX ; } memo [ 0 ] = 0 ; for ( int i = 1 ; i < 100 ; i ++ ) { memo [ i ] = min ( memo [ i - 1 ] + 1 , memo [ i ] ) ; } for ( int i = 10 ; i < 100 ; i ++ ) { memo [ i ] = min ( memo [ i - 10 ] + 1 , memo [ i ] ) ; } for ( int i = 25 ; i < 100 ; i ++ ) { memo [ i ] = min ( memo [ i - 25 ] + 1 , memo [ i ] ) ; } long min_count = 0 ; while ( K > 0 ) { min_count += memo [ K % 100 ] ; K /= 100 ; } return min_count ; } int main ( ) { int K = 69 ; cout << minCount ( K ) << endl ; return 0 ; }
Number of sub | C ++ implementation of the approach ; Function to return the number of subsequences which have at least one consecutive pair with difference less than or equal to 1 ; Not required sub - sequences which turn required on adding i ; Required sub - sequence till now will be required sequence plus sub - sequence which turns required ; Similarly for not required ; Also updating total required and not required sub - sequences ; Also , storing values in dp ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 10000 ; int count_required_sequence ( int n , int arr [ ] ) { int total_required_subsequence = 0 ; int total_n_required_subsequence = 0 ; int dp [ N ] [ 2 ] ; for ( int i = 0 ; i < n ; i ++ ) { int turn_required = 0 ; for ( int j = -1 ; j <= 1 ; j ++ ) turn_required += dp [ arr [ i ] + j ] [ 0 ] ; int required_end_i = ( total_required_subsequence + turn_required ) ; int n_required_end_i = ( 1 + total_n_required_subsequence - turn_required ) ; total_required_subsequence += required_end_i ; total_n_required_subsequence += n_required_end_i ; dp [ arr [ i ] ] [ 1 ] += required_end_i ; dp [ arr [ i ] ] [ 0 ] += n_required_end_i ; } return total_required_subsequence ; } int main ( ) { int arr [ ] = { 1 , 6 , 2 , 1 , 9 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << count_required_sequence ( n , arr ) << " STRNEWLINE " ; return 0 ; }
Iterative approach to print all combinations of an Array | C ++ implementation of the approach ; Data array for combination ; Number of elements in the combination ; The boolean array ; Starting index of the 1 st tract of trues ; Ending index of the 1 st tract of trues ; Constructor ; Set the 1 st r Booleans to true , initialize Start and End ; Generate the very first combination ; Update the starting ending indices of trues in the boolean array ; Function that returns true if another combination can still be generated ; Function to generate the next combination ; Only one true in the tract ; Move the End and reset the End ; Set all the values to false starting from index Start and ending at index End in the boolean array ; Set the beginning elements to true ; Reset the End ; Function to print the combination generated previouslt ; If current index is set to true in the boolean array then element at current index in the original array is part of the combination generated previously ; Driver code
#include <iostream> NEW_LINE using namespace std ; class Combination { private : int * Indices ; int N ; int R ; bool * Flags ; int Start ; int End ; public : Combination ( int * arr , int n , int r ) { this -> Indices = arr ; this -> N = n ; this -> R = r ; this -> Flags = nullptr ; } ~ Combination ( ) { if ( this -> Flags != nullptr ) { delete [ ] this -> Flags ; } } void GetFirst ( ) { this -> Flags = new bool [ N ] ; for ( int i = 0 ; i < this -> N ; ++ i ) { if ( i < this -> R ) { Flags [ i ] = true ; } else { Flags [ i ] = false ; } } this -> Start = 0 ; this -> End = this -> R - 1 ; this -> Output ( ) ; } bool HasNext ( ) { return End < ( this -> N - 1 ) ; } void Next ( ) { if ( this -> Start == this -> End ) { this -> Flags [ this -> End ] = false ; this -> Flags [ this -> End + 1 ] = true ; this -> Start += 1 ; this -> End += 1 ; while ( this -> End + 1 < this -> N && this -> Flags [ this -> End + 1 ] ) { ++ this -> End ; } } else { if ( this -> Start == 0 ) { Flags [ this -> End ] = false ; Flags [ this -> End + 1 ] = true ; this -> End -= 1 ; } else { Flags [ this -> End + 1 ] = true ; for ( int i = this -> Start ; i <= this -> End ; ++ i ) { Flags [ i ] = false ; } for ( int i = 0 ; i < this -> End - this -> Start ; ++ i ) { Flags [ i ] = true ; } this -> End = this -> End - this -> Start - 1 ; this -> Start = 0 ; } } this -> Output ( ) ; } private : void Output ( ) { for ( int i = 0 , count = 0 ; i < this -> N && count < this -> R ; ++ i ) { if ( Flags [ i ] ) { cout << Indices [ i ] << " ▁ " ; ++ count ; } } cout << endl ; } } ; int main ( ) { int arr [ ] = { 0 , 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int r = 3 ; Combination com ( arr , n , r ) ; com . GetFirst ( ) ; while ( com . HasNext ( ) ) { com . Next ( ) ; } return 0 ; }
Number of ways to choose elements from the array such that their average is K | C ++ implementation of the above approach ; This dp array is used to store our values so that we don 't have to calculate same values again and again ; Base cases Index can 't be less than 0 ; No element is picked hence average cannot be calculated ; If remainder is non zero , we cannot divide the sum by count i . e . the average will not be an integer ; If we find an average return 1 ; If we have already calculated this function simply return it instead of calculating it again ; If we don 't pick the current element simple recur for index -1 ; If we pick the current element add it to our current sum and increment count by 1 ; Store the value for the current function ; Function to return the number of ways ; Push - 1 at the beginning to make it 1 - based indexing ; Initialize dp array by - 1 ; Call recursive function waysutil to calculate total ways ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_INDEX 51 NEW_LINE #define MAX_SUM 2505 NEW_LINE int dp [ MAX_INDEX ] [ MAX_SUM ] [ MAX_INDEX ] ; int waysutil ( int index , int sum , int count , vector < int > & arr , int K ) { if ( index < 0 ) return 0 ; if ( index == 0 ) { if ( count == 0 ) return 0 ; int remainder = sum % count ; if ( remainder != 0 ) return 0 ; int average = sum / count ; if ( average == K ) return 1 ; } if ( dp [ index ] [ sum ] [ count ] != -1 ) return dp [ index ] [ sum ] [ count ] ; int dontpick = waysutil ( index - 1 , sum , count , arr , K ) ; int pick = waysutil ( index - 1 , sum + arr [ index ] , count + 1 , arr , K ) ; int total = pick + dontpick ; dp [ index ] [ sum ] [ count ] = total ; return total ; } int ways ( int N , int K , int * arr ) { vector < int > Arr ; Arr . push_back ( -1 ) ; for ( int i = 0 ; i < N ; ++ i ) { Arr . push_back ( arr [ i ] ) ; } memset ( dp , -1 , sizeof dp ) ; int answer = waysutil ( N , 0 , 0 , Arr , K ) ; return answer ; } int main ( ) { int arr [ ] = { 3 , 6 , 2 , 8 , 7 , 6 , 5 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 5 ; cout << ways ( N , K , arr ) ; return 0 ; }
Subset with sum closest to zero | Variable to store states of dp ; Variable to store states of dp ; Function to return the number closer to integer s ; To find the sum closest to zero Since sum can be negative , we will add MAX to it to make it positive ; Base cases ; Checks if a state is already solved ; Recurrence relation ; Returning the value ; Function to calculate the closest sum value ; Calculate the Closest value for every subarray arr [ i - 1 : n ] ; Driver function ; Input array
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define arrSize 51 NEW_LINE #define maxSum 201 NEW_LINE #define MAX 100 NEW_LINE #define inf 999999 NEW_LINE int dp [ arrSize ] [ maxSum ] ; bool visit [ arrSize ] [ maxSum ] ; int RetClose ( int a , int b , int s ) { if ( abs ( a - s ) < abs ( b - s ) ) return a ; else return b ; } int MinDiff ( int i , int sum , int arr [ ] , int n ) { if ( i == n ) return 0 ; if ( visit [ i ] [ sum + MAX ] ) return dp [ i ] [ sum + MAX ] ; visit [ i ] [ sum + MAX ] = 1 ; dp [ i ] [ sum + MAX ] = RetClose ( arr [ i ] + MinDiff ( i + 1 , sum + arr [ i ] , arr , n ) , MinDiff ( i + 1 , sum , arr , n ) , -1 * sum ) ; return dp [ i ] [ sum + MAX ] ; } void FindClose ( int arr [ ] , int n ) { int ans = inf ; for ( int i = 1 ; i <= n ; i ++ ) ans = RetClose ( arr [ i - 1 ] + MinDiff ( i , arr [ i - 1 ] , arr , n ) , ans , 0 ) ; cout << ans << endl ; } int main ( ) { int arr [ ] = { 25 , -9 , -10 , -4 , -7 , -33 } ; int n = sizeof ( arr ) / sizeof ( int ) ; FindClose ( arr , n ) ; return 0 ; }
Paths from entry to exit in matrix and maximum path sum | C ++ implementation of the approach ; Recursive function to return the total paths from grid [ i ] [ j ] to grid [ n - 1 ] [ n - 1 ] ; Out of bounds ; If the current state hasn 't been solved before ; Only valid move is right ; Only valid move is down ; Right and down , both are valid moves ; Recursive function to return the maximum sum along the path from grid [ i ] [ j ] to grid [ n - 1 ] [ n - 1 ] ; Out of bounds ; If the current state hasn 't been solved before ; Only valid move is right ; Only valid move is down ; Right and down , both are valid moves ; Driver code ; Fill the dp [ ] [ ] array with - 1 ; When source and destination are same then there is only 1 path ; Print the count of paths from grid [ 0 ] [ 0 ] to grid [ n - 1 ] [ n - 1 ] ; Fill the dp [ ] [ ] array again with - 1 for ( int i = 0 ; i < n ; i ++ ) Arrays . fill ( dp [ i ] , - 1 ) ; ; When source and destination are same then the sum is grid [ n - 1 ] [ n - 1 ] ; Print the maximum sum among all the paths from grid [ 0 ] [ 0 ] to grid [ n - 1 ] [ n - 1 ]
#include <bits/stdc++.h> NEW_LINE #define COL 5 NEW_LINE #define ROW 5 NEW_LINE using namespace std ; int totalPaths ( int i , int j , int n , int grid [ ] [ COL ] , int dp [ ] [ COL ] ) { if ( i < 0 j < 0 i > = n j > = n ) return 0 ; if ( dp [ i ] [ j ] == -1 ) { if ( grid [ i ] [ j ] == 1 ) dp [ i ] [ j ] = totalPaths ( i , j + 1 , n , grid , dp ) ; else if ( grid [ i ] [ j ] == 2 ) dp [ i ] [ j ] = totalPaths ( i + 1 , j , n , grid , dp ) ; else dp [ i ] [ j ] = totalPaths ( i , j + 1 , n , grid , dp ) + totalPaths ( i + 1 , j , n , grid , dp ) ; } return dp [ i ] [ j ] ; } int maxSumPath ( int i , int j , int n , int grid [ ROW ] [ COL ] , int dp [ ROW ] [ COL ] ) { if ( i < 0 j < 0 i > = n j > = n ) return 0 ; if ( dp [ i ] [ j ] == -1 ) { if ( grid [ i ] [ j ] == 1 ) dp [ i ] [ j ] = grid [ i ] [ j ] + maxSumPath ( i , j + 1 , n , grid , dp ) ; else if ( grid [ i ] [ j ] == 2 ) dp [ i ] [ j ] = grid [ i ] [ j ] + maxSumPath ( i + 1 , j , n , grid , dp ) ; else dp [ i ] [ j ] = grid [ i ] [ j ] + max ( maxSumPath ( i , j + 1 , n , grid , dp ) , maxSumPath ( i + 1 , j , n , grid , dp ) ) ; } return dp [ i ] [ j ] ; } int main ( ) { int grid [ ROW ] [ COL ] = { { 1 , 1 , 3 , 2 , 1 } , { 3 , 2 , 2 , 1 , 2 } , { 1 , 3 , 3 , 1 , 3 } , { 1 , 2 , 3 , 1 , 2 } , { 1 , 1 , 1 , 3 , 1 } } ; int n = ROW ; int dp [ ROW ] [ COL ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) dp [ i ] [ j ] = -1 ; } dp [ n - 1 ] [ n - 1 ] = 1 ; cout << " Total ▁ paths : ▁ " << totalPaths ( 0 , 0 , n , grid , dp ) << endl ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) dp [ i ] [ j ] = -1 ; } dp [ n - 1 ] [ n - 1 ] = grid [ n - 1 ] [ n - 1 ] ; cout << " Maximum ▁ sum : ▁ " << maxSumPath ( 0 , 0 , n , grid , dp ) << endl ; return 0 ; }
Queries for bitwise OR in the index range [ L , R ] of the given array | C ++ implementation of the approach ; Array to store bit - wise prefix count ; Function to find the prefix sum ; Loop for each bit ; Loop to find prefix count ; Function to answer query ; To store the answer ; Loop for each bit ; To store the number of variables with ith bit set ; Condition for ith bit of answer to be set ; Driver code
#include <bits/stdc++.h> NEW_LINE #define MAX 100000 NEW_LINE #define bitscount 32 NEW_LINE using namespace std ; int prefix_count [ bitscount ] [ MAX ] ; void findPrefixCount ( int arr [ ] , int n ) { for ( int i = 0 ; i < bitscount ; i ++ ) { prefix_count [ i ] [ 0 ] = ( ( arr [ 0 ] >> i ) & 1 ) ; for ( int j = 1 ; j < n ; j ++ ) { prefix_count [ i ] [ j ] = ( ( arr [ j ] >> i ) & 1 ) ; prefix_count [ i ] [ j ] += prefix_count [ i ] [ j - 1 ] ; } } } int rangeOr ( int l , int r ) { int ans = 0 ; for ( int i = 0 ; i < bitscount ; i ++ ) { int x ; if ( l == 0 ) x = prefix_count [ i ] [ r ] ; else x = prefix_count [ i ] [ r ] - prefix_count [ i ] [ l - 1 ] ; if ( x != 0 ) ans = ( ans | ( 1 << i ) ) ; } return ans ; } int main ( ) { int arr [ ] = { 7 , 5 , 3 , 5 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; findPrefixCount ( arr , n ) ; int queries [ ] [ 2 ] = { { 1 , 3 } , { 4 , 5 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) cout << rangeOr ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) << endl ; return 0 ; }
Distinct palindromic sub | C ++ implementation of the approach ; Function to return the count of distinct palindromic sub - strings of the given string s ; To store the positions of palindromic sub - strings ; Map to store the sub - strings ; Sub - strings of length 1 are palindromes ; Store continuous palindromic sub - strings ; Store palindromes of size 2 ; If str [ i ... ( i + 1 ) ] is not a palindromic then set dp [ i ] [ i + 1 ] = 0 ; Find palindromic sub - strings of length >= 3 ; End of palindromic substring ; If s [ start ] = = s [ end ] and dp [ start + 1 ] [ end - 1 ] is already palindrome then s [ start ... . end ] is also a palindrome ; Set dp [ start ] [ end ] = 1 ; Not a palindrome ; Return the count of distinct palindromes ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int palindromeSubStrs ( string s ) { int dp [ s . size ( ) ] [ s . size ( ) ] ; int st , end , i , j , len ; map < string , bool > m ; for ( i = 0 ; i < s . size ( ) ; i ++ ) { dp [ i ] [ i ] = 1 ; m [ string ( s . begin ( ) + i , s . begin ( ) + i + 1 ) ] = 1 ; } for ( i = 0 ; i < s . size ( ) - 1 ; i ++ ) { if ( s [ i ] == s [ i + 1 ] ) { dp [ i ] [ i + 1 ] = 1 ; m [ string ( s . begin ( ) + i , s . begin ( ) + i + 2 ) ] = 1 ; } else { dp [ i ] [ i + 1 ] = 0 ; } } for ( len = 3 ; len <= s . size ( ) ; len ++ ) { for ( st = 0 ; st <= s . size ( ) - len ; st ++ ) { end = st + len - 1 ; if ( s [ st ] == s [ end ] && dp [ st + 1 ] [ end - 1 ] ) { dp [ st ] [ end ] = 1 ; m [ string ( s . begin ( ) + st , s . begin ( ) + end + 1 ) ] = 1 ; } else dp [ st ] [ end ] = 0 ; } } return m . size ( ) ; } int main ( ) { string s = " abaaa " ; cout << palindromeSubStrs ( s ) ; return 0 ; }
Maximum sum path in a matrix from top to bottom and back | C ++ implementation of the approach ; Input matrix ; DP matrix ; Function to return the sum of the cells arr [ i1 ] [ j1 ] and arr [ i2 ] [ j2 ] ; Recursive function to return the required maximum cost path ; Column number of second path ; Base Case ; If already calculated , return from DP matrix ; Recurring for neighbouring cells of both paths together ; Saving result to the DP matrix for current state ; Driver code ; set initial value
#include <bits/stdc++.h> NEW_LINE using namespace std ; int n = 4 , m = 4 ; int arr [ 4 ] [ 4 ] = { { 1 , 0 , 3 , -1 } , { 3 , 5 , 1 , -2 } , { -2 , 0 , 1 , 1 } , { 2 , 1 , -1 , 1 } } ; int cache [ 5 ] [ 5 ] [ 5 ] ; int sum ( int i1 , int j1 , int i2 , int j2 ) { if ( i1 == i2 && j1 == j2 ) { return arr [ i1 ] [ j1 ] ; } return arr [ i1 ] [ j1 ] + arr [ i2 ] [ j2 ] ; } int maxSumPath ( int i1 , int j1 , int i2 ) { int j2 = i1 + j1 - i2 ; if ( i1 >= n i2 >= n j1 >= m j2 >= m ) { return 0 ; } if ( cache [ i1 ] [ j1 ] [ i2 ] != -1 ) { return cache [ i1 ] [ j1 ] [ i2 ] ; } int ans = INT_MIN ; ans = max ( ans , maxSumPath ( i1 + 1 , j1 , i2 + 1 ) + sum ( i1 , j1 , i2 , j2 ) ) ; ans = max ( ans , maxSumPath ( i1 , j1 + 1 , i2 ) + sum ( i1 , j1 , i2 , j2 ) ) ; ans = max ( ans , maxSumPath ( i1 , j1 + 1 , i2 + 1 ) + sum ( i1 , j1 , i2 , j2 ) ) ; ans = max ( ans , maxSumPath ( i1 + 1 , j1 , i2 ) + sum ( i1 , j1 , i2 , j2 ) ) ; cache [ i1 ] [ j1 ] [ i2 ] = ans ; return ans ; } int main ( ) { memset ( cache , -1 , sizeof ( cache ) ) ; cout << maxSumPath ( 0 , 0 , 0 ) ; return 0 ; }
Bellman Ford Algorithm ( Simple Implementation ) | A C ++ program for Bellman - Ford 's single source shortest path algorithm. ; The main function that finds shortest distances from src to all other vertices using Bellman - Ford algorithm . The function also detects negative weight cycle The row graph [ i ] represents i - th edge with three values u , v and w . ; Initialize distance of all vertices as infinite . ; initialize distance of source as 0 ; Relax all edges | V | - 1 times . A simple shortest path from src to any other vertex can have at - most | V | - 1 edges ; check for negative - weight cycles . The above step guarantees shortest distances if graph doesn 't contain negative weight cycle. If we get a shorter path, then there is a cycle. ; Driver program to test above functions ; Every edge has three values ( u , v , w ) where the edge is from vertex u to v . And weight of the edge is w .
#include <bits/stdc++.h> NEW_LINE using namespace std ; void BellmanFord ( int graph [ ] [ 3 ] , int V , int E , int src ) { int dis [ V ] ; for ( int i = 0 ; i < V ; i ++ ) dis [ i ] = INT_MAX ; dis [ src ] = 0 ; for ( int i = 0 ; i < V - 1 ; i ++ ) { for ( int j = 0 ; j < E ; j ++ ) { if ( dis [ graph [ j ] [ 0 ] ] != INT_MAX && dis [ graph [ j ] [ 0 ] ] + graph [ j ] [ 2 ] < dis [ graph [ j ] [ 1 ] ] ) dis [ graph [ j ] [ 1 ] ] = dis [ graph [ j ] [ 0 ] ] + graph [ j ] [ 2 ] ; } } for ( int i = 0 ; i < E ; i ++ ) { int x = graph [ i ] [ 0 ] ; int y = graph [ i ] [ 1 ] ; int weight = graph [ i ] [ 2 ] ; if ( dis [ x ] != INT_MAX && dis [ x ] + weight < dis [ y ] ) cout << " Graph ▁ contains ▁ negative " " ▁ weight ▁ cycle " << endl ; } cout << " Vertex ▁ Distance ▁ from ▁ Source " << endl ; for ( int i = 0 ; i < V ; i ++ ) cout << i << " TABSYMBOL TABSYMBOL " << dis [ i ] << endl ; } int main ( ) { int graph [ ] [ 3 ] = { { 0 , 1 , -1 } , { 0 , 2 , 4 } , { 1 , 2 , 3 } , { 1 , 3 , 2 } , { 1 , 4 , 2 } , { 3 , 2 , 5 } , { 3 , 1 , 1 } , { 4 , 3 , -3 } } ; BellmanFord ( graph , V , E , 0 ) ; return 0 ; }
Find number of edges that can be broken in a tree such that Bitwise OR of resulting two trees are equal | C ++ implementation of the approach ; Function to perform simple DFS ; Finding the number of times each bit is set in all the values of a subtree rooted at v ; Checking for each bit whether the numbers with that particular bit as set are either zero in both the resulting trees or greater than zero in both the resulting trees ; Driver code ; Number of nodes ; ArrayList to store the tree ; Array to store the value of nodes ; Array to store the number of times each bit is set in all the values in complete tree ; Finding the set bits in the value of node i ; push_back edges
#include <bits/stdc++.h> NEW_LINE using namespace std ; int m [ 1000 ] , x [ 22 ] ; int a [ 1000 ] [ 22 ] ; vector < vector < int > > g ; int ans = 0 ; void dfs ( int u , int p ) { for ( int i = 0 ; i < g [ u ] . size ( ) ; i ++ ) { int v = g [ u ] [ i ] ; if ( v != p ) { dfs ( v , u ) ; for ( int i = 0 ; i < 22 ; i ++ ) a [ u ] [ i ] += a [ v ] [ i ] ; } } int pp = 0 ; for ( int i = 0 ; i < 22 ; i ++ ) { if ( ! ( ( a [ u ] [ i ] > 0 && x [ i ] - a [ u ] [ i ] > 0 ) || ( a [ u ] [ i ] == 0 && x [ i ] == 0 ) ) ) { pp = 1 ; break ; } } if ( pp == 0 ) ans ++ ; } int main ( ) { int n = 4 ; g . resize ( n + 1 ) ; m [ 1 ] = 1 ; m [ 2 ] = 3 ; m [ 3 ] = 2 ; m [ 4 ] = 3 ; for ( int i = 1 ; i <= n ; i ++ ) { int y = m [ i ] ; int k = 0 ; while ( y != 0 ) { int p = y % 2 ; if ( p == 1 ) { x [ k ] ++ ; a [ i ] [ k ] ++ ; } y = y / 2 ; k ++ ; } } g [ 1 ] . push_back ( 2 ) ; g [ 2 ] . push_back ( 1 ) ; g [ 1 ] . push_back ( 3 ) ; g [ 3 ] . push_back ( 1 ) ; g [ 1 ] . push_back ( 4 ) ; g [ 4 ] . push_back ( 1 ) ; dfs ( 1 , 0 ) ; cout << ( ans ) ; }
Find the maximum number of composite summands of a number | C ++ implementation of the above approach ; Function to generate the dp array ; combination of three integers ; take the maximum number of summands ; Function to find the maximum number of summands ; If n is a smaller number , less than 16 return dp [ n ] ; Else , find a minimal number t as explained in solution ; Driver code ; Generate dp array
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int maxn = 16 ; vector < int > precompute ( ) { vector < int > dp ( maxn , -1 ) ; dp [ 0 ] = 0 ; for ( int i = 1 ; i < maxn ; ++ i ) { for ( auto j : vector < int > { 4 , 6 , 9 } ) { if ( i >= j && dp [ i - j ] != -1 ) { dp [ i ] = max ( dp [ i ] , dp [ i - j ] + 1 ) ; } } } return dp ; } int Maximum_Summands ( vector < int > dp , int n ) { if ( n < maxn ) return dp [ n ] ; else { int t = ( n - maxn ) / 4 + 1 ; return t + dp [ n - 4 * t ] ; } } int main ( ) { int n = 12 ; vector < int > dp = precompute ( ) ; cout << Maximum_Summands ( dp , n ) << endl ; return 0 ; }
Minimum cost to reach end of array array when a maximum jump of K index is allowed | C ++ implementation of the approach ; Function for returning the min of two elements ; for calculating the number of elements ; Allocating Memo table and initializing with INT_MAX ; Base case ; For every element relax every reachable element ie relax next k elements ; reaching next k element ; Relaxing the element ; return the last element in the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min ( int a , int b ) { return ( a > b ) ? b : a ; } int minCostJumpsDP ( vector < int > & A , int k ) { int size = A . size ( ) ; vector < int > x ( size , INT_MAX ) ; x [ 0 ] = 0 ; for ( int i = 0 ; i < size ; i ++ ) { for ( int j = i + 1 ; j < i + k + 1 ; j ++ ) { x [ j ] = min ( x [ j ] , x [ i ] + abs ( A [ i ] - A [ j ] ) ) ; } } return x [ size - 1 ] ; } int main ( ) { vector < int > input { 83 , 26 , 37 , 35 , 33 , 35 , 56 } ; cout << minCostJumpsDP ( input , 3 ) ; return 0 ; }
DP on Trees | Set | C ++ program to find diameter of a tree using DFS . ; Function to find the diameter of the tree using Dynamic Programming ; Store the first maximum and secondmax ; Traverse for all children of node ; Call DFS function again ; Find first max ; Secondmaximum ; else if ( dp1 [ * i ] > secondmax ) Find secondmaximum ; Base case for every node ; if ( firstmax != - 1 ) Add ; Find dp [ 2 ] ; Return maximum of both ; Driver Code ; Constructed tree is 1 / \ 2 3 / \ 4 5 ; create undirected edges ; Find diameter by calling function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int diameter = -1 ; int dfs ( int node , int parent , int dp1 [ ] , int dp2 [ ] , list < int > * adj ) { int firstmax = -1 ; int secondmax = -1 ; for ( auto i = adj [ node ] . begin ( ) ; i != adj [ node ] . end ( ) ; ++ i ) { if ( * i == parent ) continue ; dfs ( * i , node , dp1 , dp2 , adj ) ; if ( firstmax == -1 ) { firstmax = dp1 [ * i ] ; } else if ( dp1 [ * i ] >= firstmax ) { secondmax = firstmax ; firstmax = dp1 [ * i ] ; } { secondmax = dp1 [ * i ] ; } } dp1 [ node ] = 1 ; dp1 [ node ] += firstmax ; if ( secondmax != -1 ) dp2 [ node ] = 1 + firstmax + secondmax ; return max ( dp1 [ node ] , dp2 [ node ] ) ; } int main ( ) { int n = 5 ; list < int > * adj = new list < int > [ n + 1 ] ; adj [ 1 ] . push_back ( 2 ) ; adj [ 2 ] . push_back ( 1 ) ; adj [ 1 ] . push_back ( 3 ) ; adj [ 3 ] . push_back ( 1 ) ; adj [ 2 ] . push_back ( 4 ) ; adj [ 4 ] . push_back ( 2 ) ; adj [ 2 ] . push_back ( 5 ) ; adj [ 5 ] . push_back ( 2 ) ; int dp1 [ n + 1 ] , dp2 [ n + 1 ] ; memset ( dp1 , 0 , sizeof dp1 ) ; memset ( dp2 , 0 , sizeof dp2 ) ; cout << " Diameter ▁ of ▁ the ▁ given ▁ tree ▁ is ▁ " << dfs ( 1 , 1 , dp1 , dp2 , adj ) << endl ; return 0 ; }
Find sub | C ++ implementation of the approach ; Function to return the sum of the sub - matrix ; Function that returns true if it is possible to find the sub - matrix with required sum ; 2 - D array to store the sum of all the sub - matrices ; Filling of dp [ ] [ ] array ; Checking for each possible sub - matrix of size k X k ; Sub - matrix with the given sum not found ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE #define N 4 NEW_LINE int getSum ( int r1 , int r2 , int c1 , int c2 , int dp [ N + 1 ] [ N + 1 ] ) { return dp [ r2 ] [ c2 ] - dp [ r2 ] [ c1 ] - dp [ r1 ] [ c2 ] + dp [ r1 ] [ c1 ] ; } bool sumFound ( int K , int S , int grid [ N ] [ N ] ) { int dp [ N + 1 ] [ N + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) dp [ i + 1 ] [ j + 1 ] = dp [ i + 1 ] [ j ] + dp [ i ] [ j + 1 ] - dp [ i ] [ j ] + grid [ i ] [ j ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) { int sum = getSum ( i , i + K , j , j + K , dp ) ; if ( sum == S ) return true ; } return false ; } int main ( ) { int grid [ N ] [ N ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int K = 2 ; int S = 14 ; if ( sumFound ( K , S , grid ) ) cout << " Yes " << endl ; else cout << " No " << endl ; }
Stepping Numbers | A C ++ program to find all the Stepping Number from N = n to m using BFS Approach ; Prints all stepping numbers reachable from num and in range [ n , m ] ; Queue will contain all the stepping Numbers ; Get the front element and pop from the queue ; If the Stepping Number is in the range [ n , m ] then display ; If Stepping Number is 0 or greater than m , no need to explore the neighbors ; Get the last digit of the currently visited Stepping Number ; There can be 2 cases either digit to be appended is lastDigit + 1 or lastDigit - 1 ; If lastDigit is 0 then only possible digit after 0 can be 1 for a Stepping Number ; If lastDigit is 9 then only possible digit after 9 can be 8 for a Stepping Number ; Prints all stepping numbers in range [ n , m ] using BFS . ; For every single digit Number ' i ' find all the Stepping Numbers starting with i ; Driver program to test above function ; Display Stepping Numbers in the range [ n , m ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; void bfs ( int n , int m , int num ) { queue < int > q ; q . push ( num ) ; while ( ! q . empty ( ) ) { int stepNum = q . front ( ) ; q . pop ( ) ; if ( stepNum <= m && stepNum >= n ) cout << stepNum << " ▁ " ; if ( num == 0 stepNum > m ) continue ; int lastDigit = stepNum % 10 ; int stepNumA = stepNum * 10 + ( lastDigit - 1 ) ; int stepNumB = stepNum * 10 + ( lastDigit + 1 ) ; if ( lastDigit == 0 ) q . push ( stepNumB ) ; else if ( lastDigit == 9 ) q . push ( stepNumA ) ; else { q . push ( stepNumA ) ; q . push ( stepNumB ) ; } } } void displaySteppingNumbers ( int n , int m ) { for ( int i = 0 ; i <= 9 ; i ++ ) bfs ( n , m , i ) ; } int main ( ) { int n = 0 , m = 21 ; displaySteppingNumbers ( n , m ) ; return 0 ; }
Minimum distance to the end of a grid from source | C ++ implementation of the approach ; Global variables for grid , minDistance and visited array ; Queue for BFS ; Function to find whether the move is valid or not ; Function to return the minimum distance from source to the end of the grid ; If source is one of the destinations ; Set minimum value ; Precalculate minDistance of each grid with R * C ; Insert source position in queue ; Update minimum distance to visit source ; Set source to visited ; BFS approach for calculating the minDistance of each cell from source ; Iterate over all four cells adjacent to current cell ; Initialize position of current cell ; Cell below the current cell ; Push new cell to the queue ; Update one of its neightbor 's distance ; Above the current cell ; Right cell ; Left cell ; Pop the visited cell ; Minimum distance in the first row ; Minimum distance in the last row ; Minimum distance in the first column ; Minimum distance in the last column ; If no path exists ; Return the minimum distance ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define row 5 NEW_LINE #define col 5 NEW_LINE int minDistance [ row + 1 ] [ col + 1 ] , visited [ row + 1 ] [ col + 1 ] ; queue < pair < int , int > > que ; bool isValid ( int grid [ ] [ col ] , int i , int j ) { if ( i < 0 j < 0 j > = col i > = row grid [ i ] [ j ] visited [ i ] [ j ] ) return false ; return true ; } int findMinPathminDistance ( int grid [ ] [ col ] , int sourceRow , int sourceCol ) { if ( sourceCol == 0 sourceCol == col - 1 sourceRow == 0 sourceRow == row - 1 ) return 0 ; int minFromSource = row * col ; for ( int i = 0 ; i < row ; i ++ ) for ( int j = 0 ; j < col ; j ++ ) minDistance [ i ] [ j ] = row * col ; que . push ( make_pair ( sourceRow , sourceCol ) ) ; minDistance [ sourceRow ] [ sourceCol ] = 0 ; visited [ sourceRow ] [ sourceCol ] = 1 ; while ( ! que . empty ( ) ) { pair < int , int > cell = que . front ( ) ; int cellRow = cell . first ; int cellCol = cell . second ; if ( isValid ( grid , cellRow + 1 , cellCol ) ) { que . push ( make_pair ( cellRow + 1 , cellCol ) ) ; minDistance [ cellRow + 1 ] [ cellCol ] = min ( minDistance [ cellRow + 1 ] [ cellCol ] , minDistance [ cellRow ] [ cellCol ] + 1 ) ; visited [ cellRow + 1 ] [ cellCol ] = 1 ; } if ( isValid ( grid , cellRow - 1 , cellCol ) ) { que . push ( make_pair ( cellRow - 1 , cellCol ) ) ; minDistance [ cellRow - 1 ] [ cellCol ] = min ( minDistance [ cellRow - 1 ] [ cellCol ] , minDistance [ cellRow ] [ cellCol ] + 1 ) ; visited [ cellRow - 1 ] [ cellCol ] = 1 ; } if ( isValid ( grid , cellRow , cellCol + 1 ) ) { que . push ( make_pair ( cellRow , cellCol + 1 ) ) ; minDistance [ cellRow ] [ cellCol + 1 ] = min ( minDistance [ cellRow ] [ cellCol + 1 ] , minDistance [ cellRow ] [ cellCol ] + 1 ) ; visited [ cellRow ] [ cellCol + 1 ] = 1 ; } if ( isValid ( grid , cellRow , cellCol - 1 ) ) { que . push ( make_pair ( cellRow , cellCol - 1 ) ) ; minDistance [ cellRow ] [ cellCol - 1 ] = min ( minDistance [ cellRow ] [ cellCol - 1 ] , minDistance [ cellRow ] [ cellCol ] + 1 ) ; visited [ cellRow ] [ cellCol - 1 ] = 1 ; } que . pop ( ) ; } int i ; for ( i = 0 ; i < col ; i ++ ) minFromSource = min ( minFromSource , minDistance [ 0 ] [ i ] ) ; for ( i = 0 ; i < col ; i ++ ) minFromSource = min ( minFromSource , minDistance [ row - 1 ] [ i ] ) ; for ( i = 0 ; i < row ; i ++ ) minFromSource = min ( minFromSource , minDistance [ i ] [ 0 ] ) ; for ( i = 0 ; i < row ; i ++ ) minFromSource = min ( minFromSource , minDistance [ i ] [ col - 1 ] ) ; if ( minFromSource == row * col ) return -1 ; return minFromSource ; } int main ( ) { int sourceRow = 3 , sourceCol = 3 ; int grid [ row ] [ col ] = { 1 , 1 , 1 , 1 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 1 , 0 , 1 , 1 , 0 , 0 , 0 , 1 , 1 , 1 , 0 , 1 , 0 } ; cout << findMinPathminDistance ( grid , sourceRow , sourceCol ) ; return 0 ; }
Minimum number of operations required to sum to binary string S | CPP program to find the minimum number of operations required to sum to N ; Function to return the minimum operations required to sum to a number reprented by the binary string S ; Reverse the string to consider it from LSB to MSB ; initialise the dp table ; If S [ 0 ] = '0' , there is no need to perform any operation ; If S [ 0 ] = '1' , just perform a single operation ( i . e Add 2 ^ 0 ) ; Irrespective of the LSB , dp [ 0 ] [ 1 ] is always 1 as there is always the need of making the suffix of the binary string of the form "11 . . . . 1" as suggested by the definition of dp [ i ] [ 1 ] ; Transition from dp [ i - 1 ] [ 0 ] ; 1. Transition from dp [ i - 1 ] [ 1 ] by just doing 1 extra operation of subtracting 2 ^ i 2. Transition from dp [ i - 1 ] [ 0 ] by just doing 1 extra operation of subtracting 2 ^ ( i + 1 ) ; Transition from dp [ i - 1 ] [ 1 ] ; 1. Transition from dp [ i - 1 ] [ 1 ] by just doing 1 extra operation of adding 2 ^ ( i + 1 ) 2. Transition from dp [ i - 1 ] [ 0 ] by just doing 1 extra operation of adding 2 ^ i ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinOperations ( string S ) { reverse ( S . begin ( ) , S . end ( ) ) ; int n = S . length ( ) ; int dp [ n + 1 ] [ 2 ] ; if ( S [ 0 ] == '0' ) { dp [ 0 ] [ 0 ] = 0 ; } else { dp [ 0 ] [ 0 ] = 1 ; } dp [ 0 ] [ 1 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( S [ i ] == '0' ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] ; dp [ i ] [ 1 ] = 1 + min ( dp [ i - 1 ] [ 1 ] , dp [ i - 1 ] [ 0 ] ) ; } else { dp [ i ] [ 1 ] = dp [ i - 1 ] [ 1 ] ; dp [ i ] [ 0 ] = 1 + min ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) ; } } return dp [ n - 1 ] [ 0 ] ; } int main ( ) { string S = "100" ; cout << findMinOperations ( S ) << endl ; S = "111" ; cout << findMinOperations ( S ) << endl ; return 0 ; }
K | C ++ implementation of above approach ; Function that finds the Nth element of K - Fibonacci series ; If N is less than K then the element is '1' ; first k elements are 1 ; ( K + 1 ) th element is K ; find the elements of the K - Fibonacci series ; subtract the element at index i - k - 1 and add the element at index i - i from the sum ( sum contains the sum of previous ' K ' elements ) ; set the new sum ; Driver code ; get the Nth value of K - Fibonacci series
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int N , int K ) { vector < long long int > Array ( N + 1 , 0 ) ; if ( N <= K ) { cout << "1" << endl ; return ; } long long int i = 0 , sum = K ; for ( i = 1 ; i <= K ; ++ i ) { Array [ i ] = 1 ; } Array [ i ] = sum ; for ( int i = K + 2 ; i <= N ; ++ i ) { Array [ i ] = sum - Array [ i - K - 1 ] + Array [ i - 1 ] ; sum = Array [ i ] ; } cout << Array [ N ] << endl ; } int main ( ) { long long int N = 4 , K = 2 ; solve ( N , K ) ; return 0 ; }
Minimum sum possible of any bracket sequence of length N | C ++ program to find the Minimum sum possible of any bracket sequence of length N using the given values for brackets ; DP array ; Recursive function to check for correct bracket expression ; / Not a proper bracket expression ; If reaches at end ; / If proper bracket expression ; else if not , return max ; If already visited ; To find out minimum sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_VAL 10000000 NEW_LINE int dp [ 100 ] [ 100 ] ; int find ( int index , int openbrk , int n , int adj [ ] [ 2 ] ) { if ( openbrk < 0 ) return MAX_VAL ; if ( index == n ) { if ( openbrk == 0 ) { return 0 ; } return MAX_VAL ; } if ( dp [ index ] [ openbrk ] != -1 ) return dp [ index ] [ openbrk ] ; dp [ index ] [ openbrk ] = min ( adj [ index ] [ 1 ] + find ( index + 1 , openbrk + 1 , n , adj ) , adj [ index ] [ 0 ] + find ( index + 1 , openbrk - 1 , n , adj ) ) ; return dp [ index ] [ openbrk ] ; } int main ( ) { int n = 4 ; int adj [ n ] [ 2 ] = { { 5000 , 3000 } , { 6000 , 2000 } , { 8000 , 1000 } , { 9000 , 6000 } } ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << find ( 1 , 1 , n , adj ) + adj [ 0 ] [ 1 ] << endl ; return 0 ; }
Understanding The Coin Change Problem With Dynamic Programming | We have input values of N and an array Coins that holds all of the coins . We use data type of long because we want to be able to test large values without integer overflow ; Create the ways array to 1 plus the amount to stop overflow ; Set the first way to 1 because its 0 and there is 1 way to make 0 with 0 coins ; Go through all of the coins ; Make a comparison to each index value of ways with the coin value . ; Update the ways array ; Return the value at the Nth position of the ways array . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long getNumberOfWays ( long N , vector < long > Coins ) { vector < long > ways ( N + 1 ) ; ways [ 0 ] = 1 ; for ( int i = 0 ; i < Coins . size ( ) ; i ++ ) { for ( int j = 0 ; j < ways . size ( ) ; j ++ ) { if ( Coins [ i ] <= j ) { ways [ j ] += ways [ ( j - Coins [ i ] ) ] ; } } } return ways [ N ] ; } void printArray ( vector < long > coins ) { for ( long i : coins ) cout << i << " STRNEWLINE " ; } int main ( ) { vector < long > Coins = { 1 , 5 , 10 } ; cout << " The ▁ Coins ▁ Array : " << endl ; printArray ( Coins ) ; cout << " Solution : " << endl ; cout << getNumberOfWays ( 12 , Coins ) << endl ; }
Minimum cost to buy N kilograms of sweet for M persons | C ++ program to minimum cost to buy N kilograms of sweet for M persons ; Function to find the minimum cost of sweets ; Defining the sweet array ; DP array to store the values ; Since index starts from 1 we reassign the array into sweet ; Assigning base cases for dp array ; At 0 it is free ; Package not available for desirable amount of sweets ; Buying the ' k ' kg package and assigning it to dp array ; If no solution , select from previous k - 1 packages ; If solution does not exist ; Print the solution ; Driver Function ; Calling the desired function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( int m , int n , int adj [ ] ) { int sweet [ n + 1 ] ; int dp [ n + 1 ] [ n + 1 ] [ n + 1 ] ; sweet [ 0 ] = 0 ; for ( int i = 1 ; i <= m ; ++ i ) sweet [ i ] = adj [ i - 1 ] ; for ( int i = 0 ; i <= m ; ++ i ) { for ( int k = 0 ; k <= n ; ++ k ) dp [ i ] [ 0 ] [ k ] = 0 ; for ( int k = 1 ; k <= n ; ++ k ) dp [ i ] [ k ] [ 0 ] = -1 ; } for ( int i = 0 ; i <= m ; ++ i ) { for ( int j = 1 ; j <= n ; ++ j ) { for ( int k = 1 ; k <= n ; ++ k ) { dp [ i ] [ j ] [ k ] = -1 ; if ( i > 0 && j >= k && sweet [ k ] > 0 && dp [ i - 1 ] [ j - k ] [ k ] != -1 ) dp [ i ] [ j ] [ k ] = dp [ i - 1 ] [ j - k ] [ k ] + sweet [ k ] ; if ( dp [ i ] [ j ] [ k ] == -1 || ( dp [ i ] [ j ] [ k - 1 ] != -1 && dp [ i ] [ j ] [ k ] > dp [ i ] [ j ] [ k - 1 ] ) ) dp [ i ] [ j ] [ k ] = dp [ i ] [ j ] [ k - 1 ] ; } } } if ( dp [ m ] [ n ] [ n ] == -1 ) return 0 ; else return dp [ m ] [ n ] [ n ] ; } int main ( ) { int m = 3 ; int adj [ ] = { 2 , 1 , 3 , 0 , 4 , 10 } ; int n = sizeof ( adj ) / sizeof ( adj [ 0 ] ) ; cout << find ( m , n , adj ) ; return 0 ; }
Maximum length of segments of 0 ' s ▁ and ▁ 1' s | C ++ implementation of above approach ; Recursive Function to find total length of the array Where 1 is greater than zero ; If reaches till end ; If dp is saved ; Finding for each length ; If the character scanned is 1 ; If one is greater than zero , add total length scanned till now ; Continue with next length ; Return the value for start index ; Driver Code ; Size of string ; Calling the function to find the value of function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( int start , string adj , int n , int dp [ ] ) { if ( start == n ) return 0 ; if ( dp [ start ] != -1 ) return dp [ start ] ; dp [ start ] = 0 ; int one = 0 , zero = 0 , k ; for ( k = start ; k < n ; k ++ ) { if ( adj [ k ] == '1' ) one ++ ; else zero ++ ; if ( one > zero ) dp [ start ] = max ( dp [ start ] , find ( k + 1 , adj , n , dp ) + k - start + 1 ) ; else dp [ start ] = max ( dp [ start ] , find ( k + 1 , adj , n , dp ) ) ; } return dp [ start ] ; } int main ( ) { string adj = "100110001010001" ; int n = adj . size ( ) ; int dp [ n + 1 ] ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << find ( 0 , adj , n , dp ) << endl ; return 0 ; }
Length of longest common subsequence containing vowels | C ++ implementation to find the length of longest common subsequence which contains all vowel characters ; function to check whether ' ch ' is a vowel or not ; function to find the length of longest common subsequence which contains all vowel characters ; 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 ] which contains all vowel characters ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char ch ) { if ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) return true ; return false ; } int lcs ( char * X , char * Y , int m , int n ) { int L [ m + 1 ] [ n + 1 ] ; int i , j ; for ( i = 0 ; i <= m ; i ++ ) { for ( j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( ( X [ i - 1 ] == Y [ j - 1 ] ) && isVowel ( X [ i - 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 ( ) { char X [ ] = " aieef " ; char Y [ ] = " klaief " ; int m = strlen ( X ) ; int n = strlen ( Y ) ; cout << " Length ▁ of ▁ LCS ▁ = ▁ " << lcs ( X , Y , m , n ) ; return 0 ; }
Minimum number of single digit primes required whose sum is equal to N | CPP program to find the minimum number of single digit prime numbers required which when summed equals to a given number N . ; function to check if i - th index is valid or not ; function to find the minimum number of single digit prime numbers required which when summed up equals to a given number N . ; Not possible ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int i , int val ) { if ( i - val < 0 ) return false ; return true ; } int MinimumPrimes ( int n ) { int dp [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) dp [ i ] = 1e9 ; dp [ 0 ] = dp [ 2 ] = dp [ 3 ] = dp [ 5 ] = dp [ 7 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( check ( i , 2 ) ) dp [ i ] = min ( dp [ i ] , 1 + dp [ i - 2 ] ) ; if ( check ( i , 3 ) ) dp [ i ] = min ( dp [ i ] , 1 + dp [ i - 3 ] ) ; if ( check ( i , 5 ) ) dp [ i ] = min ( dp [ i ] , 1 + dp [ i - 5 ] ) ; if ( check ( i , 7 ) ) dp [ i ] = min ( dp [ i ] , 1 + dp [ i - 7 ] ) ; } if ( dp [ n ] == ( 1e9 ) ) return -1 ; else return dp [ n ] ; } int main ( ) { int n = 12 ; int minimal = MinimumPrimes ( n ) ; if ( minimal != -1 ) cout << " Minimum ▁ number ▁ of ▁ single " << " ▁ digit ▁ primes ▁ required ▁ : ▁ " << minimal << endl ; else cout << " Not ▁ possible " ; return 0 ; }
Find all distinct subset ( or subsequence ) sums of an array | Set | C ++ program to find total sum of all distinct subset sums in O ( sum ) space . ; Function to print all th distinct sum ; Declare a boolean array of size equal to total sum of the array ; Fill the first row beforehand ; dp [ j ] will be true only if sum j can be formed by any possible addition of numbers in given array upto index i , otherwise false ; Iterate from maxSum to 1 and avoid lookup on any other row ; Do not change the dp array for j less than arr [ i ] ; If dp [ j ] is true then print ; Function to find the total sum and print the distinct sum ; find the sum of array elements ; Function to print all the distinct sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void subsetSum ( int arr [ ] , int n , int maxSum ) { bool dp [ maxSum + 1 ] ; memset ( dp , false , sizeof dp ) ; dp [ arr [ 0 ] ] = true ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = maxSum + 1 ; j >= 1 ; j -- ) { if ( arr [ i ] <= j ) { if ( arr [ i ] == j || dp [ j ] || dp [ ( j - arr [ i ] ) ] ) dp [ j ] = true ; else dp [ j ] = false ; } } } cout << 0 << " ▁ " ; for ( int j = 0 ; j <= maxSum + 1 ; j ++ ) { if ( dp [ j ] == true ) cout << j << " ▁ " ; } } void printDistinct ( int a [ ] , int n ) { int maxSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { maxSum += a [ i ] ; } subsetSum ( a , n , maxSum ) ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printDistinct ( arr , n ) ; return 0 ; }
Sudo Placement [ 1.5 ] | Wolfish | C ++ program for SP - Wolfish ; Function to find the maxCost of path from ( n - 1 , n - 1 ) to ( 0 , 0 ) | recursive approach ; base condition ; reaches the point ; i + j ; check if it is a power of 2 , then only move diagonally ; if not a power of 2 then move side - wise ; Function to return the maximum cost ; calling dp function to get the answer ; Driver Code ; Function calling to get the answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int size = 1000 ; int maxCost ( int a [ ] [ size ] , int m , int n ) { if ( n < 0 m < 0 ) return -1e9 ; else if ( m == 0 && n == 0 ) return 0 ; else { int num = m + n ; if ( ( num & ( num - 1 ) ) == 0 ) return a [ m ] [ n ] + maxCost ( a , m - 1 , n - 1 ) ; else return a [ m ] [ n ] + max ( maxCost ( a , m - 1 , n ) , maxCost ( a , m , n - 1 ) ) ; } } int answer ( int a [ ] [ size ] , int n ) { return maxCost ( a , n - 1 , n - 1 ) ; } int main ( ) { int a [ ] [ size ] = { { 1 , 2 , 3 , 1 } , { 4 , 5 , 6 , 1 } , { 7 , 8 , 9 , 1 } , { 1 , 1 , 1 , 1 } } ; int n = 4 ; cout << answer ( a , n ) ; return 0 ; }
Longest Common Subsequence | DP using Memoization | C ++ program to memoize recursive implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] memoization applied in recursive solution ; base case ; if the same state has already been computed ; if equal , then we store the value of the function call ; store it in arr to avoid further repetitive work in future function calls ; store it in arr to avoid further repetitive work in future function calls ; Driver Code ; assign - 1 to all positions
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int maximum = 1000 ; int lcs ( string X , string Y , int m , int n , int dp [ ] [ maximum ] ) { if ( m == 0 n == 0 ) return 0 ; if ( dp [ m - 1 ] [ n - 1 ] != -1 ) return dp [ m - 1 ] [ n - 1 ] ; if ( X [ m - 1 ] == Y [ n - 1 ] ) { dp [ m - 1 ] [ n - 1 ] = 1 + lcs ( X , Y , m - 1 , n - 1 , dp ) ; return dp [ m - 1 ] [ n - 1 ] ; } else { dp [ m - 1 ] [ n - 1 ] = max ( lcs ( X , Y , m , n - 1 , dp ) , lcs ( X , Y , m - 1 , n , dp ) ) ; return dp [ m - 1 ] [ n - 1 ] ; } } int main ( ) { string X = " AGGTAB " ; string Y = " GXTXAYB " ; int m = X . length ( ) ; int n = Y . length ( ) ; int dp [ m ] [ maximum ] ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << " Length ▁ of ▁ LCS : ▁ " << lcs ( X , Y , m , n , dp ) ; return 0 ; }
Stepping Numbers | A C ++ program to find all the Stepping Numbers in range [ n , m ] using DFS Approach ; Prints all stepping numbers reachable from num and in range [ n , m ] ; If Stepping Number is in the range [ n , m ] then display ; If Stepping Number is 0 or greater than m , then return ; Get the last digit of the currently visited Stepping Number ; There can be 2 cases either digit to be appended is lastDigit + 1 or lastDigit - 1 ; If lastDigit is 0 then only possible digit after 0 can be 1 for a Stepping Number ; If lastDigit is 9 then only possible digit after 9 can be 8 for a Stepping Number ; Method displays all the stepping numbers in range [ n , m ] ; For every single digit Number ' i ' find all the Stepping Numbers starting with i ; Driver program to test above function ; Display Stepping Numbers in the range [ n , m ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( int n , int m , int stepNum ) { if ( stepNum <= m && stepNum >= n ) cout << stepNum << " ▁ " ; if ( stepNum == 0 stepNum > m ) return ; int lastDigit = stepNum % 10 ; int stepNumA = stepNum * 10 + ( lastDigit - 1 ) ; int stepNumB = stepNum * 10 + ( lastDigit + 1 ) ; if ( lastDigit == 0 ) dfs ( n , m , stepNumB ) ; else if ( lastDigit == 9 ) dfs ( n , m , stepNumA ) ; else { dfs ( n , m , stepNumA ) ; dfs ( n , m , stepNumB ) ; } } void displaySteppingNumbers ( int n , int m ) { for ( int i = 0 ; i <= 9 ; i ++ ) dfs ( n , m , i ) ; } int main ( ) { int n = 0 , m = 21 ; displaySteppingNumbers ( n , m ) ; return 0 ; }
Memoization ( 1D , 2D and 3D ) | C ++ program to memoize recursive implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] memoization applied in recursive solution ; base case ; if the same state has already been computed ; if equal , then we store the value of the function call ; store it in arr to avoid further repetitive work in future function calls ; store it in arr to avoid further repetitive work in future function calls ; Utility function to get max of 2 integers ; Driver Code
#include <bits/stdc++.h> NEW_LINE int arr [ 1000 ] [ 1000 ] ; int max ( int a , int b ) ; int lcs ( char * X , char * Y , int m , int n ) { if ( m == 0 n == 0 ) return 0 ; if ( arr [ m - 1 ] [ n - 1 ] != -1 ) return arr [ m - 1 ] [ n - 1 ] ; if ( X [ m - 1 ] == Y [ n - 1 ] ) { arr [ m - 1 ] [ n - 1 ] = 1 + lcs ( X , Y , m - 1 , n - 1 ) ; return arr [ m - 1 ] [ n - 1 ] ; } else { arr [ m - 1 ] [ n - 1 ] = max ( lcs ( X , Y , m , n - 1 ) , lcs ( X , Y , m - 1 , n ) ) ; return arr [ m - 1 ] [ n - 1 ] ; } } int max ( int a , int b ) { return ( a > b ) ? a : b ; } int main ( ) { memset ( arr , -1 , sizeof ( arr ) ) ; char X [ ] = " AGGTAB " ; char Y [ ] = " GXTXAYB " ; int m = strlen ( X ) ; int n = strlen ( Y ) ; printf ( " Length ▁ of ▁ LCS ▁ is ▁ % d " , lcs ( X , Y , m , n ) ) ; return 0 ; }
Number of Unique BST with a given key | Dynamic Programming | C ++ code to find number of unique BSTs Dynamic Programming solution ; Function to find number of unique BST ; DP to store the number of unique BST with key i ; Base case ; fill the dp table in top - down approach . ; n - i in right * i - 1 in left ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfBST ( int n ) { int dp [ n + 1 ] ; fill_n ( dp , n + 1 , 0 ) ; dp [ 0 ] = 1 ; dp [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= i ; j ++ ) { dp [ i ] = dp [ i ] + ( dp [ i - j ] * dp [ j - 1 ] ) ; } } return dp [ n ] ; } int main ( ) { int n = 3 ; cout << " Number ▁ of ▁ structurally ▁ Unique ▁ BST ▁ with ▁ " << n << " ▁ keys ▁ are ▁ : ▁ " << numberOfBST ( n ) << " STRNEWLINE " ; return 0 ; }
Minimum splits in a binary string such that every substring is a power of 4 or 6. | CPP program for Minimum splits in a string such that substring is a power of 4 or 6. ; Function to find if given number is power of another number or not . ; Divide given number repeatedly by base value . ; return false ; not a power ; Function to find minimum number of partitions of given binary string so that each partition is power of 4 or 6. ; Variable to store integer value of given binary string partition . ; DP table to store results of partitioning done at differentindices . ; If the last digit is 1 , hence 4 ^ 0 = 1 and 6 ^ 0 = 1 ; Fix starting position for partition ; Binary representation with leading zeroes is not allowed . ; Iterate for all different partitions starting from i ; Find integer value of current binary partition . ; Check if the value is a power of 4 or 6 or not apply recurrence relation ; If no partitions are possible , then make dp [ i ] = - 1 to represent this . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOf ( long val , int base ) { while ( val > 1 ) { if ( val % base != 0 ) val /= base ; } return true ; } int numberOfPartitions ( string binaryNo ) { int i , j , n = binaryNo . length ( ) ; long val ; int dp [ n ] ; dp [ n - 1 ] = ( ( binaryNo [ n - 1 ] - '0' ) == 0 ) ? -1 : 1 ; for ( i = n - 2 ; i >= 0 ; i -- ) { val = 0 ; if ( ( binaryNo [ i ] - '0' ) == 0 ) { dp [ i ] = -1 ; continue ; } dp [ i ] = INT_MAX ; for ( j = i ; j < n ; j ++ ) { val = ( val * 2 ) + ( long ) ( binaryNo [ j ] - '0' ) ; if ( isPowerOf ( val , 4 ) || isPowerOf ( val , 6 ) ) { if ( j == n - 1 ) { dp [ i ] = 1 ; } else { if ( dp [ j + 1 ] != -1 ) dp [ i ] = min ( dp [ i ] , dp [ j + 1 ] + 1 ) ; } } } if ( dp [ i ] == INT_MAX ) dp [ i ] = -1 ; } return dp [ 0 ] ; } int main ( ) { string binaryNo = "100110110" ; cout << numberOfPartitions ( binaryNo ) ; return 0 ; }
Sum of product of r and rth Binomial Coefficient ( r * nCr ) | CPP Program to find sum of product of r and rth Binomial Coefficient i . e summation r * nCr ; Return summation of r * nCr ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE int summation ( int n ) { return n << ( n - 1 ) ; } int main ( ) { int n = 2 ; cout << summation ( n ) << endl ; return 0 ; }
Integers from the range that are composed of a single distinct digit | C ++ implementation of the approach ; Function to return the count of digits of a number ; Function to return a number that contains only digit ' d ' repeated exactly count times ; Function to return the count of integers that are composed of a single distinct digit only ; Count of digits in L and R ; First digits of L and R ; If L has lesser number of digits than R ; If the number that starts with firstDigitL and has number of digits = countDigitsL is within the range include the number ; Exclude the number ; If the number that starts with firstDigitR and has number of digits = countDigitsR is within the range include the number ; Exclude the number ; If both L and R have equal number of digits ; Include the number greater than L upto the maximum number whose digit = coutDigitsL ; Exclude the numbers which are greater than R ; Return the count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigits ( int n ) { int count = 0 ; while ( n > 0 ) { count += 1 ; n /= 10 ; } return count ; } int getDistinct ( int d , int count ) { int num = 0 ; count = pow ( 10 , count - 1 ) ; while ( count > 0 ) { num += ( count * d ) ; count /= 10 ; } return num ; } int findCount ( int L , int R ) { int count = 0 ; int countDigitsL = countDigits ( L ) ; int countDigitsR = countDigits ( R ) ; int firstDigitL = ( L / pow ( 10 , countDigitsL - 1 ) ) ; int firstDigitR = ( R / pow ( 10 , countDigitsR - 1 ) ) ; if ( countDigitsL < countDigitsR ) { count += ( 9 * ( countDigitsR - countDigitsL - 1 ) ) ; if ( getDistinct ( firstDigitL , countDigitsL ) >= L ) count += ( 9 - firstDigitL + 1 ) ; else count += ( 9 - firstDigitL ) ; if ( getDistinct ( firstDigitR , countDigitsR ) <= R ) count += firstDigitR ; else count += ( firstDigitR - 1 ) ; } else { if ( getDistinct ( firstDigitL , countDigitsL ) >= L ) count += ( 9 - firstDigitL + 1 ) ; else count += ( 9 - firstDigitL ) ; if ( getDistinct ( firstDigitR , countDigitsR ) <= R ) count -= ( 9 - firstDigitR ) ; else count -= ( 9 - firstDigitR + 1 ) ; } return count ; } int main ( ) { int L = 10 , R = 50 ; cout << findCount ( L , R ) ; return 0 ; }
Maximum average sum partition of an array | CPP program for maximum average sum partition ; bottom up approach to calculate score ; storing averages from starting to each i ; ; Driver code ; atmost partitioning size
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE double memo [ MAX ] [ MAX ] ; double score ( int n , vector < int > & A , int k ) { if ( memo [ n ] [ k ] > 0 ) return memo [ n ] [ k ] ; double sum = 0 ; for ( int i = n - 1 ; i > 0 ; i -- ) { sum += A [ i ] ; memo [ n ] [ k ] = max ( memo [ n ] [ k ] , score ( i , A , k - 1 ) + sum / ( n - i ) ) ; } return memo [ n ] [ k ] ; } double largestSumOfAverages ( vector < int > & A , int K ) { int n = A . size ( ) ; double sum = 0 ; memset ( memo , 0.0 , sizeof ( memo ) ) ; for ( int i = 0 ; i < n ; i ++ ) { sum += A [ i ] ; memo [ i + 1 ] [ 1 ] = sum / ( i + 1 ) ; } return score ( n , A , K ) ; } int main ( ) { vector < int > A = { 9 , 1 , 2 , 3 , 9 } ; int K = 3 ; cout << largestSumOfAverages ( A , K ) << endl ; return 0 ; }
Maximum Product Subarray | Added negative product case | C ++ program to find maximum subarray product . ; Function to find maximum subarray product . ; As maximum product can be negative , so initialize ans with minimum integer value . ; Variable to store maximum product until current value . ; Variable to store minimum product until current value . ; Variable used during updation of maximum product and minimum product . ; If current element is positive , update maxval . Update minval if it is negative . ; If current element is zero , maximum product cannot end at current element . Update minval with 1 and maxval with 0. maxval is updated to 0 as in case all other elements are negative , then maxval is 0. ; If current element is negative , then new value of maxval is previous minval * arr [ i ] and new value of minval is previous maxval * arr [ i ] . Before updating maxval , store its previous value in prevMax to be used to update minval . ; Update ans if necessary . ; If maxval is zero , then to calculate product for next iteration , it should be set to 1 as maximum product subarray does not include 0. The minimum possible value to be considered in maximum product subarray is already stored in minval , so when maxval is negative it is set to 1. ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxProduct ( int arr [ ] , int n ) { int i ; int ans = INT_MIN ; int maxval = 1 ; int minval = 1 ; int prevMax ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) { maxval = maxval * arr [ i ] ; minval = min ( 1 , minval * arr [ i ] ) ; } else if ( arr [ i ] == 0 ) { minval = 1 ; maxval = 0 ; } else if ( arr [ i ] < 0 ) { prevMax = maxval ; maxval = minval * arr [ i ] ; minval = prevMax * arr [ i ] ; } ans = max ( ans , maxval ) ; if ( maxval <= 0 ) { maxval = 1 ; } } return ans ; } int main ( ) { int arr [ ] = { 0 , -4 , 0 , -2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaxProduct ( arr , n ) ; return 0 ; }
Maximum and Minimum Values of an Algebraic Expression | CPP program to find the maximum and minimum values of an Algebraic expression of given form ; Finding sum of array elements ; shifting the integers by 50 so that they become positive ; dp [ i ] [ j ] represents true if sum j can be reachable by choosing i numbers ; if dp [ i ] [ j ] is true , that means it is possible to select i numbers from ( n + m ) numbers to sum upto j ; k can be at max n because the left expression has n numbers ; checking if a particular sum can be reachable by choosing n numbers ; getting the actual sum as we shifted the numbers by / 50 to avoid negative indexing in array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define INF 1e9 NEW_LINE #define MAX 50 NEW_LINE int minMaxValues ( int arr [ ] , int n , int m ) { int sum = 0 ; for ( int i = 0 ; i < ( n + m ) ; i ++ ) { sum += arr [ i ] ; arr [ i ] += 50 ; } bool dp [ MAX + 1 ] [ MAX * MAX + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i < ( n + m ) ; i ++ ) { for ( int k = min ( n , i + 1 ) ; k >= 1 ; k -- ) { for ( int j = 0 ; j < MAX * MAX + 1 ; j ++ ) { if ( dp [ k - 1 ] [ j ] ) dp [ k ] [ j + arr [ i ] ] = 1 ; } } } int max_value = - INF , min_value = INF ; for ( int i = 0 ; i < MAX * MAX + 1 ; i ++ ) { if ( dp [ n ] [ i ] ) { int temp = i - 50 * n ; max_value = max ( max_value , temp * ( sum - temp ) ) ; min_value = min ( min_value , temp * ( sum - temp ) ) ; } } cout << " Maximum ▁ Value : ▁ " << max_value << " STRNEWLINE " << " Minimum ▁ Value : ▁ " << min_value << endl ; } int main ( ) { int n = 2 , m = 2 ; int arr [ ] = { 1 , 2 , 3 , 4 } ; minMaxValues ( arr , n , m ) ; return 0 ; }
Check if any valid sequence is divisible by M | C ++ program to check if any valid sequence is divisible by M ; Base case ; check if sum is divisible by M ; check if the current state is already computed ; 1. Try placing ' + ' ; 2. Try placing ' - ' ; calculate value of res for recursive case ; store the value for res for current states and return for parent call ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000 ; bool isPossible ( int n , int index , int sum , int M , int arr [ ] , int dp [ ] [ MAX ] ) { if ( index == n ) { if ( ( sum % M ) == 0 ) return true ; return false ; } if ( dp [ index ] [ sum ] != -1 ) return dp [ index ] [ sum ] ; bool placeAdd = isPossible ( n , index + 1 , sum + arr [ index ] , M , arr , dp ) ; bool placeMinus = isPossible ( n , index + 1 , sum - arr [ index ] , M , arr , dp ) ; bool res = ( placeAdd placeMinus ) ; dp [ index ] [ sum ] = res ; return res ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = 4 ; int dp [ n + 1 ] [ MAX ] ; memset ( dp , -1 , sizeof ( dp ) ) ; bool res ; res = isPossible ( n , 0 , 0 , M , arr , dp ) ; cout << ( res ? " True " : " False " ) << endl ; return 0 ; }
Dynamic Programming on Trees | Set 2 | C ++ code to find the maximum path length considering any node as root ; function to pre - calculate the array in [ ] which stores the maximum height when travelled via branches ; initially every node has 0 height ; traverse in the subtree of u ; if child is same as parent ; dfs called ; recursively calculate the max height ; function to pre - calculate the array ouut [ ] which stores the maximum height when traveled via parent ; stores the longest and second longest branches ; traverse in the subtress of u ; compare and store the longest and second longest ; traverse in the subtree of u ; if longest branch has the node , then consider the second longest branch ; recursively calculate out [ i ] ; dfs function call ; function to print all the maximum heights from every node ; traversal to calculate in [ ] array ; traversal to calculate out [ ] array ; print all maximum heights ; Driver Code ; initialize the tree given in the diagram ; function to print the maximum height from every node
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_NODES = 100 ; int in [ MAX_NODES ] ; int out [ MAX_NODES ] ; void dfs1 ( vector < int > v [ ] , int u , int parent ) { in [ u ] = 0 ; for ( int child : v [ u ] ) { if ( child == parent ) continue ; dfs1 ( v , child , u ) ; in [ u ] = max ( in [ u ] , 1 + in [ child ] ) ; } } void dfs2 ( vector < int > v [ ] , int u , int parent ) { int mx1 = -1 , mx2 = -1 ; for ( int child : v [ u ] ) { if ( child == parent ) continue ; if ( in [ child ] >= mx1 ) { mx2 = mx1 ; mx1 = in [ child ] ; } else if ( in [ child ] > mx2 ) mx2 = in [ child ] ; } for ( int child : v [ u ] ) { if ( child == parent ) continue ; int longest = mx1 ; if ( mx1 == in [ child ] ) longest = mx2 ; out [ child ] = 1 + max ( out [ u ] , 1 + longest ) ; dfs2 ( v , child , u ) ; } } void printHeights ( vector < int > v [ ] , int n ) { dfs1 ( v , 1 , 0 ) ; dfs2 ( v , 1 , 0 ) ; for ( int i = 1 ; i <= n ; i ++ ) cout << " The ▁ maximum ▁ height ▁ when ▁ node ▁ " << i << " ▁ is ▁ considered ▁ as ▁ root " << " ▁ is ▁ " << max ( in [ i ] , out [ i ] ) << " STRNEWLINE " ; } int main ( ) { int n = 11 ; vector < int > v [ n + 1 ] ; v [ 1 ] . push_back ( 2 ) , v [ 2 ] . push_back ( 1 ) ; v [ 1 ] . push_back ( 3 ) , v [ 3 ] . push_back ( 1 ) ; v [ 1 ] . push_back ( 4 ) , v [ 4 ] . push_back ( 1 ) ; v [ 2 ] . push_back ( 5 ) , v [ 5 ] . push_back ( 2 ) ; v [ 2 ] . push_back ( 6 ) , v [ 6 ] . push_back ( 2 ) ; v [ 3 ] . push_back ( 7 ) , v [ 7 ] . push_back ( 3 ) ; v [ 7 ] . push_back ( 10 ) , v [ 10 ] . push_back ( 7 ) ; v [ 7 ] . push_back ( 11 ) , v [ 11 ] . push_back ( 7 ) ; v [ 4 ] . push_back ( 8 ) , v [ 8 ] . push_back ( 4 ) ; v [ 4 ] . push_back ( 9 ) , v [ 9 ] . push_back ( 4 ) ; printHeights ( v , n ) ; return 0 ; }
Golomb sequence | C ++ Program to find first n terms of Golomb sequence . ; Return the nth element of Golomb sequence ; base case ; Recursive Step ; Print the first n term of Golomb Sequence ; Finding first n terms of Golomb Sequence . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findGolomb ( int n ) { if ( n == 1 ) return 1 ; return 1 + findGolomb ( n - findGolomb ( findGolomb ( n - 1 ) ) ) ; } void printGolomb ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) cout << findGolomb ( i ) << " ▁ " ; } int main ( ) { int n = 9 ; printGolomb ( n ) ; return 0 ; }
Printing Items in 0 / 1 Knapsack | CPP code for Dynamic Programming based solution for 0 - 1 Knapsack problem ; A utility function that returns maximum of two integers ; Prints the items which are put in a knapsack of capacity W ; Build table K [ ] [ ] in bottom up manner ; stores the result of Knapsack ; either the result comes from the top ( K [ i - 1 ] [ w ] ) or from ( val [ i - 1 ] + K [ i - 1 ] [ w - wt [ i - 1 ] ] ) as in Knapsack table . If it comes from the latter one / it means the item is included . ; This item is included . ; Since this weight is included its value is deducted ; Driver code
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int max ( int a , int b ) { return ( a > b ) ? a : b ; } void printknapSack ( int W , int wt [ ] , int val [ ] , int n ) { int i , w ; int K [ n + 1 ] [ W + 1 ] ; for ( i = 0 ; i <= n ; i ++ ) { for ( w = 0 ; w <= W ; w ++ ) { if ( i == 0 w == 0 ) K [ i ] [ w ] = 0 ; else if ( wt [ i - 1 ] <= w ) K [ i ] [ w ] = max ( val [ i - 1 ] + K [ i - 1 ] [ w - wt [ i - 1 ] ] , K [ i - 1 ] [ w ] ) ; else K [ i ] [ w ] = K [ i - 1 ] [ w ] ; } } int res = K [ n ] [ W ] ; cout << res << endl ; w = W ; for ( i = n ; i > 0 && res > 0 ; i -- ) { if ( res == K [ i - 1 ] [ w ] ) continue ; else { cout << " ▁ " << wt [ i - 1 ] ; res = res - val [ i - 1 ] ; w = w - wt [ i - 1 ] ; } } } int main ( ) { int val [ ] = { 60 , 100 , 120 } ; int wt [ ] = { 10 , 20 , 30 } ; int W = 50 ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; printknapSack ( W , wt , val , n ) ; return 0 ; }
s | C ++ program for the above approach ; To sort the array and return the answer ; sort the array ; fill all stated with - 1 when only one element ; as dp [ 0 ] = 0 ( base case ) so min no of elements to be removed are n - 1 elements ; Iterate from 1 to n - 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int removals ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int dp [ n ] ; for ( int i = 0 ; i < n ; i ++ ) dp [ i ] = -1 ; int ans = n - 1 ; dp [ 0 ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] = i ; int j = dp [ i - 1 ] ; while ( j != i && arr [ i ] - arr [ j ] > k ) { j ++ ; } dp [ i ] = min ( dp [ i ] , j ) ; ans = min ( ans , ( n - ( i - j + 1 ) ) ) ; } return ans ; } int main ( ) { int a [ ] = { 1 , 3 , 4 , 9 , 10 , 11 , 12 , 17 , 20 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 4 ; cout << removals ( a , n , k ) ; return 0 ; }
Maximum number of segments of lengths a , b and c | C ++ implementation to divide N into maximum number of segments of length a , b and c ; function to find the maximum number of segments ; stores the maximum number of segments each index can have ; initialize with - 1 ; 0 th index will have 0 segments base case ; traverse for all possible segments till n ; conditions if ( i + a <= n ) avoid buffer overflow ; if ( i + b <= n ) avoid buffer overflow ; if ( i + c <= n ) avoid buffer overflow ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSegments ( int n , int a , int b , int c ) { int dp [ n + 1 ] ; memset ( dp , -1 , sizeof ( dp ) ) ; dp [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( dp [ i ] != -1 ) { dp [ i + a ] = max ( dp [ i ] + 1 , dp [ i + a ] ) ; dp [ i + b ] = max ( dp [ i ] + 1 , dp [ i + b ] ) ; dp [ i + c ] = max ( dp [ i ] + 1 , dp [ i + c ] ) ; } } return dp [ n ] ; } int main ( ) { int n = 7 , a = 5 , b = 2 , c = 5 ; cout << maximumSegments ( n , a , b , c ) ; return 0 ; }
Maximize the sum of selected numbers from an array to make it empty | CPP program to Maximize the sum of selected numbers by deleting three consecutive numbers . ; function to maximize the sum of selected numbers ; Largest element in the array ; An array to count the occurence of each element ; ans to store the result ; Using the above mentioned approach ; if occurence is greater than 0 ; add it to ans ; decrease i - 1 th element by 1 ; decrease ith element by 1 ; decrease i ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximizeSum ( int arr [ ] , int n ) { int mx = -1 ; for ( int i = 0 ; i < n ; i ++ ) { mx = max ( mx , arr [ i ] ) ; } int freq [ mx + 1 ] ; memset ( freq , 0 , sizeof ( freq ) ) ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } int ans = 0 , i = mx ; while ( i > 0 ) { if ( freq [ i ] > 0 ) { ans += i ; freq [ i - 1 ] -- ; freq [ i ] -- ; } else { i -- ; } } return ans ; } int main ( ) { int a [ ] = { 1 , 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maximizeSum ( a , n ) ; return 0 ; }
Print n terms of Newman | C ++ Program to print n terms of Newman - Conway Sequence ; Function to find the n - th element ; Declare array to store sequence ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sequence ( int n ) { int f [ n + 1 ] ; f [ 0 ] = 0 ; f [ 1 ] = 1 ; f [ 2 ] = 1 ; cout << f [ 1 ] << " ▁ " << f [ 2 ] << " ▁ " ; for ( int i = 3 ; i <= n ; i ++ ) { f [ i ] = f [ f [ i - 1 ] ] + f [ i - f [ i - 1 ] ] ; cout << f [ i ] << " ▁ " ; } } int main ( ) { int n = 13 ; sequence ( n ) ; return 0 ; }
LCS formed by consecutive segments of at least length K | CPP program to find the Length of Longest subsequence formed by consecutive segments of at least length K ; Returns the length of the longest common subsequence with a minimum of length of K consecutive segments ; length of strings ; declare the lcs and cnt array ; iterate from i = 1 to n and j = 1 to j = m ; stores the maximum of lcs [ i - 1 ] [ j ] and lcs [ i ] [ j - 1 ] ; when both the characters are equal of s1 and s2 ; when length of common segment is more than k , then update lcs answer by adding that segment to the answer ; formulate for all length of segments to get the longest subsequence with consecutive Common Segment of length of min k length ; update lcs value by adding segment length ; driver code to check the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubsequenceCommonSegment ( int k , string s1 , string s2 ) { int n = s1 . length ( ) ; int m = s2 . length ( ) ; int lcs [ n + 1 ] [ m + 1 ] ; int cnt [ n + 1 ] [ m + 1 ] ; memset ( lcs , 0 , sizeof ( lcs ) ) ; memset ( cnt , 0 , sizeof ( cnt ) ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { lcs [ i ] [ j ] = max ( lcs [ i - 1 ] [ j ] , lcs [ i ] [ j - 1 ] ) ; if ( s1 [ i - 1 ] == s2 [ j - 1 ] ) cnt [ i ] [ j ] = cnt [ i - 1 ] [ j - 1 ] + 1 ; if ( cnt [ i ] [ j ] >= k ) { for ( int a = k ; a <= cnt [ i ] [ j ] ; a ++ ) lcs [ i ] [ j ] = max ( lcs [ i ] [ j ] , lcs [ i - a ] [ j - a ] + a ) ; } } } return lcs [ n ] [ m ] ; } int main ( ) { int k = 4 ; string s1 = " aggasdfa " ; string s2 = " aggajasdfa " ; cout << longestSubsequenceCommonSegment ( k , s1 , s2 ) ; return 0 ; }
Check for possible path in 2D matrix | C ++ program to find if there is path from top left to right bottom ; to find the path from top left to bottom right ; directions ; queue ; insert the top right corner . ; until queue is empty ; mark as visited ; destination is reached . ; check all four directions ; using the direction array ; not blocked and valid ; Driver Code ; Given array ; path from arr [ 0 ] [ 0 ] to arr [ row ] [ col ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define row 5 NEW_LINE #define col 5 NEW_LINE bool isPath ( int arr [ row ] [ col ] ) { int dir [ 4 ] [ 2 ] = { { 0 , 1 } , { 0 , -1 } , { 1 , 0 } , { -1 , 0 } } ; queue < pair < int , int > > q ; q . push ( make_pair ( 0 , 0 ) ) ; while ( q . size ( ) > 0 ) { pair < int , int > p = q . front ( ) ; q . pop ( ) ; arr [ p . first ] [ p . second ] = -1 ; if ( p == make_pair ( row - 1 , col - 1 ) ) return true ; for ( int i = 0 ; i < 4 ; i ++ ) { int a = p . first + dir [ i ] [ 0 ] ; int b = p . second + dir [ i ] [ 1 ] ; if ( arr [ a ] [ b ] != -1 && a >= 0 && b >= 0 && a < row && b < col ) { q . push ( make_pair ( a , b ) ) ; } } } return false ; } int main ( ) { int arr [ row ] [ col ] = { { 0 , 0 , 0 , -1 , 0 } , { -1 , 0 , 0 , -1 , -1 } , { 0 , 0 , 0 , -1 , 0 } , { -1 , 0 , -1 , 0 , -1 } , { 0 , 0 , -1 , 0 , 0 } } ; if ( isPath ( arr ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Largest rectangular sub | C ++ implementation to find largest rectangular sub - matrix having sum divisible by k ; static readonly int SIZE = 10 ; ; function to find the longest subarray with sum divisible by k . The function stores starting and ending indexes of the subarray at addresses pointed by start and finish pointers respectively . ; unordered map ' um ' implemented as hash table ; ' mod _ arr [ i ] ' stores ( sum [ 0. . i ] % k ) ; traverse arr [ ] and build up the array ' mod _ arr [ ] ' ; as the sum can be negative , taking modulo twice ; if true then sum ( 0. . i ) is divisible by k ; update variables ; if value ' mod _ arr [ i ] ' not present in ' um ' then store it in ' um ' with index of its first occurrence ; if true , then update variables ; function to find largest rectangular sub - matrix having sum divisible by k ; Variables to store the final output ; Set the left column ; Initialize all elements of temp as 0 ; Set the right column for the left column set by outer loop ; Calculate sum between current left and right for every row ' i ' ; The longSubarrWthSumDivByK ( ) function sets the values of ' start ' and ' finish ' . So submatrix having sum divisible by ' k ' between ( start , left ) and ( finish , right ) which is the largest submatrix with boundary columns strictly as left and right . ; Calculate current area and compare it with maximum area so far . If maxArea is less , then update maxArea and other output values ; Print final values ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 10 NEW_LINE #define SIZE 10 NEW_LINE void longSubarrWthSumDivByK ( int arr [ ] , int n , int k , int & start , int & finish ) { unordered_map < int , int > um ; int mod_arr [ n ] ; int curr_sum = 0 , max = 0 ; for ( int i = 0 ; i < n ; i ++ ) { curr_sum += arr [ i ] ; mod_arr [ i ] = ( ( curr_sum % k ) + k ) % k ; } for ( int i = 0 ; i < n ; i ++ ) { if ( mod_arr [ i ] == 0 ) { max = i + 1 ; start = 0 ; finish = i ; } else if ( um . find ( mod_arr [ i ] ) == um . end ( ) ) um [ mod_arr [ i ] ] = i ; else if ( max < ( i - um [ mod_arr [ i ] ] ) ) { max = i - um [ mod_arr [ i ] ] ; start = um [ mod_arr [ i ] ] + 1 ; finish = i ; } } } void findLargestSubmatrix ( int mat [ SIZE ] [ SIZE ] , int n , int k ) { int finalLeft , finalRight , finalTop , finalBottom ; int left , right , i , maxArea = 0 ; int temp [ n ] , start , finish ; for ( left = 0 ; left < n ; left ++ ) { memset ( temp , 0 , sizeof ( temp ) ) ; for ( right = left ; right < n ; right ++ ) { for ( i = 0 ; i < n ; ++ i ) temp [ i ] += mat [ i ] [ right ] ; longSubarrWthSumDivByK ( temp , n , k , start , finish ) ; if ( maxArea < ( ( right - left + 1 ) * ( finish - start + 1 ) ) ) { finalLeft = left ; finalRight = right ; finalTop = start ; finalBottom = finish ; maxArea = ( right - left + 1 ) * ( finish - start + 1 ) ; } } } cout << " ( Top , ▁ Left ) : ▁ ( " << finalTop << " , ▁ " << finalLeft << " ) STRNEWLINE " ; cout << " ( Bottom , ▁ Right ) : ▁ ( " << finalBottom << " , ▁ " << finalRight << " ) STRNEWLINE " ; cout << " Area : ▁ " << maxArea ; } int main ( ) { int mat [ SIZE ] [ SIZE ] = { { 1 , 2 , -1 , -4 } , { -8 , -3 , 4 , 2 } , { 3 , 8 , 10 , 1 } , { -4 , -1 , 1 , 7 } } ; int n = 4 , k = 5 ; findLargestSubmatrix ( mat , n , k ) ; return 0 ; }
Next Smaller Element | A Stack based C ++ program to find next smaller element for all array elements ; prints NSE for elements of array arr [ ] of size n ; iterate for rest of the elements ; while stack is not empty and the top element is greater than next a ) NSE for top is next , use top 's index to maintain original order b) pop the top element from stack ; push next to stack so that we can find NSE for it ; After iterating over the loop , the remaining elements in stack do not have any NSE , so set - 1 for them ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printNSE ( int arr [ ] , int n ) { stack < pair < int , int > > s ; vector < int > ans ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { int next = arr [ i ] ; if ( s . empty ( ) ) { s . push ( { next , i } ) ; continue ; } while ( ! s . empty ( ) && s . top ( ) . first > next ) { ans [ s . top ( ) . second ] = next ; s . pop ( ) ; } s . push ( { next , i } ) ; } while ( ! s . empty ( ) ) { ans [ s . top ( ) . second ] = -1 ; s . pop ( ) ; } for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " ▁ - - - > ▁ " << ans [ i ] << endl ; } } int main ( ) { int arr [ ] = { 11 , 13 , 21 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printNSE ( arr , n ) ; return 0 ; }
Entringer Number | CPP Program to find Entringer Number E ( n , k ) ; Return Entringer Number E ( n , k ) ; Base cases ; Finding dp [ i ] [ j ] ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int zigzag ( int n , int k ) { int dp [ n + 1 ] [ k + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) dp [ i ] [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= i ; j ++ ) dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ i - j ] ; return dp [ n ] [ k ] ; } int main ( ) { int n = 4 , k = 3 ; cout << zigzag ( n , k ) << endl ; return 0 ; }
Lobb Number | CPP Program to find Ln , m Lobb Number . ; Returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Return the Lm , n Lobb Number . ; Driven Program
#include <bits/stdc++.h> NEW_LINE #define MAXN 109 NEW_LINE using namespace std ; int binomialCoeff ( int n , int k ) { int C [ n + 1 ] [ k + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } int lobb ( int n , int m ) { return ( ( 2 * m + 1 ) * binomialCoeff ( 2 * n , m + n ) ) / ( m + n + 1 ) ; } int main ( ) { int n = 5 , m = 3 ; cout << lobb ( n , m ) << endl ; return 0 ; }
Count of arrays having consecutive element with different values | CPP Program to find count of arrays . ; Return the number of arrays with given constartints . ; Initialising dp [ 0 ] and dp [ 1 ] . ; Computing f ( i ) for each 2 <= i <= n . ; Driven Program
#include <bits/stdc++.h> NEW_LINE #define MAXN 109 NEW_LINE using namespace std ; int countarray ( int n , int k , int x ) { int dp [ MAXN ] = { 0 } ; dp [ 0 ] = 0 ; dp [ 1 ] = 1 ; for ( int i = 2 ; i < n ; i ++ ) dp [ i ] = ( k - 2 ) * dp [ i - 1 ] + ( k - 1 ) * dp [ i - 2 ] ; return ( x == 1 ? ( k - 1 ) * dp [ n - 2 ] : dp [ n - 1 ] ) ; } int main ( ) { int n = 4 , k = 3 , x = 2 ; cout << countarray ( n , k , x ) << endl ; return 0 ; }
Number of palindromic subsequences of length k where k <= 3 | CPP program to count number of subsequences of given length . ; Precompute the prefix and suffix array . ; Precompute the prefix 2D array ; Precompute the Suffix 2D array . ; Find the number of palindromic subsequence of length k ; If k is 1. ; If k is 2 ; Adding all the products of prefix array ; For k greater than 2. Adding all the products of value of prefix and suffix array . ; Driven Program
#include <bits/stdc++.h> NEW_LINE #define MAX 100 NEW_LINE #define MAX_CHAR 26 NEW_LINE using namespace std ; void precompute ( string s , int n , int l [ ] [ MAX ] , int r [ ] [ MAX ] ) { l [ s [ 0 ] - ' a ' ] [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < MAX_CHAR ; j ++ ) l [ j ] [ i ] += l [ j ] [ i - 1 ] ; l [ s [ i ] - ' a ' ] [ i ] ++ ; } r [ s [ n - 1 ] - ' a ' ] [ n - 1 ] = 1 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { for ( int j = 0 ; j < MAX_CHAR ; j ++ ) r [ j ] [ i ] += r [ j ] [ i + 1 ] ; r [ s [ i ] - ' a ' ] [ i ] ++ ; } } int countPalindromes ( int k , int n , int l [ ] [ MAX ] , int r [ ] [ MAX ] ) { int ans = 0 ; if ( k == 1 ) { for ( int i = 0 ; i < MAX_CHAR ; i ++ ) ans += l [ i ] [ n - 1 ] ; return ans ; } if ( k == 2 ) { for ( int i = 0 ; i < MAX_CHAR ; i ++ ) ans += ( ( l [ i ] [ n - 1 ] * ( l [ i ] [ n - 1 ] - 1 ) ) / 2 ) ; return ans ; } for ( int i = 1 ; i < n - 1 ; i ++ ) for ( int j = 0 ; j < MAX_CHAR ; j ++ ) ans += l [ j ] [ i - 1 ] * r [ j ] [ i + 1 ] ; return ans ; } int main ( ) { string s = " aabab " ; int k = 2 ; int n = s . length ( ) ; int l [ MAX_CHAR ] [ MAX ] = { 0 } , r [ MAX_CHAR ] [ MAX ] = { 0 } ; precompute ( s , n , l , r ) ; cout << countPalindromes ( k , n , l , r ) << endl ; return 0 ; }
Minimum cost to make Longest Common Subsequence of length k | C ++ program to find subarray with sum closest to 0 ; Return Minimum cost to make LCS of length k ; If k is 0. ; If length become less than 0 , return big number . ; If state already calculated . ; Finding the cost ; Finding minimum cost and saving the state value ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 30 ; int solve ( char X [ ] , char Y [ ] , int l , int r , int k , int dp [ ] [ N ] [ N ] ) { if ( ! k ) return 0 ; if ( l < 0 r < 0 ) return 1e9 ; if ( dp [ l ] [ r ] [ k ] != -1 ) return dp [ l ] [ r ] [ k ] ; int cost = ( X [ l ] - ' a ' ) ^ ( Y [ r ] - ' a ' ) ; return dp [ l ] [ r ] [ k ] = min ( { cost + solve ( X , Y , l - 1 , r - 1 , k - 1 , dp ) , solve ( X , Y , l - 1 , r , k , dp ) , solve ( X , Y , l , r - 1 , k , dp ) } ) ; } int main ( ) { char X [ ] = " abble " ; char Y [ ] = " pie " ; int n = strlen ( X ) ; int m = strlen ( Y ) ; int k = 2 ; int dp [ N ] [ N ] [ N ] ; memset ( dp , -1 , sizeof dp ) ; int ans = solve ( X , Y , n - 1 , m - 1 , k , dp ) ; cout << ( ans == 1e9 ? -1 : ans ) << endl ; return 0 ; }
Maximum sum path in a matrix from top to bottom | C ++ implementation to find the maximum sum path in a matrix ; function to find the maximum sum path in a matric ; if there is a single element only ; dp [ ] [ ] matrix to store the results of each iteration ; base case , copying elements of last row ; building up the dp [ ] [ ] matrix from bottom to the top row ; finding the maximum diagonal element in the ( i + 1 ) th row if that cell exists ; adding that ' max ' element to the mat [ i ] [ j ] element ; finding the maximum value from the first row of dp [ ] [ ] ; required maximum sum ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 10 NEW_LINE int maxSum ( int mat [ SIZE ] [ SIZE ] , int n ) { if ( n == 1 ) return mat [ 0 ] [ 0 ] ; int dp [ n ] [ n ] ; int maxSum = INT_MIN , max ; for ( int j = 0 ; j < n ; j ++ ) dp [ n - 1 ] [ j ] = mat [ n - 1 ] [ j ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) { for ( int j = 0 ; j < n ; j ++ ) { max = INT_MIN ; if ( ( ( j - 1 ) >= 0 ) && ( max < dp [ i + 1 ] [ j - 1 ] ) ) max = dp [ i + 1 ] [ j - 1 ] ; if ( ( ( j + 1 ) < n ) && ( max < dp [ i + 1 ] [ j + 1 ] ) ) max = dp [ i + 1 ] [ j + 1 ] ; dp [ i ] [ j ] = mat [ i ] [ j ] + max ; } } for ( int j = 0 ; j < n ; j ++ ) if ( maxSum < dp [ 0 ] [ j ] ) maxSum = dp [ 0 ] [ j ] ; return maxSum ; } int main ( ) { int mat [ SIZE ] [ SIZE ] = { { 5 , 6 , 1 , 7 } , { -2 , 10 , 8 , -1 } , { 3 , -7 , -9 , 11 } , { 12 , -4 , 2 , 6 } } ; int n = 4 ; cout << " Maximum ▁ Sum ▁ = ▁ " << maxSum ( mat , n ) ; return 0 ; }
Longest Repeated Subsequence | C ++ program to find the longest repeated subsequence ; This function mainly returns LCS ( str , str ) with a condition that same characters at same index are not considered . ; THIS PART OF CODE IS SAME AS BELOW POST . IT FILLS dp [ ] [ ] https : www . geeksforgeeks . org / longest - repeating - subsequence / OR the code mentioned above . ; THIS PART OF CODE FINDS THE RESULT STRING USING DP [ ] [ ] Initialize result ; Traverse dp [ ] [ ] from bottom right ; If this cell is same as diagonally adjacent cell just above it , then same characters are present at str [ i - 1 ] and str [ j - 1 ] . Append any of them to result . ; Otherwise we move to the side that that gave us maximum result ; Since we traverse dp [ ] [ ] from bottom , we get result in reverse order . ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; string longestRepeatedSubSeq ( 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 i = 1 ; i <= n ; i ++ ) for ( int j = 1 ; j <= n ; j ++ ) if ( str [ i - 1 ] == str [ j - 1 ] && i != j ) dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = max ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j ] ) ; string res = " " ; int i = n , j = n ; while ( i > 0 && j > 0 ) { if ( dp [ i ] [ j ] == dp [ i - 1 ] [ j - 1 ] + 1 ) { res = res + str [ i - 1 ] ; i -- ; j -- ; } else if ( dp [ i ] [ j ] == dp [ i - 1 ] [ j ] ) i -- ; else j -- ; } reverse ( res . begin ( ) , res . end ( ) ) ; return res ; } int main ( ) { string str = " AABEBCDD " ; cout << longestRepeatedSubSeq ( str ) ; return 0 ; }
Sub | CPP code to find the sub - tree with minimum color difference in a 2 - coloured tree ; Tree traversal to compute minimum difference ; Initial min difference is the color of node ; Traversing its children ; Not traversing the parent ; If the child is adding positively to difference , we include it in the answer Otherwise , we leave the sub - tree and include 0 ( nothing ) in the answer ; DFS for colour difference : 1 colour - 2 colour ; Minimum colour difference is maximum answer value ; Clearing the current value to check for colour2 as well ; Interchanging the colours ; DFS for colour difference : 2 colour - 1 colour ; Checking if colour2 makes the minimum colour difference ; Driver code ; Nodes ; Adjacency list representation ; Edges ; Index represent the colour of that node There is no Node 0 , so we start from index 1 to N ; Printing the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( int node , int parent , vector < int > tree [ ] , int colour [ ] , int answer [ ] ) { answer [ node ] = colour [ node ] ; for ( auto u : tree [ node ] ) { if ( u == parent ) continue ; dfs ( u , node , tree , colour , answer ) ; answer [ node ] += max ( answer [ u ] , 0 ) ; } } int maxDiff ( vector < int > tree [ ] , int colour [ ] , int N ) { int answer [ N + 1 ] ; memset ( answer , 0 , sizeof ( answer ) ) ; dfs ( 1 , 0 , tree , colour , answer ) ; int high = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { high = max ( high , answer [ i ] ) ; answer [ i ] = 0 ; } for ( int i = 1 ; i <= N ; i ++ ) { if ( colour [ i ] == -1 ) colour [ i ] = 1 ; else colour [ i ] = -1 ; } dfs ( 1 , 0 , tree , colour , answer ) ; for ( int i = 1 ; i < N ; i ++ ) high = max ( high , answer [ i ] ) ; return high ; } int main ( ) { int N = 5 ; vector < int > tree [ N + 1 ] ; tree [ 1 ] . push_back ( 2 ) ; tree [ 2 ] . push_back ( 1 ) ; tree [ 1 ] . push_back ( 3 ) ; tree [ 3 ] . push_back ( 1 ) ; tree [ 2 ] . push_back ( 4 ) ; tree [ 4 ] . push_back ( 2 ) ; tree [ 3 ] . push_back ( 5 ) ; tree [ 5 ] . push_back ( 3 ) ; int colour [ ] = { 0 , 1 , 1 , -1 , -1 , 1 } ; cout << maxDiff ( tree , colour , N ) ; return 0 ; }
Maximum elements that can be made equal with k updates | C ++ program to find maximum elements that can be made equal with k updates ; Function to calculate the maximum number of equal elements possible with atmost K increment of values . Here we have done sliding window to determine that whether there are x number of elements present which on increment will become equal . The loop here will run in fashion like 0. . . x - 1 , 1. . . x , 2. . . x + 1 , ... . , n - x - 1. . . n - 1 ; It can be explained with the reasoning that if for some x number of elements we can update the values then the increment to the segment ( i to j having length -> x ) so that all will be equal is ( x * maxx [ j ] ) this is the total sum of segment and ( pre [ j ] - pre [ i ] ) is present sum So difference of them should be less than k if yes , then that segment length ( x ) can be possible return true ; sort the array in ascending order ; Initializing the prefix array and maximum array ; Calculating prefix sum of the array ; Calculating max value upto that position in the array ; Binary search applied for computation here ; printing result
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool ElementsCalculationFunc ( int pre [ ] , int maxx [ ] , int x , int k , int n ) { for ( int i = 0 , j = x ; j <= n ; j ++ , i ++ ) { if ( x * maxx [ j ] - ( pre [ j ] - pre [ i ] ) <= k ) return true ; } return false ; } void MaxNumberOfElements ( int a [ ] , int n , int k ) { sort ( a , a + n ) ; for ( int i = 0 ; i <= n ; ++ i ) { pre [ i ] = 0 ; maxx [ i ] = 0 ; } for ( int i = 1 ; i <= n ; i ++ ) { pre [ i ] = pre [ i - 1 ] + a [ i - 1 ] ; maxx [ i ] = max ( maxx [ i - 1 ] , a [ i - 1 ] ) ; } int l = 1 , r = n , ans ; while ( l < r ) { int mid = ( l + r ) / 2 ; if ( ElementsCalculationFunc ( pre , maxx , mid - 1 , k , n ) ) { ans = mid ; l = mid + 1 ; } else r = mid - 1 ; } cout << ans << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 2 , 4 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; MaxNumberOfElements ( arr , n , k ) ; return 0 ; }
Remove array end element to maximize the sum of product | CPP program to find maximum score we can get by removing elements from either end . ; If only one element left . ; If already calculated , return the value . ; Computing Maximum value when element at index i and index j is to be choosed . ; Driven Program
#include <bits/stdc++.h> NEW_LINE #define MAX 50 NEW_LINE using namespace std ; int solve ( int dp [ ] [ MAX ] , int a [ ] , int low , int high , int turn ) { if ( low == high ) return a [ low ] * turn ; if ( dp [ low ] [ high ] != 0 ) return dp [ low ] [ high ] ; dp [ low ] [ high ] = max ( a [ low ] * turn + solve ( dp , a , low + 1 , high , turn + 1 ) , a [ high ] * turn + solve ( dp , a , low , high - 1 , turn + 1 ) ) ; return dp [ low ] [ high ] ; } int main ( ) { int arr [ ] = { 1 , 3 , 1 , 5 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int dp [ MAX ] [ MAX ] ; memset ( dp , 0 , sizeof ( dp ) ) ; cout << solve ( dp , arr , 0 , n - 1 , 1 ) << endl ; return 0 ; }
Maximum sum bitonic subarray | C ++ implementation to find the maximum sum bitonic subarray ; function to find the maximum sum bitonic subarray ; ' msis [ ] ' to store the maximum sum increasing subarray up to each index of ' arr ' from the beginning ' msds [ ] ' to store the maximum sum decreasing subarray from each index of ' arr ' up to the end ; to store the maximum sum bitonic subarray ; building up the maximum sum increasing subarray for each array index ; building up the maximum sum decreasing subarray for each array index ; for each array index , calculating the maximum sum of bitonic subarray of which it is a part of ; if true , then update ' max ' bitonic subarray sum ; required maximum sum ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumBitonicSubArr ( int arr [ ] , int n ) { int msis [ n ] , msds [ n ] ; int max_sum = INT_MIN ; msis [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > arr [ i - 1 ] ) msis [ i ] = msis [ i - 1 ] + arr [ i ] ; else msis [ i ] = arr [ i ] ; msds [ n - 1 ] = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) if ( arr [ i ] > arr [ i + 1 ] ) msds [ i ] = msds [ i + 1 ] + arr [ i ] ; else msds [ i ] = arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) if ( max_sum < ( msis [ i ] + msds [ i ] - arr [ i ] ) ) max_sum = msis [ i ] + msds [ i ] - arr [ i ] ; return max_sum ; } int main ( ) { int arr [ ] = { 5 , 3 , 9 , 2 , 7 , 6 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum ▁ Sum ▁ = ▁ " << maxSumBitonicSubArr ( arr , n ) ; return 0 ; }
Find k | C ++ implementation to solve k queries for given n ranges ; Structure to store the start and end point ; Comparison function for sorting ; Function to find Kth smallest number in a vector of merged intervals ; Traverse merged [ ] to find Kth smallest element using Linear search . ; To combined both type of ranges , overlapping as well as non - overlapping . ; Sorting intervals according to start time ; Merging all intervals into merged ; To check if starting point of next range is lying between the previous range and ending point of next range is greater than the Ending point of previous range then update ending point of previous range by ending point of next range . ; If starting point of next range is greater than the ending point of previous range then store next range in merged [ ] . ; Driver \'s Function ; Merge all intervals into merged [ ] ; Processing all queries on merged intervals
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Interval { int s ; int e ; } ; bool comp ( Interval a , Interval b ) { return a . s < b . s ; } int kthSmallestNum ( vector < Interval > merged , int k ) { int n = merged . size ( ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( k <= abs ( merged [ j ] . e - merged [ j ] . s + 1 ) ) return ( merged [ j ] . s + k - 1 ) ; k = k - abs ( merged [ j ] . e - merged [ j ] . s + 1 ) ; } if ( k ) return -1 ; } void mergeIntervals ( vector < Interval > & merged , Interval arr [ ] , int n ) { sort ( arr , arr + n , comp ) ; merged . push_back ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { Interval prev = merged . back ( ) ; Interval curr = arr [ i ] ; if ( ( curr . s >= prev . s && curr . s <= prev . e ) && ( curr . e > prev . e ) ) merged . back ( ) . e = curr . e ; else { if ( curr . s > prev . e ) merged . push_back ( curr ) ; } } } int main ( ) { Interval arr [ ] = { { 2 , 6 } , { 4 , 7 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int query [ ] = { 5 , 8 } ; int q = sizeof ( query ) / sizeof ( query [ 0 ] ) ; vector < Interval > merged ; mergeIntervals ( merged , arr , n ) ; for ( int i = 0 ; i < q ; i ++ ) cout << kthSmallestNum ( merged , query [ i ] ) << endl ; return 0 ; }
Shortest possible combination of two strings | C ++ program to print supersequence of two strings ; Prints super sequence of a [ 0. . m - 1 ] and b [ 0. . n - 1 ] ; Fill table in bottom up manner ; Below steps follow above recurrence ; Following code is used to print supersequence ; Create a string of size index + 1 to store the result ; Start from the right - most - bottom - most corner and one by one store characters in res [ ] ; If current character in a [ ] and b are same , then current character is part of LCS ; Put current character in result ; reduce values of i , j and indexs ; If not same , then find the smaller of two and go in the direction of smaller value ; Copy remaining characters of string ' a ' ; Copy remaining characters of string ' b ' ; Print the result ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSuperSeq ( string & a , string & b ) { int m = a . length ( ) , n = b . length ( ) ; int dp [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( ! i ) dp [ i ] [ j ] = j ; else if ( ! j ) dp [ i ] [ j ] = i ; else if ( a [ i - 1 ] == b [ j - 1 ] ) dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = 1 + min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ; } } int index = dp [ m ] [ n ] ; string res ( index + 1 , ' \0' ) ; int i = m , j = n ; while ( i > 0 && j > 0 ) { if ( a [ i - 1 ] == b [ j - 1 ] ) { res [ index - 1 ] = a [ i - 1 ] ; i -- ; j -- ; index -- ; } else if ( dp [ i - 1 ] [ j ] < dp [ i ] [ j - 1 ] ) { res [ index - 1 ] = a [ i - 1 ] ; i -- ; index -- ; } else { res [ index - 1 ] = b [ j - 1 ] ; j -- ; index -- ; } } while ( i > 0 ) { res [ index - 1 ] = a [ i - 1 ] ; i -- ; index -- ; } while ( j > 0 ) { res [ index - 1 ] = b [ j - 1 ] ; j -- ; index -- ; } cout << res ; } int main ( ) { string a = " algorithm " , b = " rhythm " ; printSuperSeq ( a , b ) ; return 0 ; }
Find length of longest subsequence of one string which is substring of another string | Base Case ; if the last char of both strings are equal ; if the last char of both strings are not equal ; Driver code ; as minimum length can be 0 only . ; traversing for every length of Y .
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubsequenceSubstring ( string & X , string & Y , int n , int m ) { if ( n == 0 m == 0 ) return 0 ; if ( X [ n - 1 ] == Y [ m - 1 ] ) { return 1 + maxSubsequenceSubstring ( X , Y , n - 1 , m - 1 ) ; } else { return maxSubsequenceSubstring ( X , Y , n - 1 , m ) ; } } int main ( ) { string X = " abcd " ; string Y = " bacdbdcd " ; int n = X . size ( ) , m = Y . size ( ) ; int maximum_length = 0 ; for ( int i = 0 ; i <= m ; i ++ ) { int temp_ans = maxSubsequenceSubstring ( X , Y , n , i ) ; if ( temp_ans > maximum_length ) maximum_length = temp_ans ; } cout << " Length ▁ for ▁ maximum ▁ possible ▁ Subsequence ▁ of ▁ string ▁ X ▁ which ▁ is ▁ Substring ▁ of ▁ Y ▁ - > ▁ " << maximum_length ; return 0 ; }
Minimum time to write characters using insert , delete and copy operation | C ++ program to write characters in minimum time by inserting , removing and copying operation ; method returns minimum time to write ' N ' characters ; declare dp array and initialize with zero ; first char will always take insertion time ; loop for ' N ' number of times ; if current char count is even then choose minimum from result for ( i - 1 ) chars and time for insertion and result for half of chars and time for copy ; if current char count is odd then choose minimum from result for ( i - 1 ) chars and time for insertion and result for half of chars and time for copy and one extra character deletion ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minTimeForWritingChars ( int N , int insert , int remove , int copy ) { if ( N == 0 ) return 0 ; if ( N == 1 ) return insert ; int dp [ N + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 1 ] = insert ; for ( int i = 2 ; i <= N ; i ++ ) { if ( i % 2 == 0 ) dp [ i ] = min ( dp [ i - 1 ] + insert , dp [ i / 2 ] + copy ) ; else dp [ i ] = min ( dp [ i - 1 ] + insert , dp [ ( i + 1 ) / 2 ] + copy + remove ) ; } return dp [ N ] ; } int main ( ) { int N = 9 ; int insert = 1 , remove = 2 , copy = 1 ; cout << minTimeForWritingChars ( N , insert , remove , copy ) ; return 0 ; }
Count the number of ways to tile the floor of size n x m using 1 x m size tiles | C ++ implementation to count number of ways to tile a floor of size n x m using 1 x m tiles ; function to count the total number of ways ; table to store values of subproblems ; Fill the table upto value n ; recurrence relation ; base cases and for i = m = 1 ; i = = m ; required number of ways ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int n , int m ) { int count [ n + 1 ] ; count [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i > m ) count [ i ] = count [ i - 1 ] + count [ i - m ] ; else if ( i < m i == 1 ) count [ i ] = 1 ; else count [ i ] = 2 ; } return count [ n ] ; } int main ( ) { int n = 7 , m = 4 ; cout << " Number ▁ of ▁ ways ▁ = ▁ " << countWays ( n , m ) ; return 0 ; }
Longest alternating subsequence | C ++ program for above approach ; Function for finding longest alternating subsequence ; " inc " and " dec " initialized as 1 as single element is still LAS ; Iterate from second element ; " inc " changes iff " dec " changes ; " dec " changes iff " inc " changes ; Return the maximum length ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LAS ( int arr [ ] , int n ) { int inc = 1 ; int dec = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] ) { inc = dec + 1 ; } else if ( arr [ i ] < arr [ i - 1 ] ) { dec = inc + 1 ; } } return max ( inc , dec ) ; } int main ( ) { int arr [ ] = { 10 , 22 , 9 , 33 , 49 , 50 , 31 , 60 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << LAS ( arr , n ) << endl ; return 0 ; }
Minimum number of deletions to make a string palindrome | C ++ program for above approach ; Function to return minimum Element between two values ; Utility function for calculating Minimum element to delete ; Condition to compare characters ; Recursive function call ; Return value , incrementing by 1 ; Function to calculate the minimum Element required to delete for Making string pelindrom ; Utility function call ; Driver code
#include <iostream> NEW_LINE using namespace std ; int min ( int x , int y ) { return ( x < y ) ? x : y ; } int utility_fun_for_del ( string str , int i , int j ) { if ( i >= j ) return 0 ; if ( str [ i ] == str [ j ] ) { return utility_fun_for_del ( str , i + 1 , j - 1 ) ; } return 1 + min ( utility_fun_for_del ( str , i + 1 , j ) , utility_fun_for_del ( str , i , j - 1 ) ) ; } int min_ele_del ( string str ) { return utility_fun_for_del ( str , 0 , str . length ( ) - 1 ) ; } int main ( ) { string str = " abefbac " ; cout << " Minimum ▁ element ▁ of ▁ deletions ▁ = ▁ " << min_ele_del ( str ) << endl ; return 0 ; }
Minimum number of deletions to make a string palindrome | Function definition ; Base cases ; Checking the ndesired condition ; If yes increment the count ; If no ; Return the value form the table ; Else store the max tranforamtion from the subsequence ; Return the dp [ - 1 ] [ - 1 ] ; Driver code ; Initialize the array with - 1
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 2000 ] [ 2000 ] ; int transformation ( string s1 , string s2 , int i , int j ) { if ( i >= ( s1 . size ( ) ) || j >= ( s2 . size ( ) ) ) return 0 ; if ( s1 [ i ] == s2 [ j ] ) { dp [ i ] [ j ] = 1 + transformation ( s1 , s2 , i + 1 , j + 1 ) ; } if ( dp [ i ] [ j ] != -1 ) { return dp [ i ] [ j ] ; } else dp [ i ] [ j ] = max ( transformation ( s1 , s2 , i , j + i ) , transformation ( s1 , s2 , i + 1 , j ) ) ; return dp [ s1 . size ( ) - 1 ] [ s2 . size ( ) - 1 ] ; } int main ( ) { string s1 = " geeksforgeeks " ; string s2 = " geeks " ; int i = 0 ; int j = 0 ; memset ( dp , -1 , sizeof dp ) ; cout << " MINIMUM ▁ NUMBER ▁ OF ▁ DELETIONS : ▁ " << ( s1 . size ( ) ) - transformation ( s1 , s2 , 0 , 0 ) << endl ; cout << " MINIMUM ▁ NUMBER ▁ OF ▁ INSERTIONS : ▁ " << ( s2 . size ( ) ) - transformation ( s1 , s2 , 0 , 0 ) << endl ; cout << ( " LCS ▁ LENGTH : ▁ " ) << transformation ( s1 , s2 , 0 , 0 ) ; }
Largest sum Zigzag sequence in a matrix | 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 largestZigZagSumRec ( int mat [ ] [ MAX ] , int i , int j , int n ) { if ( i == n - 1 ) return 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 zzs + mat [ i ] [ j ] ; } int largestZigZag ( int mat [ ] [ MAX ] , int n ) { 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 ; }
Perfect Sum Problem ( Print all subsets with given sum ) | C ++ program to count all subsets with given sum . ; dp [ i ] [ j ] is going to store true if sum j is possible with array elements from 0 to i . ; A recursive function to print all subsets with the help of dp [ ] [ ] . Vector p [ ] stores current subset . ; If we reached end and sum is non - zero . We print p [ ] only if arr [ 0 ] is equal to sun OR dp [ 0 ] [ sum ] is true . ; Display Only when Sum of elements of p is equal to sum ; If sum becomes 0 ; If given sum can be achieved after ignoring current element . ; Create a new vector to store path ; If given sum can be achieved after considering current element . ; Prints all subsets of arr [ 0. . n - 1 ] with sum 0. ; Sum 0 can always be achieved with 0 elements ; Sum arr [ 0 ] can be achieved with single element ; Fill rest of the entries in dp [ ] [ ] ; Now recursively traverse dp [ ] [ ] to find all paths from dp [ n - 1 ] [ sum ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool * * dp ; void display ( const vector < int > & v ) { for ( int i = 0 ; i < v . size ( ) ; ++ i ) printf ( " % d ▁ " , v [ i ] ) ; printf ( " STRNEWLINE " ) ; } void printSubsetsRec ( int arr [ ] , int i , int sum , vector < int > & p ) { if ( i == 0 && sum != 0 && dp [ 0 ] [ sum ] ) { p . push_back ( arr [ i ] ) ; if ( arr [ i ] == sum ) display ( p ) ; return ; } if ( i == 0 && sum == 0 ) { display ( p ) ; return ; } if ( dp [ i - 1 ] [ sum ] ) { vector < int > b = p ; printSubsetsRec ( arr , i - 1 , sum , b ) ; } if ( sum >= arr [ i ] && dp [ i - 1 ] [ sum - arr [ i ] ] ) { p . push_back ( arr [ i ] ) ; printSubsetsRec ( arr , i - 1 , sum - arr [ i ] , p ) ; } } void printAllSubsets ( int arr [ ] , int n , int sum ) { if ( n == 0 sum < 0 ) return ; dp = new bool * [ n ] ; for ( int i = 0 ; i < n ; ++ i ) { dp [ i ] = new bool [ sum + 1 ] ; dp [ i ] [ 0 ] = true ; } if ( arr [ 0 ] <= sum ) dp [ 0 ] [ arr [ 0 ] ] = true ; for ( int i = 1 ; i < n ; ++ i ) for ( int j = 0 ; j < sum + 1 ; ++ j ) dp [ i ] [ j ] = ( arr [ i ] <= j ) ? dp [ i - 1 ] [ j ] || dp [ i - 1 ] [ j - arr [ i ] ] : dp [ i - 1 ] [ j ] ; if ( dp [ n - 1 ] [ sum ] == false ) { printf ( " There ▁ are ▁ no ▁ subsets ▁ with ▁ sum ▁ % d STRNEWLINE " , sum ) ; return ; } vector < int > p ; printSubsetsRec ( arr , n - 1 , sum , p ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int sum = 10 ; printAllSubsets ( arr , n , sum ) ; return 0 ; }
Count ways to increase LCS length of two strings by one | C ++ program to get number of ways to increase LCS by 1 ; Utility method to get integer position of lower alphabet character ; Method returns total ways to increase LCS length by 1 ; Fill positions of each character in vector ; Initializing 2D array by 0 values ; Filling LCS array for prefix substrings ; Filling LCS array for suffix substrings ; Looping for all possible insertion positions in first string ; Trying all possible lower case characters ; Now for each character , loop over same character positions in second string ; If both , left and right substrings make total LCS then increase result by 1 ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 26 NEW_LINE int toInt ( char ch ) { return ( ch - ' a ' ) ; } int waysToIncreaseLCSBy1 ( string str1 , string str2 ) { int m = str1 . length ( ) , n = str2 . length ( ) ; vector < int > position [ M ] ; for ( int i = 1 ; i <= n ; i ++ ) position [ toInt ( str2 [ i - 1 ] ) ] . push_back ( i ) ; int lcsl [ m + 2 ] [ n + 2 ] ; int lcsr [ m + 2 ] [ n + 2 ] ; for ( int i = 0 ; i <= m + 1 ; i ++ ) for ( int j = 0 ; j <= n + 1 ; j ++ ) lcsl [ i ] [ j ] = lcsr [ i ] [ j ] = 0 ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( str1 [ i - 1 ] == str2 [ j - 1 ] ) lcsl [ i ] [ j ] = 1 + lcsl [ i - 1 ] [ j - 1 ] ; else lcsl [ i ] [ j ] = max ( lcsl [ i - 1 ] [ j ] , lcsl [ i ] [ j - 1 ] ) ; } } for ( int i = m ; i >= 1 ; i -- ) { for ( int j = n ; j >= 1 ; j -- ) { if ( str1 [ i - 1 ] == str2 [ j - 1 ] ) lcsr [ i ] [ j ] = 1 + lcsr [ i + 1 ] [ j + 1 ] ; else lcsr [ i ] [ j ] = max ( lcsr [ i + 1 ] [ j ] , lcsr [ i ] [ j + 1 ] ) ; } } int ways = 0 ; for ( int i = 0 ; i <= m ; i ++ ) { for ( char c = ' a ' ; c <= ' z ' ; c ++ ) { for ( int j = 0 ; j < position [ toInt ( c ) ] . size ( ) ; j ++ ) { int p = position [ toInt ( c ) ] [ j ] ; if ( lcsl [ i ] [ p - 1 ] + lcsr [ i + 1 ] [ p + 1 ] == lcsl [ m ] [ n ] ) ways ++ ; } } } return ways ; } int main ( ) { string str1 = " abcabc " ; string str2 = " abcd " ; cout << waysToIncreaseLCSBy1 ( str1 , str2 ) ; return 0 ; }
Count of strings that can be formed using a , b and c under given constraints | C ++ program to count number of strings of n characters with ; n is total number of characters . bCount and cCount are counts of ' b ' and ' c ' respectively . ; Base cases ; Three cases , we choose , a or b or c In all three cases n decreases by 1. ; Driver code ; Total number of characters
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countStr ( int n , int bCount , int cCount ) { if ( bCount < 0 cCount < 0 ) return 0 ; if ( n == 0 ) return 1 ; if ( bCount == 0 && cCount == 0 ) return 1 ; int res = countStr ( n - 1 , bCount , cCount ) ; res += countStr ( n - 1 , bCount - 1 , cCount ) ; res += countStr ( n - 1 , bCount , cCount - 1 ) ; return res ; } int main ( ) { int n = 3 ; cout << countStr ( n , 1 , 2 ) ; return 0 ; }
Maximum path sum that starting with any cell of 0 | C ++ program to find Maximum path sum start any column in row '0' and ends up to any column in row ' n - 1' ; function find maximum sum path ; create 2D matrix to store the sum of the path ; initialize all dp matrix as '0' ; copy all element of first column into ' dp ' first column ; Find maximum path sum that end ups at any column of last row ' N - 1' ; return maximum sum path ; driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE int MaximumPath ( int Mat [ ] [ N ] ) { int result = 0 ; int dp [ N ] [ N + 2 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 0 ; i < N ; i ++ ) dp [ 0 ] [ i + 1 ] = Mat [ 0 ] [ i ] ; for ( int i = 1 ; i < N ; i ++ ) for ( int j = 1 ; j <= N ; j ++ ) dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j - 1 ] , max ( dp [ i - 1 ] [ j ] , dp [ i - 1 ] [ j + 1 ] ) ) + Mat [ i ] [ j - 1 ] ; for ( int i = 0 ; i <= N ; i ++ ) result = max ( result , dp [ N - 1 ] [ i ] ) ; return result ; } int main ( ) { int Mat [ 4 ] [ 4 ] = { { 4 , 2 , 3 , 4 } , { 2 , 9 , 1 , 10 } , { 15 , 1 , 3 , 0 } , { 16 , 92 , 41 , 44 } } ; cout << MaximumPath ( Mat ) << endl ; return 0 ; }
Probability of getting at least K heads in N tosses of Coins | Dynamic and Logarithm approach find probability of at least k heads ; dp [ i ] is going to store Log ( i ! ) in base 2 ; Initialize result ; Iterate from k heads to n heads ; Preprocess all the logarithm value on base 2 ; Driver code ; Probability of getting 2 head out of 3 coins ; Probability of getting 3 head out of 6 coins ; Probability of getting 500 head out of 10000 coins
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100001 NEW_LINE double dp [ MAX ] ; double probability ( int k , int n ) { double ans = 0 ; for ( int i = k ; i <= n ; ++ i ) { double res = dp [ n ] - dp [ i ] - dp [ n - i ] - n ; ans += pow ( 2.0 , res ) ; } return ans ; } void precompute ( ) { for ( int i = 2 ; i < MAX ; ++ i ) dp [ i ] = log2 ( i ) + dp [ i - 1 ] ; } int main ( ) { precompute ( ) ; cout << probability ( 2 , 3 ) << " STRNEWLINE " ; cout << probability ( 3 , 6 ) << " STRNEWLINE " ; cout << probability ( 500 , 1000 ) ; 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 . ; dp [ i ] [ j ] stores maximum possible number of people among arr [ 0. . i - 1 ] can vote in j time . ; Find sum of all times ; Fill dp [ ] [ ] in bottom up manner ( Similar to knapsack ) . ; If remaining people can go to other machine . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool canVote ( int a [ ] , int n , int x ) { int dp [ n + 1 ] [ x + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; int sum = 0 ; for ( int i = 0 ; i <= n ; i ++ ) sum += a [ i ] ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = 1 ; j <= x ; j ++ ) if ( a [ i ] <= j ) dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , a [ i ] + dp [ i - 1 ] [ j - a [ i ] ] ) ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; return ( sum - dp [ n ] [ x ] <= x ) ; } int main ( ) { int n = 3 , x = 4 ; int a [ ] = { 2 , 4 , 2 } ; canVote ( a , n , x ) ? cout << " YES STRNEWLINE " : cout << " NO STRNEWLINE " ; return 0 ; }
Maximum path sum for each position with jumps under divisibility condition | C ++ program to print maximum path sum ending with each position x such that all path step positions divide x . ; Create an array such that dp [ i ] stores maximum path sum ending with i . ; Calculating maximum sum path for each element . ; Finding previous step for arr [ i ] Moving from 1 to sqrt ( i + 1 ) since all the divisors are present from sqrt ( i + 1 ) . ; Checking if j is divisor of i + 1. ; Checking which divisor will provide greater value . ; Printing the answer ( Maximum path sum ending with every position i + 1. ; Driven Program ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMaxSum ( int arr [ ] , int n ) { int dp [ n ] ; memset ( dp , 0 , sizeof dp ) ; for ( int i = 0 ; i < n ; i ++ ) { dp [ i ] = arr [ i ] ; int maxi = 0 ; for ( int j = 1 ; j <= sqrt ( i + 1 ) ; j ++ ) { if ( ( ( i + 1 ) % j == 0 ) && ( i + 1 ) != j ) { if ( dp [ j - 1 ] > maxi ) maxi = dp [ j - 1 ] ; if ( dp [ ( i + 1 ) / j - 1 ] > maxi && j != 1 ) maxi = dp [ ( i + 1 ) / j - 1 ] ; } } dp [ i ] += maxi ; } for ( int i = 0 ; i < n ; i ++ ) cout << dp [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 2 , 3 , 1 , 4 , 6 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printMaxSum ( arr , n ) ; return 0 ; }
Minimum sum subsequence such that at least one of every four consecutive elements is picked | CPP program to calculate minimum possible sum for given constraint ; function to calculate min sum using dp ; if elements are less than or equal to 4 ; save start four element as it is ; compute sum [ ] for all rest elements ; sum [ i ] = ar [ i ] + ( * min_element ( sum + i - 4 , sum + i ) ) ; ; Since one of the last 4 elements must be present ; driver program
#include <bits/stdc++.h> NEW_LINE typedef long long ll ; using namespace std ; int minSum ( int ar [ ] , int n ) { if ( n <= 4 ) return * min_element ( ar , ar + n ) ; int sum [ n ] ; sum [ 0 ] = ar [ 0 ] ; sum [ 1 ] = ar [ 1 ] ; sum [ 2 ] = ar [ 2 ] ; sum [ 3 ] = ar [ 3 ] ; for ( int i = 4 ; i < n ; i ++ ) sum [ i ] = ar [ i ] + ( * min_element ( sum + i - 4 , sum + i ) ) ; return * min_element ( sum + n - 4 , sum + n ) ; } int main ( ) { int ar [ ] = { 2 , 4 , 1 , 5 , 2 , 3 , 6 , 1 , 2 , 4 } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; cout << " Minimum ▁ sum ▁ = ▁ " << minSum ( ar , n ) ; return 0 ; }
Maximum sum alternating subsequence | C ++ program to find sum of maximum sum alternating sequence starting with first element . ; Return sum of maximum sum alternating sequence starting with arr [ 0 ] and is first decreasing . ; handling the edge case ; stores sum of decreasing and increasing sub - sequence ; store sum of increasing and decreasing sun - sequence ; As per question , first element must be part of solution . ; Traverse remaining elements of array ; IF current sub - sequence is decreasing the update dec [ j ] if needed . dec [ i ] by current inc [ j ] + arr [ i ] ; Revert the flag , if first decreasing is found ; If next element is greater but flag should be 1 i . e . this element should be counted after the first decreasing element gets counted ; If current sub - sequence is increasing then update inc [ i ] ; find maximum sum in b / w inc [ ] and dec [ ] ; return maximum sum alternate sun - sequence ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxAlternateSum ( int arr [ ] , int n ) { if ( n == 1 ) return arr [ 0 ] ; int min = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( min > arr [ i ] ) min = arr [ i ] ; } if ( min == arr [ 0 ] ) { return arr [ 0 ] ; } int dec [ n ] ; memset ( dec , 0 , sizeof ( dec ) ) ; int inc [ n ] ; memset ( inc , 0 , sizeof ( inc ) ) ; dec [ 0 ] = inc [ 0 ] = arr [ 0 ] ; int flag = 0 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ j ] > arr [ i ] ) { dec [ i ] = max ( dec [ i ] , inc [ j ] + arr [ i ] ) ; flag = 1 ; } else if ( arr [ j ] < arr [ i ] && flag == 1 ) inc [ i ] = max ( inc [ i ] , dec [ j ] + arr [ i ] ) ; } } int result = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { if ( result < inc [ i ] ) result = inc [ i ] ; if ( result < dec [ i ] ) result = dec [ i ] ; } return result ; } int main ( ) { int arr [ ] = { 8 , 2 , 3 , 5 , 7 , 9 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum ▁ sum ▁ = ▁ " << maxAlternateSum ( arr , n ) << endl ; return 0 ; }
Padovan Sequence | C ++ program to find n 'th term in Padovan Sequence using Dynamic Programming ; Function to calculate padovan number P ( n ) ; 0 th , 1 st and 2 nd number of the series are 1 ; Driver Program
#include <iostream> NEW_LINE using namespace std ; int pad ( int n ) { int pPrevPrev = 1 , pPrev = 1 , pCurr = 1 , pNext = 1 ; for ( int i = 3 ; i <= n ; i ++ ) { pNext = pPrevPrev + pPrev ; pPrevPrev = pPrev ; pPrev = pCurr ; pCurr = pNext ; } return pNext ; } int main ( ) { int n = 12 ; cout << pad ( n ) ; return 0 ; }
Find length of the largest region in Boolean Matrix | Program to find the length of the largest region in boolean 2D - matrix ; A function to check if a given cell ( row , col ) can be included in DFS ; row number is in range , column number is in range and value is 1 and not yet visited ; A utility function to do DFS for a 2D boolean matrix . It only considers the 8 neighbours as adjacent vertices ; These arrays are used to get row and column numbers of 8 neighbours of a given cell ; Mark this cell as visited ; Recur for all connected neighbours ; Increment region length by one ; The main function that returns largest length region of a given boolean 2D matrix ; Make a bool array to mark visited cells . Initially all cells are unvisited ; Initialize result as 0 and travesle through the all cells of given matrix ; If a cell with value 1 is not ; visited yet , then new region found ; maximum region ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ROW 4 NEW_LINE #define COL 5 NEW_LINE int isSafe ( int M [ ] [ COL ] , int row , int col , bool visited [ ] [ COL ] ) { return ( row >= 0 ) && ( row < ROW ) && ( col >= 0 ) && ( col < COL ) && ( M [ row ] [ col ] && ! visited [ row ] [ col ] ) ; } void DFS ( int M [ ] [ COL ] , int row , int col , bool visited [ ] [ COL ] , int & count ) { static int rowNbr [ ] = { -1 , -1 , -1 , 0 , 0 , 1 , 1 , 1 } ; static int colNbr [ ] = { -1 , 0 , 1 , -1 , 1 , -1 , 0 , 1 } ; visited [ row ] [ col ] = true ; for ( int k = 0 ; k < 8 ; ++ k ) { if ( isSafe ( M , row + rowNbr [ k ] , col + colNbr [ k ] , visited ) ) { count ++ ; DFS ( M , row + rowNbr [ k ] , col + colNbr [ k ] , visited , count ) ; } } } int largestRegion ( int M [ ] [ COL ] ) { bool visited [ ROW ] [ COL ] ; memset ( visited , 0 , sizeof ( visited ) ) ; int result = INT_MIN ; for ( int i = 0 ; i < ROW ; ++ i ) { for ( int j = 0 ; j < COL ; ++ j ) { if ( M [ i ] [ j ] && ! visited [ i ] [ j ] ) { int count = 1 ; DFS ( M , i , j , visited , count ) ; result = max ( result , count ) ; } } } return result ; } int main ( ) { int M [ ] [ COL ] = { { 0 , 0 , 1 , 1 , 0 } , { 1 , 0 , 1 , 1 , 0 } , { 0 , 1 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 1 } } ; cout << largestRegion ( M ) ; return 0 ; }
Lucas Numbers | Iterative C / C ++ program to find n 'th Lucas Number ; Iterative function ; declaring base values for positions 0 and 1 ; generating number ; Driver Code
#include <stdio.h> NEW_LINE int lucas ( int n ) { int a = 2 , b = 1 , c , i ; if ( n == 0 ) return a ; for ( i = 2 ; i <= n ; i ++ ) { c = a + b ; a = b ; b = c ; } return b ; } int main ( ) { int n = 9 ; printf ( " % d " , lucas ( n ) ) ; return 0 ; }
Recursively break a number in 3 parts to get maximum sum | A Dynamic programming based C ++ program to find maximum sum by recursively breaking a number in 3 parts . ; Function to find the maximum sum ; base conditions ; Fill in bottom - up manner using recursive formula . ; Driver program to run the case
#include <bits/stdc++.h> NEW_LINE #define MAX 1000000 NEW_LINE using namespace std ; int breakSum ( int n ) { int dp [ n + 1 ] ; dp [ 0 ] = 0 , dp [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) dp [ i ] = max ( dp [ i / 2 ] + dp [ i / 3 ] + dp [ i / 4 ] , i ) ; return dp [ n ] ; } int main ( ) { int n = 24 ; cout << breakSum ( n ) ; return 0 ; }
Longest repeating and non | C ++ program to find the longest repeated non - overlapping substring ; Returns the longest repeating non - overlapping substring in str ; building table in bottom - up manner ; ( j - i ) > LCSRe [ i - 1 ] [ j - 1 ] to remove overlapping ; updating maximum length of the substring and updating the finishing index of the suffix ; If we have non - empty result , then insert all characters from first character to last character of string ; Driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; string longestRepeatedSubstring ( string str ) { int n = str . length ( ) ; int LCSRe [ n + 1 ] [ n + 1 ] ; memset ( LCSRe , 0 , sizeof ( LCSRe ) ) ; int i , index = 0 ; for ( i = 1 ; i <= n ; i ++ ) { for ( int j = i + 1 ; j <= n ; j ++ ) { if ( str [ i - 1 ] == str [ j - 1 ] && LCSRe [ i - 1 ] [ j - 1 ] < ( j - i ) ) { LCSRe [ i ] [ j ] = LCSRe [ i - 1 ] [ j - 1 ] + 1 ; if ( LCSRe [ i ] [ j ] > res_length ) { res_length = LCSRe [ i ] [ j ] ; index = max ( i , index ) ; } } else LCSRe [ i ] [ j ] = 0 ; } } if ( res_length > 0 ) for ( i = index - res_length + 1 ; i <= index ; i ++ ) res . push_back ( str [ i - 1 ] ) ; return res ; } int main ( ) { string str = " geeksforgeeks " ; cout << longestRepeatedSubstring ( str ) ; 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 ; Returns the best obtainable price for a rod of length n and price [ ] as prices of different pieces ; Build the table val [ ] in bottom up manner and return the last entry from the table ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( int cost [ ] , int n ) { int dp [ n + 1 ] ; dp [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int min_cost = INT_MAX ; for ( int j = 0 ; j < i ; j ++ ) if ( j < n && cost [ j ] != -1 ) min_cost = min ( min_cost , cost [ j ] + dp [ i - j - 1 ] ) ; dp [ i ] = min_cost ; } return dp [ n ] ; } int main ( ) { int cost [ ] = { 20 , 10 , 4 , 50 , 100 } ; int W = sizeof ( cost ) / sizeof ( cost [ 0 ] ) ; cout << minCost ( cost , W ) ; return 0 ; }
Printing Maximum Sum Increasing Subsequence | Dynamic Programming solution to construct Maximum Sum Increasing Subsequence ; Utility function to calculate sum of all vector elements ; Function to construct Maximum Sum Increasing Subsequence ; 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 ] ; L [ i ] now stores Maximum Sum Increasing Subsequence of arr [ 0. . i ] that ends with arr [ i ] ; find max ; max will contain result ; Driver Code ; construct and print Max Sum IS of arr
#include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; int findSum ( vector < int > arr ) { int sum = 0 ; for ( int i : arr ) sum += i ; return sum ; } void printMaxSumIS ( 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 ] ) && ( findSum ( L [ i ] ) < findSum ( L [ j ] ) ) ) L [ i ] = L [ j ] ; } L [ i ] . push_back ( arr [ i ] ) ; } vector < int > res = L [ 0 ] ; for ( vector < int > x : L ) if ( findSum ( x ) > findSum ( res ) ) res = x ; for ( int i : res ) cout << i << " ▁ " ; cout << endl ; } int main ( ) { int arr [ ] = { 3 , 2 , 6 , 4 , 5 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printMaxSumIS ( arr , n ) ; return 0 ; }
Construction of Longest Increasing Subsequence ( LIS ) and printing LIS sequence | Dynamic Programming solution to construct Longest Increasing Subsequence ; Utility function to print LIS ; Function to construct and print Longest Increasing Subsequence ; L [ i ] - The longest increasing sub - sequence ends with arr [ i ] ; L [ 0 ] is equal to arr [ 0 ] ; start from index 1 ; do for every j less than i ; L [ i ] = { Max ( L [ j ] ) } + arr [ i ] where j < i and arr [ j ] < arr [ i ] ; L [ i ] ends with arr [ i ] ; L [ i ] now stores increasing sub - sequence of arr [ 0. . i ] that ends with arr [ i ] ; LIS will be max of all increasing sub - sequences of arr ; max will contain LIS ; Driver function ; construct and print LIS of arr
#include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void printLIS ( vector < int > & arr ) { for ( int x : arr ) cout << x << " ▁ " ; cout << endl ; } void constructPrintLIS ( 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 ( ) + 1 ) ) L [ i ] = L [ j ] ; } L [ i ] . push_back ( arr [ i ] ) ; } vector < int > max = L [ 0 ] ; for ( vector < int > x : L ) if ( x . size ( ) > max . size ( ) ) max = x ; printLIS ( max ) ; } int main ( ) { int arr [ ] = { 3 , 2 , 6 , 4 , 5 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; constructPrintLIS ( arr , n ) ; return 0 ; }
Find if string is K | C ++ program to find if given string is K - Palindrome or not ; 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 and Y ; find if given string is K - Palindrome or not ; Find reverse of string ; find longest palindromic subsequence of given string ; If the difference between longest palindromic subsequence and the original string is less than equal to k , then the string is k - palindrome ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lcs ( string X , string 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 ] ; } bool isKPal ( string str , int k ) { int n = str . length ( ) ; string revStr = str ; reverse ( revStr . begin ( ) , revStr . end ( ) ) ; int lps = lcs ( str , revStr , n , n ) ; return ( n - lps <= k ) ; } int main ( ) { string str = " abcdeca " ; int k = 2 ; isKPal ( str , k ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Wildcard Pattern Matching | C ++ program to implement wildcard pattern matching algorithm ; Function that matches input str with given wildcard pattern ; empty pattern can only match with empty string ; lookup table for storing results of subproblems ; initialize lookup table to false ; empty pattern can match with empty string ; Only ' * ' can match with empty string ; fill the table in bottom - up fashion ; Two cases if we see a ' * ' a ) We ignore a * aTM character and move to next character in the pattern , i . e . , a * aTM indicates an empty sequence . b ) ' * ' character matches with ith character in input ; Current characters are considered as matching in two cases ( a ) current character of pattern is ' ? ' ( b ) characters actually match ; If characters don 't match ; Driver code ; char pattern [ ] = " ba * * * * * ab " ; char pattern [ ] = " ba * ab " ; char pattern [ ] = " a * ab " ; char pattern [ ] = " a * * * * * ab " ; char pattern [ ] = " * a * * * * * ab " ; char pattern [ ] = " ba * ab * * * * " ; char pattern [ ] = " * * * * " ; char pattern [ ] = " * " ; char pattern [ ] = " aa ? ab " ; char pattern [ ] = " b * b " ; char pattern [ ] = " a * a " ; char pattern [ ] = " baaabab " ; char pattern [ ] = " ? baaabab " ; char pattern [ ] = " * baaaba * " ;
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool strmatch ( char str [ ] , char pattern [ ] , int n , int m ) { if ( m == 0 ) return ( n == 0 ) ; bool lookup [ n + 1 ] [ m + 1 ] ; memset ( lookup , false , sizeof ( lookup ) ) ; lookup [ 0 ] [ 0 ] = true ; for ( int j = 1 ; j <= m ; j ++ ) if ( pattern [ j - 1 ] == ' * ' ) lookup [ 0 ] [ j ] = lookup [ 0 ] [ j - 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { if ( pattern [ j - 1 ] == ' * ' ) lookup [ i ] [ j ] = lookup [ i ] [ j - 1 ] || lookup [ i - 1 ] [ j ] ; else if ( pattern [ j - 1 ] == ' ? ' str [ i - 1 ] == pattern [ j - 1 ] ) lookup [ i ] [ j ] = lookup [ i - 1 ] [ j - 1 ] ; else lookup [ i ] [ j ] = false ; } } return lookup [ n ] [ m ] ; } int main ( ) { char str [ ] = " baaabab " ; char pattern [ ] = " * * * * * ba * * * * * ab " ; if ( strmatch ( str , pattern , strlen ( str ) , strlen ( pattern ) ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }