text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Split a Numeric String into Fibonacci Sequence | C ++ program of the above approach ; Function that returns true if Fibonacci sequence is found ; Base condition : If pos is equal to length of S and seq length is greater than 3 ; Return true ; Stores current number ; Add current digit to num ; Avoid integer overflow ; Avoid leading zeros ; If current number is greater than last two number of seq ; If seq length is less 2 or current number is is equal to the last two of the seq ; Add to the seq ; Recur for i + 1 ; Remove last added number ; If no sequence is found ; Function that prints the Fibonacci sequence from the split of string S ; Initialize a vector to store the sequence ; Call helper function ; If sequence length is greater than 3 ; Print the sequence ; If no sequence is found ; Print - 1 ; Driver Code ; Given String ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define LL long long NEW_LINE bool splitIntoFibonacciHelper ( int pos , string S , vector < int > & seq ) { if ( pos == S . length ( ) and ( seq . size ( ) >= 3 ) ) { return true ; } LL num = 0 ; for ( int i = pos ; i < S . length ( ) ; i ++ ) { num = num * 10 + ( S [ i ] - '0' ) ; if ( num > INT_MAX ) break ; if ( S [ pos ] == '0' and i > pos ) break ; if ( seq . size ( ) > 2 and ( num > ( ( LL ) seq . back ( ) + ( LL ) seq [ seq . size ( ) - 2 ] ) ) ) break ; if ( seq . size ( ) < 2 or ( num == ( ( LL ) seq . back ( ) + ( LL ) seq [ seq . size ( ) - 2 ] ) ) ) { seq . push_back ( num ) ; if ( splitIntoFibonacciHelper ( i + 1 , S , seq ) ) return true ; seq . pop_back ( ) ; } } return false ; } void splitIntoFibonacci ( string S ) { vector < int > seq ; splitIntoFibonacciHelper ( 0 , S , seq ) ; if ( seq . size ( ) >= 3 ) { for ( int i : seq ) cout << i << " β " ; } else { cout << -1 ; } } int main ( ) { string S = "11235813" ; splitIntoFibonacci ( S ) ; return 0 ; } |
Count pair of strings whose concatenation has every vowel | C ++ program for the above approach ; Function to return the count of all concatenated string with each vowel at least once ; Creating a hash array with initial value as 0 ; Traversing through each string and getting hash value for each of them ; Initializing the weight of each string ; Find the hash value for each string ; Increasing the count of the hash value ; Getting all possible pairs of indexes in hash array ; Check if the pair which has hash value 31 and multiplying the count of string and add it strCount ; Corner case , for strings which independently has all the vowels ; Return thre final count ; Driver Code ; Given array of strings ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int good_pairs ( string str [ ] , int N ) { int arr [ 32 ] = { 0 } , strCount = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int Weight = 0 ; for ( int j = 0 ; j < str [ i ] . size ( ) ; j ++ ) { switch ( str [ i ] [ j ] ) { case ' a ' : Weight = Weight | 1 ; break ; case ' e ' : Weight = Weight | 2 ; break ; case ' i ' : Weight = Weight | 4 ; break ; case ' o ' : Weight = Weight | 8 ; break ; case ' u ' : Weight = Weight | 16 ; break ; } } arr [ Weight ] ++ ; } for ( int i = 0 ; i < 32 ; i ++ ) { for ( int j = i + 1 ; j < 32 ; j ++ ) { if ( ( i j ) == 31 ) strCount += arr [ i ] * arr [ j ] ; } } strCount += ( arr [ 31 ] * ( arr [ 31 ] - 1 ) ) / 2 ; return strCount ; } int main ( ) { string str [ ] = { " aaweiolkju " , " oxdfgujkmi " } ; int N = sizeof ( str ) / sizeof ( str [ 0 ] ) ; cout << good_pairs ( str , N ) ; return 0 ; } |
Color a grid such that all same color cells are connected either horizontally or vertically | C ++ Program to Color a grid such that all same color cells are connected either horizontally or vertically ; Current color ; final grid ; if even row ; traverse from left to right ; if color has been exhausted , move to the next color ; color the grid at this position ; reduce the color count ; traverse from right to left for odd rows ; print the grid ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( vector < int > & arr , int r , int c ) { int idx = 1 ; int dp [ r ] ; for ( int i = 0 ; i < r ; i ++ ) { if ( i % 2 == 0 ) { for ( int j = 0 ; j < c ; j ++ ) { if ( arr [ idx - 1 ] == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr [ idx - 1 ] -- ; } } else { for ( int j = c - 1 ; j >= 0 ; j -- ) { if ( arr [ idx - 1 ] == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr [ idx - 1 ] -- ; } } } for ( int i = 0 ; i < r ; ++ i ) { for ( int j = 0 ; j < c ; ++ j ) { cout << dp [ i ] [ j ] << " β " ; } cout << endl ; } } int main ( ) { int r = 3 , c = 5 ; int n = 5 ; vector < int > arr = { 1 , 2 , 3 , 4 , 5 } ; solve ( arr , r , c ) ; return 0 ; } |
Count of 0 s to be flipped to make any two adjacent 1 s at least K 0 s apart | C ++ program for the above problem ; Function to find the count of 0 s to be flipped ; Loop traversal to mark K adjacent positions to the right of already existing 1 s . ; Loop traversal to mark K adjacent positions to the left of already existing 1 s . ; Loop to count the maximum number of 0 s that will be replaced by 1 s ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int k , string s ) { int ar [ s . length ( ) ] ; int end = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == '1' ) { for ( int j = i ; j < s . length ( ) && j <= i + k ; j ++ ) { ar [ j ] = -1 ; end = j ; } i = end ; } } end = 0 ; for ( int i = s . length ( ) - 1 ; i >= 0 ; i -- ) { if ( s [ i ] == '1' ) { for ( int j = i ; j >= 0 && j >= i - k ; j -- ) { ar [ j ] = -1 ; end = j ; } i = end ; } } int ans = 0 ; end = 0 ; for ( int j = 0 ; j < s . length ( ) ; j ++ ) { if ( ar [ j ] == 0 ) { ans ++ ; for ( int g = j ; g <= j + k && g < s . length ( ) ; g ++ ) { ar [ g ] = -1 ; end = g ; } j = end - 1 ; } } return ans ; } int main ( ) { int K = 2 ; string s = "000000" ; cout << count ( K , s ) << endl ; return 0 ; } |
Length of longest connected 1 Γ’ β¬β’ s in a Binary Grid | C ++ program for the above approach ; Keeps a track of directions that is up , down , left , right ; Function to perform the dfs traversal ; Mark the current node as visited ; Increment length from this node ; Update the diameter length ; Move to next cell in x - direction ; Move to next cell in y - direction ; Check if cell is invalid then continue ; Perform DFS on new cell ; Decrement the length ; Function to find the maximum length of connected 1 s in the given grid ; Increment the id ; Traverse the grid [ ] ; Find start point of start dfs call ; DFS Traversal from cell ( x , y ) ; Print the maximum length ; Driver Code ; Given grid [ ] [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE #define row 6 NEW_LINE #define col 7 NEW_LINE using namespace std ; int vis [ row + 1 ] [ col + 1 ] , id ; int diameter = 0 , length = 0 ; int dx [ ] = { -1 , 1 , 0 , 0 } ; int dy [ ] = { 0 , 0 , -1 , 1 } ; void dfs ( int a , int b , int lis [ ] [ col ] , int & x , int & y ) { vis [ a ] [ b ] = id ; length ++ ; if ( length > diameter ) { x = a ; y = b ; diameter = length ; } for ( int j = 0 ; j < 4 ; j ++ ) { int cx = a + dx [ j ] ; int cy = b + dy [ j ] ; if ( cx < 0 cy < 0 cx > = row cy > = col lis [ cx ] [ cy ] == 0 vis [ cx ] [ cy ] ) { continue ; } dfs ( cx , cy , lis , x , y ) ; } vis [ a ] [ b ] = 0 ; length -- ; } void findMaximumLength ( int lis [ ] [ col ] ) { int x , y ; id ++ ; length = 0 ; diameter = 0 ; for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { if ( lis [ i ] [ j ] != 0 ) { dfs ( i , j , lis , x , y ) ; i = row ; break ; } } } id ++ ; length = 0 ; diameter = 0 ; dfs ( x , y , lis , x , y ) ; cout << diameter ; } int main ( ) { int grid [ ] [ col ] = { { 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 , 0 , 1 , 0 } , { 0 , 1 , 1 , 1 , 1 , 1 , 0 } , { 0 , 0 , 0 , 1 , 0 , 0 , 0 } } ; findMaximumLength ( grid ) ; return 0 ; } |
Last two digits of powers of 7 | C ++ program for the above approach ; Function to find the last two digits of 7 ^ N ; Case 4 ; Case 3 ; Case 2 ; Case 1 ; Driver Code ; Given Number ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; string get_last_two_digit ( int N ) { if ( N % 4 == 0 ) return "01" ; else if ( N % 4 == 1 ) return "07" ; else if ( N % 4 == 2 ) return "49" ; return "43" ; } int main ( ) { int N = 12 ; cout << get_last_two_digit ( N ) ; return 0 ; } |
Subsequence with maximum pairwise absolute difference and minimum size | C ++ program for the above approach ; Function to find the subsequence with maximum absolute difference ; To store the resultant subsequence ; First element should be included in the subsequence ; Traverse the given array arr [ ] ; If current element is greater than the previous element ; If the current element is not the local maxima then continue ; Else push it in subsequence ; If the current element is less then the previous element ; If the current element is not the local minima then continue ; Else push it in subsequence ; Last element should also be included in subsequence ; Print the element ; Driver Code ; Given array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void getSubsequence ( vector < int > ar ) { int N = ar . size ( ) ; vector < int > ans ; ans . push_back ( ar [ 0 ] ) ; for ( int i = 1 ; i < N - 1 ; i ++ ) { if ( ar [ i ] > ar [ i - 1 ] ) { if ( i < N - 1 && ar [ i ] <= ar [ i + 1 ] ) { continue ; } else { ans . push_back ( ar [ i ] ) ; } } else { if ( i < N - 1 && ar [ i + 1 ] < ar [ i ] ) { continue ; } else { ans . push_back ( ar [ i ] ) ; } } } ans . push_back ( ar [ N - 1 ] ) ; for ( auto & it : ans ) cout << it << ' β ' ; } int main ( ) { vector < int > arr = { 1 , 2 , 4 , 3 , 5 } ; getSubsequence ( arr ) ; } |
Maximum product of two non | C ++ program to find maximum product of two non - intersecting paths ; Returns maximum length path in subtree rooted at u after removing edge connecting u and v ; To find lengths of first and second maximum in subtrees . currMax is to store overall maximum . ; loop through all neighbors of u ; if neighbor is v , then skip it ; call recursively with current neighbor as root ; get max from one side and update ; store total length by adding max and second max ; update current max by adding 1 , i . e . current node is included ; method returns maximum product of length of two non - intersecting paths ; one by one removing all edges and calling dfs on both subtrees ; calling dfs on subtree rooted at g [ i ] [ j ] , excluding edge from g [ i ] [ j ] to i . ; calling dfs on subtree rooted at i , edge from i to g [ i ] [ j ] ; Utility function to add an undirected edge ( u , v ) ; Driver code to test above methods ; there are N edges , so + 1 for nodes and + 1 for 1 - based indexing | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dfs ( vector < int > g [ ] , int & curMax , int u , int v ) { int max1 = 0 , max2 = 0 , total = 0 ; for ( int i = 0 ; i < g [ u ] . size ( ) ; i ++ ) { if ( g [ u ] [ i ] == v ) continue ; total = max ( total , dfs ( g , curMax , g [ u ] [ i ] , u ) ) ; if ( curMax > max1 ) { max2 = max1 ; max1 = curMax ; } else max2 = max ( max2 , curMax ) ; } total = max ( total , max1 + max2 ) ; curMax = max1 + 1 ; return total ; } int maxProductOfTwoPaths ( vector < int > g [ ] , int N ) { int res = INT_MIN ; int path1 , path2 ; for ( int i = 1 ; i < N + 2 ; i ++ ) { for ( int j = 0 ; j < g [ i ] . size ( ) ; j ++ ) { int curMax = 0 ; path1 = dfs ( g , curMax , g [ i ] [ j ] , i ) ; curMax = 0 ; path2 = dfs ( g , curMax , i , g [ i ] [ j ] ) ; res = max ( res , path1 * path2 ) ; } } return res ; } void addEdge ( vector < int > g [ ] , int u , int v ) { g [ u ] . push_back ( v ) ; g [ v ] . push_back ( u ) ; } int main ( ) { int edges [ ] [ 2 ] = { { 1 , 8 } , { 2 , 6 } , { 3 , 1 } , { 5 , 3 } , { 7 , 8 } , { 8 , 4 } , { 8 , 6 } } ; int N = sizeof ( edges ) / sizeof ( edges [ 0 ] ) ; vector < int > g [ N + 2 ] ; for ( int i = 0 ; i < N ; i ++ ) addEdge ( g , edges [ i ] [ 0 ] , edges [ i ] [ 1 ] ) ; cout << maxProductOfTwoPaths ( g , N ) << endl ; return 0 ; } |
Minimum steps to reach N from 1 by multiplying each step by 2 , 3 , 4 or 5 | C ++ implementation to find minimum number of steps to reach N from 1 ; Function to find a minimum number of steps to reach N from 1 ; Check until N is greater than 1 and operations can be applied ; Condition to choose the operations greedily ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Minsteps ( int n ) { int ans = 0 ; while ( n > 1 ) { if ( n % 5 == 0 ) { ans ++ ; n = n / 5 ; continue ; } else if ( n % 4 == 0 ) { ans ++ ; n = n / 4 ; continue ; } else if ( n % 3 == 0 ) { ans ++ ; n = n / 3 ; continue ; } else if ( n % 2 == 0 ) { ans ++ ; n = n / 2 ; continue ; } return -1 ; } return ans ; } int main ( ) { int n = 10 ; cout << Minsteps ( n ) ; return 0 ; } |
Find the maximum difference after applying the given operations two times on a number | C ++ program to find the maximum difference after two given operations on a number ; Function that returns the maximum difference after two given operations on a number ; Initialize the strings to make operations ; Store length of the string ; Make the maximum number using the first operation ; Find the first digit which is not equal to '9' ; Store the digit for the given operation ; Replace all the selected ' digit ' with '9' ; Break after the operation is completed ; Check if first digit is equal to '1' ; Find the first digit which is greater than '1' ; Store the digit for the given operation ; Replace all the selected ' digit ' with '0' ; Break after the operation is completed ; Select the first digit for the given operation ; Replace all the selected ' digit ' with '1' ; Return the difference after converting into integers ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minDifference ( int num ) { string maximum = to_string ( num ) ; string minimum = to_string ( num ) ; int n = maximum . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( maximum [ i ] != '9' ) { char digit = maximum [ i ] ; for ( int j = i ; j < n ; j ++ ) { if ( maximum [ j ] == digit ) maximum [ j ] = '9' ; } break ; } } if ( minimum [ 0 ] == '1' ) { for ( int i = 1 ; i < n ; i ++ ) { if ( minimum [ i ] - '0' > 1 ) { char digit = minimum [ i ] ; for ( int j = i ; j < n ; j ++ ) { if ( digit == minimum [ j ] ) minimum [ j ] = '0' ; } break ; } } } else { char digit = minimum [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( minimum [ i ] == digit ) minimum [ i ] = '1' ; } } return ( stoi ( maximum ) - stoi ( minimum ) ) ; } int main ( ) { int N = 1101157 ; cout << minDifference ( N ) ; return 0 ; } |
Check if the square of a number is divisible by K or not | C ++ implementation to check if the square of X is divisible by K ; Function to return if square of X is divisible by K ; Finding gcd of x and k ; Dividing k by their gcd ; Check for divisibility of X by reduced K ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkDivisible ( int x , int k ) { int g = __gcd ( x , k ) ; k /= g ; if ( x % k == 0 ) { cout << " YES STRNEWLINE " ; } else { cout << " NO STRNEWLINE " ; } } int main ( ) { int x = 6 , k = 9 ; checkDivisible ( x , k ) ; return 0 ; } |
Find the minimum value of the given expression over all pairs of the array | C ++ program to find the minimum value of the given expression over all pairs of the array ; Function to find the minimum value of the expression ; The expression simplifies to finding the minimum xor value pair ; Calculate min xor of consecutive pairs ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumValue ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int minXor = INT_MAX ; int val = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { val = arr [ i ] ^ arr [ i + 1 ] ; minXor = min ( minXor , val ) ; } return minXor ; } int main ( ) { int N = 6 ; int A [ N ] = { 12 , 3 , 14 , 5 , 9 , 8 } ; cout << MinimumValue ( A , N ) ; return 0 ; } |
Find length of longest substring with at most K normal characters | C ++ implementation to Find length of longest substring with at most K normal characters ; Function to find maximum length of normal substrings ; keeps count of normal characters ; indexes of substring ; maintain length of longest substring with at most K normal characters ; get position of character ; check if current character is normal ; check if normal characters count exceeds K ; update answer with substring length ; get position of character ; check if character is normal then decrement count ; Driver code ; initialise the string | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxNormalSubstring ( string & P , string & Q , int K , int N ) { if ( K == 0 ) return 0 ; int count = 0 ; int left = 0 , right = 0 ; int ans = 0 ; while ( right < N ) { while ( right < N && count <= K ) { int pos = P [ right ] - ' a ' ; if ( Q [ pos ] == '0' ) { if ( count + 1 > K ) break ; else count ++ ; } right ++ ; if ( count <= K ) ans = max ( ans , right - left ) ; } while ( left < right ) { int pos = P [ left ] - ' a ' ; left ++ ; if ( Q [ pos ] == '0' ) count -- ; if ( count < K ) break ; } } return ans ; } int main ( ) { string P = " giraffe " , Q = "01111001111111111011111111" ; int K = 2 ; int N = P . length ( ) ; cout << maxNormalSubstring ( P , Q , K , N ) ; return 0 ; } |
Make all the elements of array even with given operations | C ++ program to make all array element even ; Function to count the total number of operations needed to make all array element even ; Traverse the given array ; If an odd element occurs then increment that element and next adjacent element by 1 ; Traverse the array if any odd element occurs then return - 1 ; Returns the count of operations ; Driver code | #include " bits / stdc + + . h " NEW_LINE using namespace std ; int countOperations ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] & 1 ) { arr [ i ] ++ ; arr [ i + 1 ] ++ ; count += 2 ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & 1 ) return -1 ; } return count ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << countOperations ( arr , n ) ; return 0 ; } |
Count of pairs with difference at most K with no element repeating | C ++ implementation to count the number of pairs whose difference is atmost K in an array ; Function to count the number of pairs whose difference is atmost K in an array ; Sorting the Array ; Variable to store the count of pairs whose difference is atmost K ; Loop to consider the consecutive pairs of the array ; if Pair found increment the index by 2 ; Driver Code ; Function Call | #include <iostream> NEW_LINE #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int k , int n ) { sort ( arr , arr + n ) ; int pair = 0 ; int index = 0 ; while ( index < n - 1 ) { if ( arr [ index + 1 ] - arr [ index ] <= k ) { pair += 1 ; index += 2 ; } else { index += 1 ; } } return pair ; } int main ( ) { int arr [ ] = { 1 , 4 , 3 , 7 , 5 } ; int k = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int count = countPairs ( arr , k , n ) ; cout << count << endl ; ; } |
Maximum profit by selling N items at two markets | C ++ implementation of the approach ; Function to calculate max profit ; Prefix sum array for profitA [ ] ; Suffix sum array for profitB [ ] ; If all the items are sold in market A ; Find the maximum profit when the first i items are sold in market A and the rest of the items are sold in market B for all possible values of i ; If all the items are sold in market B ; Driver code ; Function to calculate max profit | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProfit ( int profitA [ ] , int profitB [ ] , int n ) { int preSum [ n ] ; preSum [ 0 ] = profitA [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { preSum [ i ] = preSum [ i - 1 ] + profitA [ i ] ; } int suffSum [ n ] ; suffSum [ n - 1 ] = profitB [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) { suffSum [ i ] = suffSum [ i + 1 ] + profitB [ i ] ; } int res = preSum [ n - 1 ] ; for ( int i = 1 ; i < n - 1 ; i ++ ) { res = max ( res , preSum [ i ] + suffSum [ i + 1 ] ) ; } res = max ( res , suffSum [ 0 ] ) ; return res ; } int main ( ) { int profitA [ ] = { 2 , 3 , 2 } ; int profitB [ ] = { 10 , 30 , 40 } ; int n = sizeof ( profitA ) / sizeof ( int ) ; cout << maxProfit ( profitA , profitB , n ) ; return 0 ; } |
Find if possible to visit every nodes in given Graph exactly once based on given conditions | C ++ program for above approach . ; Function to find print path ; If a [ 0 ] is 1 ; Printing path ; Seeking for a [ i ] = 0 and a [ i + 1 ] = 1 ; Printing path ; If a [ N - 1 ] = 0 ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findpath ( int N , int a [ ] ) { if ( a [ 0 ] ) { cout << " β " << N + 1 ; for ( int i = 1 ; i <= N ; i ++ ) cout << " β " << i ; return ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( ! a [ i ] && a [ i + 1 ] ) { for ( int j = 1 ; j <= i ; j ++ ) cout << " β " << j ; cout << " β " << N + 1 ; for ( int j = i + 1 ; j <= N ; j ++ ) cout << " β " << j ; return ; } } for ( int i = 1 ; i <= N ; i ++ ) cout << " β " << i ; cout << " β " << N + 1 ; } int main ( ) { int N = 3 , arr [ ] = { 0 , 1 , 0 } ; findpath ( N , arr ) ; } |
Minimum number of edges that need to be added to form a triangle | C ++ implementation of the approach ; Function to return the minimum number of edges that need to be added to the given graph such that it contains at least one triangle ; adj is the adjacency matrix such that adj [ i ] [ j ] = 1 when there is an edge between i and j ; As the graph is undirected so there will be an edge between ( i , j ) and ( j , i ) ; To store the required count of edges ; For every possible vertex triplet ; If the vertices form a triangle ; If no edges are present ; If only 1 edge is required ; Two edges are required ; Driver code ; Number of nodes ; Storing the edges in a vector of pairs | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minEdges ( vector < pair < int , int > > v , int n ) { vector < vector < int > > adj ; adj . resize ( n + 1 ) ; for ( int i = 0 ; i < adj . size ( ) ; i ++ ) adj [ i ] . resize ( n + 1 , 0 ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { adj [ v [ i ] . first ] [ v [ i ] . second ] = 1 ; adj [ v [ i ] . second ] [ v [ i ] . first ] = 1 ; } int edgesNeeded = 3 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = i + 1 ; j <= n ; j ++ ) { for ( int k = j + 1 ; k <= n ; k ++ ) { if ( adj [ i ] [ j ] && adj [ j ] [ k ] && adj [ k ] [ i ] ) return 0 ; if ( ! ( adj [ i ] [ j ] adj [ j ] [ k ] adj [ k ] [ i ] ) ) edgesNeeded = min ( edgesNeeded , 3 ) ; else { if ( ( adj [ i ] [ j ] && adj [ j ] [ k ] ) || ( adj [ j ] [ k ] && adj [ k ] [ i ] ) || ( adj [ k ] [ i ] && adj [ i ] [ j ] ) ) { edgesNeeded = 1 ; } else edgesNeeded = min ( edgesNeeded , 2 ) ; } } } } return edgesNeeded ; } int main ( ) { int n = 3 ; vector < pair < int , int > > v = { { 1 , 2 } , { 1 , 3 } } ; cout << minEdges ( v , n ) ; return 0 ; } |
Modify a numeric string to a balanced parentheses by replacements | C ++ program for the above approach ; Function to check if the given string can be converted to a balanced bracket sequence or not ; Check if the first and last characters are equal ; Initialize two variables to store the count of open and closed brackets ; If the current character is same as the first character ; If the current character is same as the last character ; If count of open brackets becomes less than 0 ; Print the new string ; If the current character is same as the first character ; If bracket sequence is not balanced ; Check for unbalanced bracket sequence ; Print the sequence ; Driver Code ; Given Input ; Function Call | #include <iostream> NEW_LINE using namespace std ; void balBracketSequence ( string str ) { int n = str . size ( ) ; if ( str [ 0 ] == str [ n - 1 ] ) { cout << " No " << endl ; } else { int cntForOpen = 0 , cntForClose = 0 ; int check = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) cntForOpen ++ ; else if ( str [ i ] == str [ n - 1 ] ) cntForOpen -- ; else cntForOpen ++ ; if ( cntForOpen < 0 ) { check = 0 ; break ; } } if ( check && cntForOpen == 0 ) { cout << " Yes , β " ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ n - 1 ] ) cout << ' ) ' ; else cout << ' ( ' ; } return ; } else { for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) cntForClose ++ ; else cntForClose -- ; if ( cntForClose < 0 ) { check = 0 ; break ; } } if ( check && cntForClose == 0 ) { cout << " Yes , β " ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) cout << ' ( ' ; else cout << ' ) ' ; } return ; } } cout << " No " ; } } int main ( ) { string str = "123122" ; balBracketSequence ( str ) ; return 0 ; } |
Length of the longest subsequence such that xor of adjacent elements is non | C ++ implementation of the approach ; Function to find the length of the longest subsequence such that the XOR of adjacent elements in the subsequence must be non - decreasing ; Computing xor of all the pairs of elements and store them along with the pair ( i , j ) ; Sort all possible xor values ; Initialize the dp array ; Calculating the dp array for each possible position and calculating the max length that ends at a particular index ; Taking maximum of all position ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestXorSubsequence ( int arr [ ] , int n ) { vector < pair < int , pair < int , int > > > v ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { v . push_back ( make_pair ( arr [ i ] ^ arr [ j ] , make_pair ( i , j ) ) ) ; } } sort ( v . begin ( ) , v . end ( ) ) ; int dp [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { dp [ i ] = 1 ; } for ( auto i : v ) { dp [ i . second . second ] = max ( dp [ i . second . second ] , 1 + dp [ i . second . first ] ) ; } int ans = 1 ; for ( int i = 0 ; i < n ; i ++ ) ans = max ( ans , dp [ i ] ) ; return ans ; } int main ( ) { int arr [ ] = { 2 , 12 , 6 , 7 , 13 , 14 , 8 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << LongestXorSubsequence ( arr , n ) ; return 0 ; } |
Delete Edge to minimize subtree sum difference | C ++ program to minimize subtree sum difference by one edge deletion ; DFS method to traverse through edges , calculating subtree sum at each node and updating the difference between subtrees ; loop for all neighbors except parent and aggregate sum over all subtrees ; store sum in current node 's subtree index ; at one side subtree sum is ' sum ' and other side subtree sum is ' totalSum β - β sum ' so their difference will be totalSum - 2 * sum , by which we 'll update res ; Method returns minimum subtree sum difference ; Calculating total sum of tree and initializing subtree sum 's by vertex values ; filling edge data structure ; calling DFS method at node 0 , with parent as - 1 ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( int u , int parent , int totalSum , vector < int > edge [ ] , int subtree [ ] , int & res ) { int sum = subtree [ u ] ; for ( int i = 0 ; i < edge [ u ] . size ( ) ; i ++ ) { int v = edge [ u ] [ i ] ; if ( v != parent ) { dfs ( v , u , totalSum , edge , subtree , res ) ; sum += subtree [ v ] ; } } subtree [ u ] = sum ; if ( u != 0 && abs ( totalSum - 2 * sum ) < res ) res = abs ( totalSum - 2 * sum ) ; } int getMinSubtreeSumDifference ( int vertex [ ] , int edges [ ] [ 2 ] , int N ) { int totalSum = 0 ; int subtree [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { subtree [ i ] = vertex [ i ] ; totalSum += vertex [ i ] ; } vector < int > edge [ N ] ; for ( int i = 0 ; i < N - 1 ; i ++ ) { edge [ edges [ i ] [ 0 ] ] . push_back ( edges [ i ] [ 1 ] ) ; edge [ edges [ i ] [ 1 ] ] . push_back ( edges [ i ] [ 0 ] ) ; } int res = INT_MAX ; dfs ( 0 , -1 , totalSum , edge , subtree , res ) ; return res ; } int main ( ) { int vertex [ ] = { 4 , 2 , 1 , 6 , 3 , 5 , 2 } ; int edges [ ] [ 2 ] = { { 0 , 1 } , { 0 , 2 } , { 0 , 3 } , { 2 , 4 } , { 2 , 5 } , { 3 , 6 } } ; int N = sizeof ( vertex ) / sizeof ( vertex [ 0 ] ) ; cout << getMinSubtreeSumDifference ( vertex , edges , N ) ; return 0 ; } |
Minimum operations required to make every element greater than or equal to K | C ++ implementation of above approach ; C ++ function to get minimum operation needed ; The priority queue holds a minimum element in the top position ; push value one by one from the given array ; store count of minimum operation needed ; All elements are now >= k ; It is impossible to make as there are no sufficient elements available ; Take two smallest elements and replace them by their LCM first smallest element ; Second smallest element ; Increment the count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int FindMinOperation ( int a [ ] , int n , int k ) { priority_queue < int , vector < int > , greater < int > > Q ; for ( int i = 0 ; i < n ; i ++ ) Q . push ( a [ i ] ) ; int ans = 0 ; while ( 1 ) { if ( Q . top ( ) >= k ) break ; if ( Q . size ( ) < 2 ) return -1 ; int x = Q . top ( ) ; Q . pop ( ) ; int y = Q . top ( ) ; Q . pop ( ) ; int z = ( x * y ) / __gcd ( x , y ) ; Q . push ( z ) ; ans ++ ; } return ans ; } int main ( ) { int a [ ] = { 3 , 5 , 7 , 6 , 8 } ; int k = 8 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << FindMinOperation ( a , n , k ) ; } |
Check if it is possible to make two matrices strictly increasing by swapping corresponding values only | C ++ implementation of the above approach ; Function to check whether the matrices can be made strictly increasing with the given operation ; Swap only when a [ i ] [ j ] > b [ i ] [ j ] ; Check if rows are strictly increasing ; Check if columns are strictly increasing ; Driver code | using System ; using System . Collections ; class GfG { #include <bits/stdc++.h> NEW_LINE using namespace std ; string Check ( int a [ ] [ 2 ] , int b [ ] [ 2 ] , int n , int m ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) if ( a [ i ] [ j ] > b [ i ] [ j ] ) swap ( a [ i ] [ j ] , b [ i ] [ j ] ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m - 1 ; j ++ ) if ( a [ i ] [ j ] >= a [ i ] [ j + 1 ] b [ i ] [ j ] >= b [ i ] [ j + 1 ] ) return " No " ; for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) if ( a [ i ] [ j ] >= a [ i + 1 ] [ j ] b [ i ] [ j ] >= b [ i + 1 ] [ j ] ) return " No " ; return " Yes " ; } int main ( ) { int n = 2 , m = 2 ; int a [ ] [ 2 ] = { { 2 , 10 } , { 11 , 5 } } ; int b [ ] [ 2 ] = { { 9 , 4 } , { 3 , 12 } } ; cout << ( Check ( a , b , n , m ) ) ; } |
Find the lexicographically smallest string which satisfies the given condition | C ++ implementation of the approach ; Function to return the required string ; First character will always be ' a ' ; To store the resultant string ; Since length of the string should be greater than 0 and first element of array should be 1 ; Check one by one all element of given prefix array ; If the difference between any two consecutive elements of the prefix array is greater than 1 then there will be no such string possible that satisfies the given array Also , string cannot have more than 26 distinct characters ; If difference is 0 then the ( i + 1 ) th character will be same as the ith character ; If difference is 1 then the ( i + 1 ) th character will be different from the ith character ; Return the resultant string ; Driver code | #include <iostream> NEW_LINE using namespace std ; string smallestString ( int N , int A [ ] ) { char ch = ' a ' ; string S = " " ; if ( N < 1 A [ 0 ] != 1 ) { S = " - 1" ; return S ; } S += ch ; ch ++ ; for ( int i = 1 ; i < N ; i ++ ) { int diff = A [ i ] - A [ i - 1 ] ; if ( diff > 1 diff < 0 A [ i ] > 26 ) { S = " - 1" ; return S ; } else if ( diff == 0 ) S += ' a ' ; else { S += ch ; ch ++ ; } } return S ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << smallestString ( n , arr ) ; return 0 ; } |
Count of alphabets whose ASCII values can be formed with the digits of N | C ++ implementation of the approach ; Function that returns true if num can be formed with the digits in digits [ ] array ; Copy of the digits array ; Get last digit ; If digit array doesn 't contain current digit ; One occurrence is used ; Remove the last digit ; Function to return the count of required alphabets ; To store the occurrences of digits ( 0 - 9 ) ; Get last digit ; Update the occurrence of the digit ; Remove the last digit ; If any lowercase character can be picked from the current digits ; If any uppercase character can be picked from the current digits ; Return the required count of alphabets ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canBePicked ( int digits [ ] , int num ) { int copyDigits [ 10 ] ; for ( int i = 0 ; i < 10 ; i ++ ) copyDigits [ i ] = digits [ i ] ; while ( num > 0 ) { int digit = num % 10 ; if ( copyDigits [ digit ] == 0 ) return false ; else copyDigits [ digit ] -= 1 ; num = floor ( num / 10 ) ; } return true ; } int countAlphabets ( long n ) { int count = 0 ; int digits [ 10 ] = { 0 } ; while ( n > 0 ) { int digit = n % 10 ; digits [ digit ] += 1 ; n = floor ( n / 10 ) ; } for ( int i = 97 ; i <= 122 ; i ++ ) if ( canBePicked ( digits , i ) ) count += 1 ; for ( int i = 65 ; i < 91 ; i ++ ) if ( canBePicked ( digits , i ) ) count += 1 ; return count ; } int main ( ) { long n = 1623455078 ; cout << ( countAlphabets ( n ) ) ; } |
Largest number less than X having at most K set bits | C ++ implementation of the approach ; Function to return the greatest number <= X having at most K set bits . ; Remove rightmost set bits one by one until we count becomes k ; Return the required number ; Driver code | #include <iostream> NEW_LINE using namespace std ; int greatestKBits ( int X , int K ) { int set_bit_count = __builtin_popcount ( X ) ; if ( set_bit_count <= K ) return X ; int diff = set_bit_count - K ; for ( int i = 0 ; i < diff ; i ++ ) X &= ( X - 1 ) ; return X ; } int main ( ) { int X = 21 , K = 2 ; cout << greatestKBits ( X , K ) ; return 0 ; } |
Find the minimum number of moves needed to move from one cell of matrix to another | C ++ program to find the minimum numbers of moves needed to move from source to destination . ; add edge to graph ; Level BFS function to find minimum path from source to sink ; Base case ; make initial distance of all vertex - 1 from source ; Create a queue for BFS ; Mark the source node level [ s ] = '0' ; it will be used to get all adjacent vertices of a vertex ; Dequeue a vertex from queue ; Get all adjacent vertices of the dequeued vertex s . If a adjacent has not been visited ( level [ i ] < '0' ) , then update level [ i ] = = parent_level [ s ] + 1 and enqueue it ; Else , continue to do BFS ; return minimum moves from source to sink ; Returns minimum numbers of moves from a source ( acell with value 1 ) to a destination ( a cell withvalue 2 ) ; ; create graph with n * n node each cell consider as node Number of current vertex ; connect all 4 adjacent cell to current cell ; source index ; destination index ; find minimum moves ; driver program to check above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE class Graph { int V ; list < int > * adj ; public : Graph ( int V ) { this -> V = V ; adj = new list < int > [ V ] ; } void addEdge ( int s , int d ) ; int BFS ( int s , int d ) ; } ; void Graph :: addEdge ( int s , int d ) { adj [ s ] . push_back ( d ) ; adj [ d ] . push_back ( s ) ; } int Graph :: BFS ( int s , int d ) { if ( s == d ) return 0 ; int * level = new int [ V ] ; for ( int i = 0 ; i < V ; i ++ ) level [ i ] = -1 ; list < int > queue ; level [ s ] = 0 ; queue . push_back ( s ) ; list < int > :: iterator i ; while ( ! queue . empty ( ) ) { s = queue . front ( ) ; queue . pop_front ( ) ; for ( i = adj [ s ] . begin ( ) ; i != adj [ s ] . end ( ) ; ++ i ) { if ( level [ * i ] < 0 level [ * i ] > level [ s ] + 1 ) { level [ * i ] = level [ s ] + 1 ; queue . push_back ( * i ) ; } } } return level [ d ] ; } bool isSafe ( int i , int j , int M [ ] [ N ] ) { if ( ( i < 0 i > = N ) || ( j < 0 j > = N ) M [ i ] [ j ] == 0 ) return false ; return true ; } int MinimumPath ( int M [ ] [ N ] ) { int s , d ; int V = N * N + 2 ; Graph g ( V ) ; int k = 1 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( M [ i ] [ j ] != 0 ) { if ( isSafe ( i , j + 1 , M ) ) g . addEdge ( k , k + 1 ) ; if ( isSafe ( i , j - 1 , M ) ) g . addEdge ( k , k - 1 ) ; if ( j < N - 1 && isSafe ( i + 1 , j , M ) ) g . addEdge ( k , k + N ) ; if ( i > 0 && isSafe ( i - 1 , j , M ) ) g . addEdge ( k , k - N ) ; } if ( M [ i ] [ j ] == 1 ) s = k ; if ( M [ i ] [ j ] == 2 ) d = k ; k ++ ; } } return g . BFS ( s , d ) ; } int main ( ) { int M [ N ] [ N ] = { { 3 , 3 , 1 , 0 } , { 3 , 0 , 3 , 3 } , { 2 , 3 , 0 , 3 } , { 0 , 3 , 3 , 3 } } ; cout << MinimumPath ( M ) << endl ; return 0 ; } |
Find two numbers whose sum and GCD are given | C ++ program to find two numbers whose sum and GCD is given ; Function to find two numbers whose sum and gcd is given ; sum != gcd checks that both the numbers are positive or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findTwoNumbers ( int sum , int gcd ) { if ( __gcd ( gcd , sum - gcd ) == gcd && sum != gcd ) cout << " a β = β " << min ( gcd , sum - gcd ) << " , β b β = β " << sum - min ( gcd , sum - gcd ) << endl ; else cout << -1 << endl ; } int main ( ) { int sum = 8 ; int gcd = 2 ; findTwoNumbers ( sum , gcd ) ; return 0 ; } |
Find maximum distance between any city and station | C ++ program to calculate the maximum distance between any city and its nearest station ; Function to calculate the maximum distance between any city and its nearest station ; Initialize boolean list ; Assign True to cities containing station ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxDistance ( int numOfCities , int station [ ] , int n ) { bool hasStation [ numOfCities + 1 ] = { false } ; for ( int city = 0 ; city < n ; city ++ ) { hasStation [ station [ city ] ] = true ; } int dist = 0 ; int maxDist = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { maxDist = min ( station [ i ] , maxDist ) ; } for ( int city = 0 ; city < numOfCities ; city ++ ) { if ( hasStation [ city ] == true ) { maxDist = max ( ( dist + 1 ) / 2 , maxDist ) ; dist = 0 ; } else dist += 1 ; } return max ( maxDist , dist ) ; } int main ( ) { int numOfCities = 6 ; int station [ ] = { 3 , 1 } ; int n = sizeof ( station ) / sizeof ( station [ 0 ] ) ; cout << " Max β Distance : " << findMaxDistance ( numOfCities , station , n ) ; } |
Split the number into N parts such that difference between the smallest and the largest part is minimum | CPP implementation of the approach ; Function that prints the required sequence ; If we cannot split the number into exactly ' N ' parts ; If x % n == 0 then the minimum difference is 0 and all numbers are x / n ; upto n - ( x % n ) the values will be x / n after that the values will be x / n + 1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; ; void split ( int x , int n ) { if ( x < n ) cout << " - 1" << " β " ; else if ( x % n == 0 ) { for ( int i = 0 ; i < n ; i ++ ) cout << ( x / n ) << " β " ; } else { int zp = n - ( x % n ) ; int pp = x / n ; for ( int i = 0 ; i < n ; i ++ ) { if ( i >= zp ) cout << ( pp + 1 ) << " β " ; else cout << pp << " β " ; } } } int main ( ) { int x = 5 ; int n = 3 ; split ( x , n ) ; } |
Minimum time to reach a point with + t and | C ++ implementation of the above approach ; returns the minimum time required to reach ' X ' ; Stores the minimum time ; increment ' t ' by 1 ; update the sum ; Driver code | #include <iostream> NEW_LINE using namespace std ; long cal_minimum_time ( long X ) { long t = 0 ; long sum = 0 ; while ( sum < X ) { t ++ ; sum = sum + t ; } return t ; } int main ( ) { long n = 6 ; long ans = cal_minimum_time ( n ) ; cout << " The β minimum β time β required β is β : β " << ans ; return 0 ; } |
Check if a string can be rearranged to form special palindrome | C ++ implementation of the above approach ; Driver code ; creating a array which stores the frequency of each character ; Checking if a character is uppercase or not ; Increasing by 1 if uppercase ; Decreasing by 1 if lower case ; Storing the sum of positive numbers in the frequency array ; Storing the sum of negative numbers in the frequency array ; If all character balances out then its Yes ; If there is only 1 character which does not balances then also it is Yes | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { string s = " ABCdcba " ; int u [ 26 ] = { 0 } ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( isupper ( s [ i ] ) ) { u [ s [ i ] - 65 ] += 1 ; } else { u [ s [ i ] - 97 ] -= 1 ; } } bool f1 = true ; int po = 0 ; int ne = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( u [ i ] > 0 ) po += u [ i ] ; if ( u [ i ] < 0 ) ne += u [ i ] ; } if ( po == 0 && ne == 0 ) cout << ( " YES " ) << endl ; else if ( po == 1 && ne == 0 ) cout << ( " YES " ) << endl ; else if ( po == 0 && ne == -1 ) cout << ( " YES " ) << endl ; else cout << ( " NO " ) << endl ; } |
Modify the string such that it contains all vowels at least once | C ++ 14 implementation of the above approach ; All vowels ; List to store distinct vowels ; if length of string is less than 5 then always Impossible ; Storing the distinct vowels in the string by checking if it in the list of string and not in the list of distinct vowels ; Storing the vowels which are not present in the string ; No replacement needed condition ; Replacing the characters to get all Vowels ; copy th rest of the string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void addAllVowel ( string str ) { char x [ ] = { ' A ' , ' E ' , ' I ' , ' O ' , ' U ' } ; vector < char > y ; int length = str . length ( ) ; if ( length < 5 ) cout << " Impossible " << endl ; else { for ( int i = 0 ; i < length ; i ++ ) { if ( find ( x , x + 5 , str [ i ] ) != x + 5 and find ( y . begin ( ) , y . end ( ) , str [ i ] ) == y . end ( ) ) y . push_back ( str [ i ] ) ; } vector < char > z ; for ( int i = 0 ; i < 5 ; i ++ ) if ( find ( y . begin ( ) , y . end ( ) , x [ i ] ) == y . end ( ) ) z . push_back ( x [ i ] ) ; if ( z . empty ( ) ) cout << str << endl ; else { int cc = 0 ; vector < char > y ; for ( int i = 0 ; i < length ; i ++ ) { if ( find ( x , x + 5 , str [ i ] ) != x + 5 and find ( y . begin ( ) , y . end ( ) , str [ i ] ) == y . end ( ) ) y . push_back ( str [ i ] ) ; else { str [ i ] = z [ cc ] ; cc ++ ; } if ( cc == z . size ( ) ) break ; } cout << str << endl ; } } } int main ( int argc , char const * argv [ ] ) { string str = " ABCDEFGHI " ; addAllVowel ( str ) ; return 0 ; } |
Minimum number of days required to complete the work | C ++ program to find the minimum number days required ; Function to find the minimum number days required ; initialising ans to least value possible ; sort by first i . e D ( i ) ; Calculate the minimum possible days ; return the answer ; Driver Code ; Number of works ; D1 [ i ] ; D2 [ i ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define inf INT_MAX NEW_LINE int minimumDays ( int N , int D1 [ ] , int D2 [ ] ) { int ans = - inf ; vector < pair < int , int > > vect ; for ( int i = 0 ; i < N ; i ++ ) vect . push_back ( make_pair ( D1 [ i ] , D2 [ i ] ) ) ; sort ( vect . begin ( ) , vect . end ( ) ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( vect [ i ] . second >= ans ) ans = vect [ i ] . second ; else ans = vect [ i ] . first ; } return ans ; } int main ( ) { int N = 3 ; int D1 [ ] = { 6 , 5 , 4 } ; int D2 [ ] = { 1 , 2 , 3 } ; cout << minimumDays ( N , D1 , D2 ) ; return 0 ; } |
Count substrings made up of a single distinct character | C ++ program for the above approach ; Function to count the number of substrings made up of a single distinct character ; Stores the required count ; Stores the count of substrings possible by using current character ; Stores the previous character ; Traverse the string ; If current character is same as the previous character ; Increase count of substrings possible with current character ; Reset count of substrings possible with current character ; Update count of substrings ; Update previous character ; Driver code | #include <iostream> NEW_LINE using namespace std ; void countSubstrings ( string s ) { int ans = 0 ; int subs = 1 ; char pre = '0' ; for ( auto & i : s ) { if ( pre == i ) { subs += 1 ; } else { subs = 1 ; } ans += subs ; pre = i ; } cout << ans << endl ; } int main ( ) { string s = " geeksforgeeks " ; countSubstrings ( s ) ; return 0 ; } |
Sum of minimum difference between consecutive elements of an array | C ++ program for finding the minimum sum of difference between consecutive elements ; function to find minimum sum of difference of consecutive element ; ul to store upper limit ll to store lower limit ; storethe lower range in ll and upper range in ul ; initialize the answer with 0 ; iterate for all ranges ; case 1 , in this case the difference will be 0 ; change upper limit and lower limit ; case 2 ; store the difference ; case 3 ; store the difference ; Driver code ; array of range | #include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( pair < int , int > v [ ] , int n ) { int ans , ul , ll ; ll = v [ 0 ] . first ; ul = v [ 0 ] . second ; ans = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( ( v [ i ] . first <= ul && v [ i ] . first >= ll ) || ( v [ i ] . second >= ll && v [ i ] . second <= ul ) ) { if ( v [ i ] . first > ll ) { ll = v [ i ] . first ; } if ( v [ i ] . second < ul ) { ul = v [ i ] . second ; } } else if ( v [ i ] . first > ul ) { ans += abs ( ul - v [ i ] . first ) ; ul = v [ i ] . first ; ll = v [ i ] . first ; } else if ( v [ i ] . second < ll ) { ans += abs ( ll - v [ i ] . second ) ; ul = v [ i ] . second ; ll = v [ i ] . second ; } } return ans ; } int main ( ) { pair < int , int > v [ ] = { { 1 , 3 } , { 2 , 5 } , { 6 , 8 } , { 1 , 2 } , { 2 , 3 } } ; int n = sizeof ( v ) / sizeof ( v [ 0 ] ) ; cout << solve ( v , n ) << endl ; return 0 ; } |
Find the Largest Cube formed by Deleting minimum Digits from a number | C ++ code to implement maximum perfect cube formed after deleting minimum digits ; Returns vector of Pre Processed perfect cubes ; convert the cube to string and push into preProcessedCubes vector ; Utility function for findLargestCube ( ) . Returns the Largest cube number that can be formed ; reverse the preProcessed cubes so that we have the largest cube in the beginning of the vector ; iterate over all cubes ; check if the current digit of the cube matches with that of the number num ; if control reaches here , the its not possible to form a perfect cube ; wrapper for findLargestCubeUtil ( ) ; pre process perfect cubes ; convert number n to string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > preProcess ( long long int n ) { vector < string > preProcessedCubes ; for ( int i = 1 ; i * i * i <= n ; i ++ ) { long long int iThCube = i * i * i ; string cubeString = to_string ( iThCube ) ; preProcessedCubes . push_back ( cubeString ) ; } return preProcessedCubes ; } string findLargestCubeUtil ( string num , vector < string > preProcessedCubes ) { reverse ( preProcessedCubes . begin ( ) , preProcessedCubes . end ( ) ) ; int totalCubes = preProcessedCubes . size ( ) ; for ( int i = 0 ; i < totalCubes ; i ++ ) { string currCube = preProcessedCubes [ i ] ; int digitsInCube = currCube . length ( ) ; int index = 0 ; int digitsInNumber = num . length ( ) ; for ( int j = 0 ; j < digitsInNumber ; j ++ ) { if ( num [ j ] == currCube [ index ] ) index ++ ; if ( digitsInCube == index ) return currCube ; } } return " Not β Possible " ; } void findLargestCube ( long long int n ) { vector < string > preProcessedCubes = preProcess ( n ) ; string num = to_string ( n ) ; string ans = findLargestCubeUtil ( num , preProcessedCubes ) ; cout << " Largest β Cube β that β can β be β formed β from β " << n << " β is β " << ans << endl ; } int main ( ) { long long int n ; n = 4125 ; findLargestCube ( n ) ; n = 876 ; findLargestCube ( n ) ; return 0 ; } |
Water Connection Problem | C ++ program to find efficient solution for the network ; number of houses and number of pipes ; Array rd stores the ending vertex of pipe ; Array wd stores the value of diameters between two pipes ; Array cd stores the starting end of pipe ; Vector a , b , c are used to store the final output ; Function performing calculations . ; If a pipe has no ending vertex but has starting vertex i . e is an outgoing pipe then we need to start DFS with this vertex . ; We put the details of component in final output array ; main function ; set the value of the araray to zero | #include <bits/stdc++.h> NEW_LINE using namespace std ; int n , p ; int rd [ 1100 ] ; int wt [ 1100 ] ; int cd [ 1100 ] ; vector < int > a ; vector < int > b ; vector < int > c ; int ans ; int dfs ( int w ) { if ( cd [ w ] == 0 ) return w ; if ( wt [ w ] < ans ) ans = wt [ w ] ; return dfs ( cd [ w ] ) ; } void solve ( int arr [ ] [ 3 ] ) { int i = 0 ; while ( i < p ) { int q = arr [ i ] [ 0 ] , h = arr [ i ] [ 1 ] , t = arr [ i ] [ 2 ] ; cd [ q ] = h ; wt [ q ] = t ; rd [ h ] = q ; i ++ ; } a . clear ( ) ; b . clear ( ) ; c . clear ( ) ; for ( int j = 1 ; j <= n ; ++ j ) if ( rd [ j ] == 0 && cd [ j ] ) { ans = 1000000000 ; int w = dfs ( j ) ; a . push_back ( j ) ; b . push_back ( w ) ; c . push_back ( ans ) ; } cout << a . size ( ) << endl ; for ( int j = 0 ; j < a . size ( ) ; ++ j ) cout << a [ j ] << " β " << b [ j ] << " β " << c [ j ] << endl ; } int main ( ) { n = 9 , p = 6 ; memset ( rd , 0 , sizeof ( rd ) ) ; memset ( cd , 0 , sizeof ( cd ) ) ; memset ( wt , 0 , sizeof ( wt ) ) ; int arr [ ] [ 3 ] = { { 7 , 4 , 98 } , { 5 , 9 , 72 } , { 4 , 6 , 10 } , { 2 , 8 , 22 } , { 9 , 7 , 17 } , { 3 , 1 , 66 } } ; solve ( arr ) ; return 0 ; } |
Print a closest string that does not contain adjacent duplicates | C ++ program to print a string with no adjacent duplicates by doing minimum changes to original string ; Function to print simple string ; If any two adjacent characters are equal ; Initialize it to ' a ' ; Traverse the loop until it is different from the left and right letter . ; Driver Function | #include <bits/stdc++.h> NEW_LINE using namespace std ; string noAdjacentDup ( string s ) { int n = s . length ( ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] ) { s [ i ] = ' a ' ; while ( s [ i ] == s [ i - 1 ] || ( i + 1 < n && s [ i ] == s [ i + 1 ] ) ) s [ i ] ++ ; i ++ ; } } return s ; } int main ( ) { string s = " geeksforgeeks " ; cout << noAdjacentDup ( s ) ; return 0 ; } |
Array element moved by k using single moves | C ++ program to find winner of game ; if the number of steps is more then n - 1 , ; initially the best is 0 and no of wins is 0. ; traverse through all the numbers ; if the value of array is more then that of previous best ; best is replaced by a [ i ] ; if not the first index ; times = 1 ; no of wins is 1 now ; if any position has more then k wins then return ; Maximum element will be winner because we move smaller element at end and repeat the process . ; driver program to test the above function | #include <iostream> NEW_LINE using namespace std ; int winner ( int a [ ] , int n , int k ) { if ( k >= n - 1 ) return n ; int best = 0 , times = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > best ) { best = a [ i ] ; if ( i ) } else if ( times >= k ) return best ; } return best ; } int main ( ) { int a [ ] = { 2 , 1 , 3 , 4 , 5 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 2 ; cout << winner ( a , n , k ) ; return 0 ; } |
Paper Cut into Minimum Number of Squares | C ++ program to find minimum number of squares to cut a paper . ; Returns min number of squares needed ; swap if a is small size side . ; Iterate until small size side is greater then 0 ; Update result ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumSquare ( int a , int b ) { long long result = 0 , rem = 0 ; if ( a < b ) swap ( a , b ) ; while ( b > 0 ) { result += a / b ; long long rem = a % b ; a = b ; b = rem ; } return result ; } int main ( ) { int n = 13 , m = 29 ; cout << minimumSquare ( n , m ) ; return 0 ; } |
Maximize array sum after K negations | Set 2 | A PriorityQueue based C ++ program to maximize array sum after k negations . ; Function to find Maximum sum after K negations ; Create a min heap for priority queue ; Insert all elements in f array in priority_queue ; Retrieve and remove min element ; Modify the minimum element and add back to priority queue ; Calculate the sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxSum ( int a [ ] , int n , int k ) { int sum = 0 ; priority_queue < int , vector < int > , greater < int > > pq ; for ( int i = 0 ; i < n ; i ++ ) { pq . push ( a [ i ] ) ; } while ( k -- ) { int temp = pq . top ( ) ; pq . pop ( ) ; temp = ( temp ) * -1 ; pq . push ( temp ) ; } while ( ! pq . empty ( ) ) { sum = sum + pq . top ( ) ; pq . pop ( ) ; } return sum ; } int main ( ) { int a [ ] = { -2 , 0 , 5 , -1 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 4 ; cout << MaxSum ( a , n , k ) ; return 0 ; } |
Count of non decreasing Arrays with ith element in range [ A [ i ] , B [ i ] ] | C ++ program for the above approach ; Function to count the total number of possible valid arrays ; Make a 2D DP table ; Make a 2D prefix sum table ; Initialize all values to 0 ; Base Case ; Initialize the prefix values ; Iterate over the range and update the dp table accordingly ; Add the dp values to the prefix sum ; Update the prefix sum table ; Find the result count of arrays formed ; Return the total count of arrays ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int totalValidArrays ( int a [ ] , int b [ ] , int N ) { int dp [ N + 1 ] [ b [ N - 1 ] + 1 ] ; int pref [ N + 1 ] [ b [ N - 1 ] + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) , memset ( pref , 0 , sizeof ( pref ) ) ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i <= b [ N - 1 ] ; i ++ ) { pref [ 0 ] [ i ] = 1 ; } for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = a [ i - 1 ] ; j <= b [ i - 1 ] ; j ++ ) { dp [ i ] [ j ] += pref [ i - 1 ] [ j ] ; pref [ i ] [ j ] += dp [ i ] [ j ] ; } for ( int j = 0 ; j <= b [ N - 1 ] ; j ++ ) { if ( j > 0 ) { pref [ i ] [ j ] += pref [ i ] [ j - 1 ] ; } } } int ans = 0 ; for ( int i = a [ N - 1 ] ; i <= b [ N - 1 ] ; i ++ ) { ans += dp [ N ] [ i ] ; } return ans ; } int main ( ) { int A [ ] = { 1 , 1 } ; int B [ ] = { 2 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << totalValidArrays ( A , B , N ) ; return 0 ; } |
Query to find length of the longest subarray consisting only of 1 s | C ++ Program for the above approach ; Function to calculate the longest subarray consisting of 1 s only ; Stores the maximum length of subarray containing 1 s only ; Traverse the array ; If current element is '1' ; Increment length ; Otherwise ; Reset length ; Update maximum subarray length ; Function to perform given queries ; Stores count of queries ; Traverse each query ; Flip the character ; Driver Code ; Size of array ; Given array ; Given queries ; Number of queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; int longestsubarray ( int a [ ] , int N ) { int maxlength = 0 , sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( a [ i ] == 1 ) { sum ++ ; } else { sum = 0 ; } maxlength = max ( maxlength , sum ) ; } return maxlength ; } void solveQueries ( int arr [ ] , int n , vector < vector < int > > Q , int k ) { int cntQuery = Q . size ( ) ; for ( int i = 0 ; i < cntQuery ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) { cout << longestsubarray ( arr , n ) << " β " ; } else { arr [ Q [ i ] [ 1 ] - 1 ] ^= 1 ; } } } int main ( ) { int N = 10 ; int arr [ ] = { 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; vector < vector < int > > Q = { { 1 } , { 2 , 3 } , { 1 } } ; int K = 3 ; solveQueries ( arr , N , Q , K ) ; } |
Count of integers in range [ L , R ] having even frequency of each digit | C ++ program for the above approach ; Stores the upper limit of the range ; Stores the overlapping states ; Recursive Function to calculate the count of valid integers in the range [ 1 , s ] using memoization ; Base Case ; If current integer has even count of digits and is not repeated ; If current state is already considered ; Stores the maximum valid digit at the current index ; Stores the count of valid integers ; If the current digit is not the most significant digit , i . e , the integer is already started ; Iterate through all valid digits ; Recursive call for ith digit at the current index ; Recursive call for integers having leading zeroes in the beginning ; Iterate through all valid digits as most significant digits ; Recursive call for ith digit at the current index ; Return answer ; Function to calculate valid number in the range [ 1 , X ] ; Initialize dp array with - 1 ; Store the range in form of string ; Return Count ; Function to find the count of integers in the range [ L , R ] such that the frequency of each digit is even ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string s ; int dp [ 1024 ] [ 10 ] [ 2 ] [ 2 ] ; int calcCnt ( int mask , int len , int smaller , int started ) { if ( len == s . size ( ) ) { return ( mask == 0 && started ) ; } if ( dp [ mask ] [ len ] [ smaller ] [ started ] != -1 ) return dp [ mask ] [ len ] [ smaller ] [ started ] ; int mx = 9 ; if ( ! smaller ) { mx = s [ len ] - '0' ; } int ans = 0 ; if ( started ) { for ( int i = 0 ; i <= mx ; i ++ ) { ans += calcCnt ( mask ^ ( 1 << i ) , len + 1 , smaller || ( i < s [ len ] - '0' ) , 1 ) ; } } else { ans = calcCnt ( mask , len + 1 , 1 , 0 ) ; for ( int i = 1 ; i <= mx ; i ++ ) { ans += calcCnt ( mask ^ ( 1 << i ) , len + 1 , smaller || ( i < s [ len ] - '0' ) , 1 ) ; } } return dp [ mask ] [ len ] [ smaller ] [ started ] = ans ; } int countInt ( int x ) { memset ( dp , -1 , sizeof ( dp ) ) ; s = to_string ( x ) ; return calcCnt ( 0 , 0 , 0 , 0 ) ; } int countIntInRange ( int L , int R ) { return countInt ( R ) - countInt ( L - 1 ) ; } int main ( ) { int L = 32 , R = 1010 ; cout << countIntInRange ( L , R ) ; return 0 ; } |
Minimize cost of swapping set bits with unset bits in a given Binary string | C ++ program for the above approach ; Function to find the minimum cost required to swap every set bit with an unset bit ; Stores the indices of set and unset bits of the string S ; Traverse the string S ; Store the indices ; Initialize a dp table of size n1 * n2 ; Set unreachable states to INF ; Fill the dp Table according to the given recurrence relation ; Update the value of dp [ i ] [ j ] ; Return the minimum cost ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define INF 1000000000 NEW_LINE int minimumCost ( string s ) { int N = s . length ( ) ; vector < int > A , B ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '1' ) { A . push_back ( i ) ; } else { B . push_back ( i ) ; } } int n1 = A . size ( ) ; int n2 = B . size ( ) ; int dp [ n1 + 1 ] [ n2 + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 1 ; i <= n1 ; i ++ ) { dp [ i ] [ 0 ] = INF ; } for ( int i = 1 ; i <= n1 ; i ++ ) { for ( int j = 1 ; j <= n2 ; j ++ ) { dp [ i ] [ j ] = min ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j - 1 ] + abs ( A [ i - 1 ] - B [ j - 1 ] ) ) ; } } return dp [ n1 ] [ n2 ] ; } int main ( ) { string S = "1010001" ; cout << minimumCost ( S ) ; return 0 ; } |
Queries to find minimum absolute difference between adjacent array elements in given ranges | C ++ program for the above approach ; Structure for query range ; Function to find the minimum difference between adjacent array element over the given range [ L , R ] for Q Queries ; Find the sum of all queries ; Left and right boundaries of current range ; Print the sum of the current query range ; Function to find the minimum absolute difference of adjacent array elements for the given range ; Stores the absolute difference of adjacent elements ; Find the minimum difference of adjacent elements ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Query { int L , R ; } ; int MAX = 5000 ; void minDifference ( int arr [ ] , int n , Query q [ ] , int m ) { for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] . L , R = q [ i ] . R ; int ans = MAX ; for ( int i = L ; i < R ; i ++ ) { ans = min ( ans , arr [ i ] ) ; } cout << ans << ' ' ; } } void minimumDifference ( int arr [ ] , Query q [ ] , int N , int m ) { int diff [ N ] ; for ( int i = 0 ; i < N - 1 ; i ++ ) diff [ i ] = abs ( arr [ i ] - arr [ i + 1 ] ) ; minDifference ( diff , N - 1 , q , m ) ; } int main ( ) { int arr [ ] = { 2 , 6 , 1 , 8 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Query Q [ ] = { { 0 , 3 } , { 1 , 5 } , { 4 , 5 } } ; int M = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; minimumDifference ( arr , Q , N , M ) ; return 0 ; } |
Count of N digit numbers which contains all single digit primes | C ++ program for the above approach ; Function ; If index = N + 1 ; Find count of distinct prime numbers by counting number of set bits . ; If count of distinct prime numbers is equal to 4 return 1. ; If the state has already been computed ; If current position is 1 , then any digit from [ 1 - 9 ] can be placed . If N = 1 , 0 can be also placed . ; If the digit is a prime number , set the index of the digit to 1 in the bitmask . ; For remaining positions , any digit from [ 0 - 9 ] can be placed ; If the digit is a prime number , set the index of the digit to 1 in the bitmask . ; Return the answer . ; Driver Code ; Initializing dp array with - 1. ; Indexing prime numbers in ascending order ; Given Input ; Function call . | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100 ] [ 1 << 4 ] ; map < int , int > primeIndex ; int countOfNumbers ( int index , int mask , int N ) { if ( index == N + 1 ) { int countOfPrimes = __builtin_popcount ( mask ) ; if ( countOfPrimes == 4 ) { return 1 ; } return 0 ; } int & val = dp [ index ] [ mask ] ; if ( val != -1 ) { return val ; } val = 0 ; if ( index == 1 ) { for ( int digit = ( N == 1 ? 0 : 1 ) ; digit <= 9 ; ++ digit ) { if ( primeIndex . find ( digit ) != primeIndex . end ( ) ) { val += countOfNumbers ( index + 1 , mask | ( 1 << primeIndex [ digit ] ) , N ) ; } else { val += countOfNumbers ( index + 1 , mask , N ) ; } } } else { for ( int digit = 0 ; digit <= 9 ; ++ digit ) { if ( primeIndex . find ( digit ) != primeIndex . end ( ) ) { val += countOfNumbers ( index + 1 , mask | ( 1 << primeIndex [ digit ] ) , N ) ; } else { val += countOfNumbers ( index + 1 , mask , N ) ; } } } return val ; } int main ( ) { memset ( dp , -1 , sizeof dp ) ; primeIndex [ 2 ] = 0 ; primeIndex [ 3 ] = 1 ; primeIndex [ 5 ] = 2 ; primeIndex [ 7 ] = 3 ; int N = 4 ; cout << countOfNumbers ( 1 , 0 , N ) ; return 0 ; } |
Count of N | C ++ program for the above approach ; Stores the dp - states ; Recursive Function to find number of N - digit numbers which has equal count of distinct odd & even digits ; If index is N + 1 ; Find the count of set bits in the evenMask ; Find the count of set bits in the oddMask ; If the count of set bits in both masks are equal then return 1 as they have equal number of distinct odd and even digits ; If the state has already been computed ; If N = 1 , 0 can be also placed ; If digit is odd ; Set the ( digit / 2 ) th bit of the oddMask ; Set the ( digit / 2 ) th bit of the number evenMask ; For remaining positions , any digit from [ 0 - 9 ] can be placed ; If digit is odd ; Set the ( digit / 2 ) th bit of oddMask ; Set the ( digit / 2 ) th bit of evenMask ; Return the answer ; Function to find number of N - digit numbers which has equal count of distinct odd and even digits ; Initialize dp array with - 1 ; Function Call ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100 ] [ 1 << 5 ] [ 1 << 5 ] ; int countOfNumbers ( int index , int evenMask , int oddMask , int N ) { if ( index == N + 1 ) { int countOfEvenDigits = __builtin_popcount ( evenMask ) ; int countOfOddDigits = __builtin_popcount ( oddMask ) ; if ( countOfOddDigits == countOfEvenDigits ) { return 1 ; } return 0 ; } int & val = dp [ index ] [ evenMask ] [ oddMask ] ; if ( val != -1 ) return val ; val = 0 ; if ( index == 1 ) { for ( int digit = ( N == 1 ? 0 : 1 ) ; digit <= 9 ; ++ digit ) { if ( digit & 1 ) { val += countOfNumbers ( index + 1 , evenMask , oddMask | ( 1 << ( digit / 2 ) ) , N ) ; } else { val += countOfNumbers ( index + 1 , evenMask | ( 1 << ( digit / 2 ) ) , oddMask , N ) ; } } } else { for ( int digit = 0 ; digit <= 9 ; ++ digit ) { if ( digit & 1 ) { val += countOfNumbers ( index + 1 , evenMask , oddMask | ( 1 << ( digit / 2 ) ) , N ) ; } else { val += countOfNumbers ( index + 1 , evenMask | ( 1 << ( digit / 2 ) ) , oddMask , N ) ; } } } return val ; } void countNDigitNumber ( int N ) { memset ( dp , -1 , sizeof dp ) ; cout << countOfNumbers ( 1 , 0 , 0 , N ) ; } int main ( ) { int N = 3 ; countNDigitNumber ( N ) ; return 0 ; } |
Minimum number of flips or swaps of adjacent characters required to make two strings equal | C ++ program for the above approach ; Function to count the minimum number of operations required to make strings A and B equal ; Stores all dp - states ; Iterate over the range [ 1 , N ] ; If A [ i - 1 ] equals to B [ i - 1 ] ; Assign Dp [ i - 1 ] to Dp [ i ] ; Otherwise ; Update dp [ i ] ; If swapping is possible ; Update dp [ i ] ; Return the minimum number of steps required ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinSteps ( string A , string B , int N ) { vector < int > dp ( N + 1 , 0 ) ; for ( int i = 1 ; i <= N ; i ++ ) { if ( A [ i - 1 ] == B [ i - 1 ] ) { dp [ i ] = dp [ i - 1 ] ; } else { dp [ i ] = dp [ i - 1 ] + 1 ; } if ( i >= 2 && A [ i - 2 ] == B [ i - 1 ] && A [ i - 1 ] == B [ i - 2 ] ) { dp [ i ] = min ( dp [ i ] , dp [ i - 2 ] + 1 ) ; } } return dp [ N ] ; } int main ( ) { string A = "0101" ; string B = "0011" ; int N = A . length ( ) ; cout << countMinSteps ( A , B , N ) ; return 0 ; } |
Count of N | C ++ program for the above approach ; Function to find the number of N digit numbers such that at least one digit occurs more than once ; Base Case ; If repeated is true , then for remaining positions any digit can be placed ; If the current state has already been computed , then return it ; Stores the count of number for the current recursive calls ; If n = 1 , 0 can be also placed ; If a digit has occurred for the second time , then set repeated to 1 ; Otherwise ; For remaining positions any digit can be placed ; If a digit has occurred for the second time , then set repeated to 1 ; Return the resultant count for the current recursive call ; Function to count all the N - digit numbers having at least one digit 's occurrence more than once ; Initialize dp array with - 1 ; Function to count all possible number satisfying the given criteria ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 50 ] [ 1 << 10 ] [ 2 ] ; int countOfNumbers ( int digit , int mask , bool repeated , int n ) { if ( digit == n + 1 ) { if ( repeated == true ) { return 1 ; } return 0 ; } if ( repeated == true ) { return pow ( 10 , n - digit + 1 ) ; } int & val = dp [ digit ] [ mask ] [ repeated ] ; if ( val != -1 ) { return val ; } val = 0 ; if ( digit == 1 ) { for ( int i = ( n == 1 ? 0 : 1 ) ; i <= 9 ; ++ i ) { if ( mask & ( 1 << i ) ) { val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 1 , n ) ; } else { val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 0 , n ) ; } } } else { for ( int i = 0 ; i <= 9 ; ++ i ) { if ( mask & ( 1 << i ) ) { val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 1 , n ) ; } else { val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 0 , n ) ; } } } return val ; } void countNDigitNumber ( int N ) { memset ( dp , -1 , sizeof dp ) ; cout << countOfNumbers ( 1 , 0 , 0 , N ) ; } int main ( ) { int N = 2 ; countNDigitNumber ( N ) ; return 0 ; } |
Construct the largest number whose sum of cost of digits is K | C ++ program for the above approach ; Function to find the maximum number among the two numbers S and T ; If "0" exists in the string S ; If "0" exists in the string T ; Else return the maximum number formed ; Recursive function to find maximum number formed such that the sum of cost of digits of formed number is K ; Base Case ; Return the stored state ; Including the digit ( idx + 1 ) ; Excluding the digit ( idx + 1 ) ; Store the result and return ; Function to find the maximum number formed such that the sum of the cost digits in the formed number is K ; Stores all Dp - states ; Recursive Call ; Return the result ; Driver Code | #include " bits / stdc + + . h " NEW_LINE using namespace std ; string getMaximum ( string & S , string & T ) { if ( S . find ( "0" ) != string :: npos ) return T ; if ( T . find ( "0" ) != string :: npos ) return S ; return ( S . length ( ) > T . length ( ) ? S : T ) ; } string recursion ( int arr [ ] , int idx , int N , int K , vector < vector < string > > & dp ) { if ( K == 0 ) { return " " ; } if ( K < 0 or idx == N ) { return "0" ; } if ( dp [ idx ] [ K ] != " - 1" ) return dp [ idx ] [ K ] ; string include = to_string ( idx + 1 ) + recursion ( arr , 0 , N , K - arr [ idx ] , dp ) ; string exclude = recursion ( arr , idx + 1 , N , K , dp ) ; return dp [ idx ] [ K ] = getMaximum ( include , exclude ) ; } string largestNumber ( int arr [ ] , int N , int K ) { vector < vector < string > > dp ( N + 1 , vector < string > ( K + 1 , " - 1" ) ) ; string ans = recursion ( arr , 0 , N , K , dp ) ; return ( ans == " " ? "0" : ans ) ; } int main ( ) { int arr [ ] = { 3 , 12 , 9 , 5 , 3 , 4 , 6 , 5 , 10 } ; int K = 14 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << largestNumber ( arr , N , K ) ; return 0 ; } |
Count of N | C ++ program for the above approach ; Function to calculate count of ' N ' digit numbers such that bitwise AND of adjacent digits is 0. ; If digit = n + 1 , a valid n - digit number has been formed ; If the state has already been computed ; If current position is 1 , then any digit from [ 1 - 9 ] can be placed . If n = 1 , 0 can be also placed . ; For remaining positions , any digit from [ 0 - 9 ] can be placed after checking the conditions . ; Check if bitwise AND of current digit and previous digit is 0. ; Return answer ; Driver code ; Initialize dp array with - 1. ; Given Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100 ] [ 10 ] ; int countOfNumbers ( int digit , int prev , int n ) { if ( digit == n + 1 ) { return 1 ; } int & val = dp [ digit ] [ prev ] ; if ( val != -1 ) { return val ; } val = 0 ; if ( digit == 1 ) { for ( int i = ( n == 1 ? 0 : 1 ) ; i <= 9 ; ++ i ) { val += countOfNumbers ( digit + 1 , i , n ) ; } } else { for ( int i = 0 ; i <= 9 ; ++ i ) { if ( ( i & prev ) == 0 ) { val += countOfNumbers ( digit + 1 , i , n ) ; } } } return val ; } int main ( ) { memset ( dp , -1 , sizeof dp ) ; int N = 3 ; cout << countOfNumbers ( 1 , 0 , N ) << endl ; } |
Maximum sum among all ( a x b ) submatrices for given Q queries | C ++ program for the above approach ; Function to preprcess input mat [ N ] [ M ] . This function mainly fills dp [ N ] [ M ] such that dp [ i ] [ j ] stores sum of elements from ( 0 , 0 ) to ( i , j ) ; Copy first row of mat [ ] [ ] to dp [ ] [ ] ; Do column wise sum ; Do row wise sum ; A O ( 1 ) time function to compute sum of submatrix between ( tli , tlj ) and ( rbi , rbj ) using dp [ ] [ ] which is built by the preprocess function ; Result is now sum of elements between ( 0 , 0 ) and ( rbi , rbj ) ; Remove elements between ( 0 , 0 ) and ( tli - 1 , rbj ) ; Remove elements between ( 0 , 0 ) and ( rbi , tlj - 1 ) ; Add dp [ tli - 1 ] [ tlj - 1 ] as elements between ( 0 , 0 ) and ( tli - 1 , tlj - 1 ) are subtracted twice ; Function to find the maximum sum among all ( a x b ) sub - matrices of the matrix ; Function call ; Run a loop for finding answer for all queries ; Driver Code ; Given input ; Function call ; Print answer for all queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; void preProcess ( vector < vector < int > > & mat , vector < vector < int > > & dp , int n , int m ) { for ( int i = 0 ; i < m ; i ++ ) { dp [ 0 ] [ i ] = mat [ 0 ] [ i ] ; } for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + mat [ i ] [ j ] ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 1 ; j < m ; j ++ ) { dp [ i ] [ j ] += dp [ i ] [ j - 1 ] ; } } } int sumQuery ( vector < vector < int > > dp , int tli , int tlj , int rbi , int rbj ) { int res = dp [ rbi ] [ rbj ] ; if ( tli > 0 ) res = res - dp [ tli - 1 ] [ rbj ] ; if ( tlj > 0 ) res = res - dp [ rbi ] [ tlj - 1 ] ; if ( tli > 0 && tlj > 0 ) res = res + dp [ tli - 1 ] [ tlj - 1 ] ; return res ; } vector < int > maxSubMatrixSumQueries ( vector < vector < int > > mat , int n , int m , vector < vector < int > > queries , int q ) { vector < vector < int > > dp ( n , vector < int > ( m ) ) ; preProcess ( mat , dp , n , m ) ; vector < int > maxSum ( ( int ) queries . size ( ) ) ; for ( int qi = 0 ; qi < q ; qi ++ ) { for ( int i = 0 ; i < n - queries [ qi ] [ 0 ] + 1 ; i ++ ) { for ( int j = 0 ; j < m - queries [ qi ] [ 1 ] + 1 ; j ++ ) { maxSum [ qi ] = max ( maxSum [ qi ] , sumQuery ( dp , i , j , i + queries [ qi ] [ 0 ] - 1 , j + queries [ qi ] [ 1 ] - 1 ) ) ; } } } return maxSum ; } int main ( ) { int n = 3 , m = 4 ; vector < vector < int > > mat = { { 1 , 2 , 3 , 9 } , { 4 , 5 , 6 , 2 } , { 8 , 3 , 2 , 6 } } ; int Q = 3 ; vector < vector < int > > Queries = { { 1 , 1 } , { 2 , 2 } , { 3 , 3 } } ; vector < int > maxSum = maxSubMatrixSumQueries ( mat , n , m , Queries , Q ) ; for ( int i = 0 ; i < Q ; i ++ ) { cout << maxSum [ i ] << " β " ; } } |
Number of ways such that only K bars are visible from the left | C ++ implementation for the above approach ; dp array ; Function to calculate the number of permutations of N , where only K bars are visible from the left . ; If subproblem has already been calculated , return ; Only ascending order is possible ; N is placed at the first position The nest N - 1 are arranged in ( N - 1 ) ! ways ; Recursing ; Driver code ; Input ; Initialize dp array ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 1005 ] [ 1005 ] ; int KvisibleFromLeft ( int N , int K ) { if ( dp [ N ] [ K ] != -1 ) return dp [ N ] [ K ] ; if ( N == K ) return dp [ N ] [ K ] = 1 ; if ( K == 1 ) { int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) ans *= i ; return dp [ N ] [ K ] = ans ; } return dp [ N ] [ K ] = KvisibleFromLeft ( N - 1 , K - 1 ) + ( N - 1 ) * KvisibleFromLeft ( N - 1 , K ) ; } int main ( ) { int N = 5 , K = 2 ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << KvisibleFromLeft ( N , K ) << endl ; return 0 ; } |
Number of distinct words of size N with at most K contiguous vowels | C ++ program for the above approach ; Power function to calculate long powers with mod ; Function for finding number of ways to create string with length N and atmost K contiguous vowels ; Array dp to store number of ways ; dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] . . dp [ i - 1 ] [ k ] ) * 21 ; Now setting sum to be dp [ i ] [ 0 ] ; If j > i , no ways are possible to create a string with length i and vowel j ; If j = i all the character should be vowel ; dp [ i ] [ j ] relation with dp [ i - 1 ] [ j - 1 ] ; Adding dp [ i ] [ j ] in the sum ; Driver Program ; Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int power ( long long int x , long long int y , long long int p ) { long long int res = 1ll ; x = x % p ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } int kvowelwords ( int N , int K ) { long long int i , j ; long long int MOD = 1000000007 ; long long int dp [ N + 1 ] [ K + 1 ] = { 0 } ; long long int sum = 1 ; for ( i = 1 ; i <= N ; i ++ ) { dp [ i ] [ 0 ] = sum * 21 ; dp [ i ] [ 0 ] %= MOD ; sum = dp [ i ] [ 0 ] ; for ( j = 1 ; j <= K ; j ++ ) { if ( j > i ) dp [ i ] [ j ] = 0 ; else if ( j == i ) { dp [ i ] [ j ] = power ( 5ll , i , MOD ) ; } else { dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] * 5 ; } dp [ i ] [ j ] %= MOD ; sum += dp [ i ] [ j ] ; sum %= MOD ; } } return sum ; } int main ( ) { int N = 3 ; int K = 3 ; cout << kvowelwords ( N , K ) << endl ; return 0 ; } |
Maximize the length of upper boundary formed by placing given N rectangles horizontally or vertically | C ++ program for the above approach ; Function to find maximum length of the upper boundary formed by placing each of the rectangles either horizontally or vertically ; Stores the intermediate transition states ; Place the first rectangle horizontally ; Place the first rectangle vertically ; Place horizontally ; Stores the difference in height of current and previous rectangle ; Take maximum out of two options ; Place Vertically ; Stores the difference in height of current and previous rectangle ; Take maximum out two options ; Print maximum of horizontal or vertical alignment of the last rectangle ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxBoundary ( int N , vector < pair < int , int > > V ) { int dp [ N ] [ 2 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = V [ 0 ] . first ; dp [ 0 ] [ 1 ] = V [ 0 ] . second ; for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = V [ i ] . first ; int height1 = abs ( V [ i - 1 ] . second - V [ i ] . second ) ; int height2 = abs ( V [ i - 1 ] . first - V [ i ] . second ) ; dp [ i ] [ 0 ] += max ( height1 + dp [ i - 1 ] [ 0 ] , height2 + dp [ i - 1 ] [ 1 ] ) ; dp [ i ] [ 1 ] = V [ i ] . second ; int vertical1 = abs ( V [ i ] . first - V [ i - 1 ] . second ) ; int vertical2 = abs ( V [ i ] . first - V [ i - 1 ] . first ) ; dp [ i ] [ 1 ] += max ( vertical1 + dp [ i - 1 ] [ 0 ] , vertical2 + dp [ i - 1 ] [ 1 ] ) ; } cout << max ( dp [ N - 1 ] [ 0 ] , dp [ N - 1 ] [ 1 ] ) ; } int main ( ) { int N = 5 ; vector < pair < int , int > > V = { { 2 , 5 } , { 3 , 8 } , { 1 , 10 } , { 7 , 14 } , { 2 , 5 } } ; maxBoundary ( N , V ) ; return 0 ; } |
Find maximum subset | Dp vector ; current element ; current element modulo D ; copy previous state ; Transitions ; return answer ; Driver code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( vector < int > A , int N , int K , int D ) { vector < vector < vector < int > > > dp ( N + 1 , vector < vector < int > > ( K + 1 , vector < int > ( D + 1 , -1 ) ) ) ; for ( int i = 1 ; i <= N ; i ++ ) { int element = A [ i - 1 ] ; int mod = A [ i - 1 ] % D ; dp [ i ] = dp [ i - 1 ] ; for ( int j = 1 ; j <= K ; j ++ ) { dp [ i ] [ j ] [ mod ] = max ( dp [ i ] [ j ] [ mod ] , element ) ; for ( int p = 0 ; p < D ; p ++ ) { if ( dp [ i - 1 ] [ j - 1 ] [ p ] != -1 ) { dp [ i ] [ j ] [ ( p + mod ) % D ] = max ( dp [ i ] [ j ] [ ( p + mod ) % D ] , dp [ i - 1 ] [ j - 1 ] [ p ] + element ) ; } } } } if ( dp [ N ] [ K ] [ 0 ] == -1 ) return 0 ; return dp [ N ] [ K ] [ 0 ] ; } int main ( ) { int N = 5 , K = 3 , D = 7 ; vector < int > A = { 1 , 11 , 5 , 5 , 18 } ; cout << maximumSum ( A , N , K , D ) << endl ; return 0 ; } |
Program to find the Nth natural number with exactly two bits set | Set 2 | C ++ program for the above approach ; Function to find the Nth number with exactly two bits set ; Initialize variables ; Initialize the range in which the value of ' a ' is present ; Perform Binary Search ; Find the mid value ; Update the range using the mid value t ; Find b value using a and N ; Print the value 2 ^ a + 2 ^ b ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNthNum ( long long int N ) { long long int a , b , left ; long long int right , mid ; long long int t , last_num = 0 ; left = 1 , right = N ; while ( left <= right ) { mid = left + ( right - left ) / 2 ; t = ( mid * ( mid + 1 ) ) / 2 ; if ( t < N ) { left = mid + 1 ; } else if ( t == N ) { a = mid ; break ; } else { a = mid ; right = mid - 1 ; } } t = a - 1 ; b = N - ( t * ( t + 1 ) ) / 2 - 1 ; cout << ( 1 << a ) + ( 1 << b ) ; } int main ( ) { long long int N = 15 ; findNthNum ( N ) ; return 0 ; } |
Longest subsequence having maximum sum | C ++ program to implement the above approach ; Function to find the longest subsequence from the given array with maximum sum ; Stores the largest element of the array ; If Max is less than 0 ; Print the largest element of the array ; Traverse the array ; If arr [ i ] is greater than or equal to 0 ; Print elements of the subsequence ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void longestSubWithMaxSum ( int arr [ ] , int N ) { int Max = * max_element ( arr , arr + N ) ; if ( Max < 0 ) { cout << Max ; return ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= 0 ) { cout << arr [ i ] << " β " ; } } } int main ( ) { int arr [ ] = { 1 , 2 , -4 , -2 , 3 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; longestSubWithMaxSum ( arr , N ) ; return 0 ; } |
Ways to sum to N using Natural Numbers up to K with repetitions allowed | C ++ program for the above approach ; Function to find the total number of ways to represent N as the sum of integers over the range [ 1 , K ] ; Initialize a list ; Update dp [ 0 ] to 1 ; Iterate over the range [ 1 , K + 1 ] ; Iterate over the range [ 1 , N + 1 ] ; If col is greater than or equal to row ; Update current dp [ col ] state ; Return the total number of ways ; Driver Code ; Given inputs | #include <bits/stdc++.h> NEW_LINE using namespace std ; int NumberOfways ( int N , int K ) { vector < int > dp ( N + 1 , 0 ) ; dp [ 0 ] = 1 ; for ( int row = 1 ; row < K + 1 ; row ++ ) { for ( int col = 1 ; col < N + 1 ; col ++ ) { if ( col >= row ) dp [ col ] = dp [ col ] + dp [ col - row ] ; } } return ( dp [ N ] ) ; } int main ( ) { int N = 8 ; int K = 2 ; cout << ( NumberOfways ( N , K ) ) ; } |
Queries to check if array elements from indices [ L , R ] forms an Arithmetic Progression or not | C ++ program for the above approach ; Function to check if the given range of queries form an AP or not in the given array arr [ ] ; Stores length of the longest subarray forming AP for every array element ; Iterate over the range [ 0 , N ] ; Stores the index of the last element of forming AP ; Iterate until the element at index ( j , j + 1 ) forms AP ; Increment j by 1 ; Traverse the current subarray over the range [ i , j - 1 ] ; Update the length of the longest subarray at index k ; Update the value of i ; Traverse the given queries ; Print the result ; Otherwise ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findAPSequence ( int arr [ ] , int N , int Q [ ] [ 2 ] , int M ) { int dp [ N + 5 ] = { 0 } ; for ( int i = 0 ; i + 1 < N ; ) { int j = i + 1 ; while ( j + 1 < N && arr [ j + 1 ] - arr [ j ] == arr [ i + 1 ] - arr [ i ] ) j ++ ; for ( int k = i ; k < j ; k ++ ) { dp [ k ] = j - k ; } i = j ; } for ( int i = 0 ; i < M ; i ++ ) { if ( dp [ Q [ i ] [ 0 ] ] >= Q [ i ] [ 1 ] - Q [ i ] [ 0 ] ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } } } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 7 , 6 , 5 , 4 , 1 } ; int Q [ ] [ 2 ] = { { 0 , 3 } , { 3 , 4 } , { 2 , 4 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; findAPSequence ( arr , N , Q , M ) ; return 0 ; } |
Minimize difference between sum of two K | C ++ program for the above approach ; Stores the values at recursive states ; Function to find the minimum difference between sum of two K - length subsets ; Base Case ; If k1 and k2 are 0 , then return the absolute difference between sum1 and sum2 ; Otherwise , return INT_MAX ; If the result is already computed , return the result ; Store the 3 options ; Including the element in first subset ; Including the element in second subset ; Not including the current element in both the subsets ; Store minimum of 3 values obtained ; Return the value for the current states ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100 ] [ 100 ] [ 100 ] ; int minSumDifference ( int * arr , int n , int k1 , int k2 , int sum1 , int sum2 ) { if ( n < 0 ) { if ( k1 == 0 && k2 == 0 ) { return abs ( sum1 - sum2 ) ; } else { return INT_MAX ; } } if ( dp [ n ] [ sum1 ] [ sum2 ] != -1 ) { return dp [ n ] [ sum1 ] [ sum2 ] ; } int op1 = INT_MAX ; int op2 = INT_MAX ; int op3 = INT_MAX ; if ( k1 > 0 ) { op1 = minSumDifference ( arr , n - 1 , k1 - 1 , k2 , sum1 + arr [ n ] , sum2 ) ; } if ( k2 > 0 ) { op2 = minSumDifference ( arr , n - 1 , k1 , k2 - 1 , sum1 , sum2 + arr [ n ] ) ; } op3 = minSumDifference ( arr , n - 1 , k1 , k2 , sum1 , sum2 ) ; dp [ n ] [ sum1 ] [ sum2 ] = min ( op1 , min ( op2 , op3 ) ) ; return dp [ n ] [ sum1 ] [ sum2 ] ; } int main ( ) { int arr [ ] = { 12 , 3 , 5 , 6 , 7 , 17 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << minSumDifference ( arr , N - 1 , K , K , 0 , 0 ) ; return 0 ; } |
Geek | Function to calculate the N - th Geek - onacci Number ; Stores the geekonacci series ; Store the first three terms of the series ; Iterate over the range [ 3 , N ] ; Update the value of arr [ i ] as the sum of previous 3 terms in the series ; Return the last element of arr [ ] as the N - th term ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( int A , int B , int C , int N ) { int arr [ N ] ; arr [ 0 ] = A ; arr [ 1 ] = B ; arr [ 2 ] = C ; for ( int i = 3 ; i < N ; i ++ ) { arr [ i ] = arr [ i - 1 ] + arr [ i - 2 ] + arr [ i - 3 ] ; } return arr [ N - 1 ] ; } int main ( ) { int A = 1 , B = 3 , C = 2 , N = 4 ; cout << ( find ( A , B , C , N ) ) ; return 0 ; } |
Maximum sum subsequence made up of at most K distant elements including the first and last array elements | CPP program for the above approach ; Function to find maximum sum of a subsequence satisfying the given conditions ; Stores the maximum sum ; Starting index of the subsequence ; Stores the pair of maximum value and the index of that value ; Traverse the array ; Increment the first value of deque by arr [ i ] and store it in dp [ i ] ; Delete all the values which are less than dp [ i ] in deque ; Append the current pair of value and index in deque ; If first value of the queue is at a distance > K ; Return the value at the last index ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxResult ( int arr [ ] , int k , int n ) { int dp [ n ] = { 0 } ; dp [ 0 ] = arr [ 0 ] ; deque < pair < int , int > > q ; q . push_back ( { arr [ 0 ] , 0 } ) ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] = arr [ i ] + q . front ( ) . first ; while ( q . size ( ) > 0 and q . back ( ) . first < dp [ i ] ) q . pop_back ( ) ; q . push_back ( { dp [ i ] , i } ) ; if ( i - k == q . front ( ) . second ) q . pop_front ( ) ; } return dp [ n - 1 ] ; } int main ( ) { int arr [ ] = { 10 , -5 , -2 , 4 , 0 , 3 } ; int K = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxResult ( arr , K , n ) ; } |
Minimum days required to cure N persons | C ++ Program for the above approach ; Function to find minimum count of days required to give a cure such that the high risk person and risk person does not get a dose on same day . ; Stores count of persons whose age is less than or equal to 10 and greater than or equal to 60. ; Stores the count of persons whose age is in the range [ 11 , 59 ] ; Traverse the array arr [ ] ; If age less than or equal to 10 or greater than or equal to 60 ; Update risk ; Update normal_risk ; Calculate days to cure risk and normal_risk persons ; Print the days ; Driver Code ; Given array ; Size of the array ; Given P | #include <bits/stdc++.h> NEW_LINE using namespace std ; void daysToCure ( int arr [ ] , int N , int P ) { int risk = 0 ; int normal_risk = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= 60 arr [ i ] <= 10 ) { risk ++ ; } else { normal_risk ++ ; } } int days = ( risk / P ) + ( risk % P > 0 ) + ( normal_risk / P ) + ( normal_risk % P > 0 ) ; cout << days ; } int main ( ) { int arr [ ] = { 9 , 80 , 27 , 72 , 79 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int P = 2 ; daysToCure ( arr , N , P ) ; return 0 ; } |
Count numbers from a given range whose product of digits is K | C ++ program to implement the above approach ; Function to count numbers in the range [ 0 , X ] whose product of digit is K ; If count of digits in a number greater than count of digits in X ; If product of digits of a number equal to K ; If overlapping subproblems already occurred ; Stores count of numbers whose product of digits is K ; Check if the numbers exceeds K or not ; Iterate over all possible value of i - th digits ; if number contains leading 0 ; Update res ; Update res ; Return res ; Utility function to count the numbers in the range [ L , R ] whose prod of digits is K ; Stores numbers in the form of string ; Stores overlapping subproblems ; Initialize dp [ ] [ ] [ ] to - 1 ; Stores count of numbers in the range [ 0 , R ] whose product of digits is k ; Update str ; Initialize dp [ ] [ ] [ ] to - 1 ; Stores count of numbers in the range [ 0 , L - 1 ] whose product of digits is k ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 100 NEW_LINE int cntNum ( string X , int i , int prod , int K , int st , int tight , int dp [ M ] [ M ] [ 2 ] [ 2 ] ) { if ( i >= X . length ( ) prod > K ) { return prod == K ; } if ( dp [ prod ] [ i ] [ tight ] [ st ] != -1 ) { return dp [ prod ] [ i ] [ tight ] [ st ] ; } int res = 0 ; int end = tight ? X [ i ] - '0' : 9 ; for ( int j = 0 ; j <= end ; j ++ ) { if ( j == 0 && ! st ) { res += cntNum ( X , i + 1 , prod , K , false , ( tight & ( j == end ) ) , dp ) ; } else { res += cntNum ( X , i + 1 , prod * j , K , true , ( tight & ( j == end ) ) , dp ) ; } return dp [ prod ] [ i ] [ tight ] [ st ] = res ; } int UtilCntNumRange ( int L , int R , int K ) { string str = to_string ( R ) ; int dp [ M ] [ M ] [ 2 ] [ 2 ] ; memset ( dp , -1 , sizeof ( dp ) ) ; int cntR = cntNum ( str , 0 , 1 , K , false , true , dp ) ; str = to_string ( L - 1 ) ; memset ( dp , -1 , sizeof ( dp ) ) ; int cntL = cntNum ( str , 0 , 1 , K , false , true , dp ) ; return ( cntR - cntL ) ; } int main ( ) { int L = 20 , R = 10000 , K = 14 ; cout << UtilCntNumRange ( L , R , K ) ; } |
Count all possible N | C ++ program for the above approach ; Function to find the number of vowel permutations possible ; To avoid the large output value ; Initialize 2D dp array ; Initialize dp [ 1 ] [ i ] as 1 since string of length 1 will consist of only one vowel in the string ; Directed graph using the adjacency matrix ; Iterate over the range [ 1 , N ] ; Traverse the directed graph ; Traversing the list ; Update dp [ i + 1 ] [ u ] ; Stores total count of permutations ; Return count of permutations ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countVowelPermutation ( int n ) { int MOD = ( int ) ( 1e9 + 7 ) ; long dp [ n + 1 ] [ 5 ] ; for ( int i = 0 ; i < 5 ; i ++ ) { dp [ 1 ] [ i ] = 1 ; } vector < vector < int > > relation = { { 1 } , { 0 , 2 } , { 0 , 1 , 3 , 4 } , { 2 , 4 } , { 0 } } ; for ( int i = 1 ; i < n ; i ++ ) { for ( int u = 0 ; u < 5 ; u ++ ) { dp [ i + 1 ] [ u ] = 0 ; for ( int v : relation [ u ] ) { dp [ i + 1 ] [ u ] += dp [ i ] [ v ] % MOD ; } } } long ans = 0 ; for ( int i = 0 ; i < 5 ; i ++ ) { ans = ( ans + dp [ n ] [ i ] ) % MOD ; } return ( int ) ans ; } int main ( ) { int N = 2 ; cout << countVowelPermutation ( N ) ; } |
Queries to calculate Bitwise OR of each subtree of a given node in an N | C ++ program for the above approach ; Maximum Number of nodes ; Adjacency list ; Stores Bitwise OR of each node ; Function to add edges to the Tree ; Traverse the edges ; Add edges ; Function to perform DFS Traversal on the given tree ; Initialize answer with bitwise OR of current node ; Iterate over each child of the current node ; Skip parent node ; Call DFS for each child ; Taking bitwise OR of the answer of the child to find node 's OR value ; Function to call DFS from the '= root for precomputing answers ; Function to calculate and print the Bitwise OR for Q queries ; Perform preprocessing ; Iterate over each given query ; Utility function to find and print bitwise OR for Q queries ; Function to add edges to graph ; Function call ; Driver Code ; Number of nodes ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1e5 + 5 ; vector < int > adj [ N ] ; vector < int > answer ( N ) ; void addEdgesToGraph ( int Edges [ ] [ 2 ] , int N ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { int u = Edges [ i ] [ 0 ] ; int v = Edges [ i ] [ 1 ] ; adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } } void DFS ( int node , int parent , int Val [ ] ) { answer [ node ] = Val [ node ] ; for ( int child : adj [ node ] ) { if ( child == parent ) continue ; DFS ( child , node , Val ) ; answer [ node ] = ( answer [ node ] answer [ child ] ) ; } } void preprocess ( int Val [ ] ) { DFS ( 1 , -1 , Val ) ; } void findSubtreeOR ( int Queries [ ] , int Q , int Val [ ] ) { preprocess ( Val ) ; for ( int i = 0 ; i < Q ; i ++ ) { cout << answer [ Queries [ i ] ] << ' β ' ; } } void findSubtreeORUtil ( int N , int Edges [ ] [ 2 ] , int Val [ ] , int Queries [ ] , int Q ) { addEdgesToGraph ( Edges , N ) ; findSubtreeOR ( Queries , Q , Val ) ; } int main ( ) { int N = 5 ; int Edges [ ] [ 2 ] = { { 1 , 2 } , { 1 , 3 } , { 3 , 4 } , { 3 , 5 } } ; int Val [ ] = { 0 , 2 , 3 , 4 , 8 , 16 } ; int Queries [ ] = { 2 , 3 , 1 } ; int Q = sizeof ( Queries ) / sizeof ( Queries [ 0 ] ) ; findSubtreeORUtil ( N , Edges , Val , Queries , Q ) ; return 0 ; } |
Maximize sum of K elements selected from a Matrix such that each selected element must be preceded by selected row elements | C ++ program for the above approach ; Function to return the maximum of two elements ; Function to find the maximum sum of selecting K elements from the given 2D array arr [ ] [ ] ; dp table of size ( K + 1 ) * ( N + 1 ) ; Initialize dp [ 0 ] [ i ] = 0 ; Initialize dp [ i ] [ 0 ] = 0 ; Selecting i elements ; Select i elements till jth row ; sum = 0 , to keep track of cummulative elements sum ; Traverse arr [ j ] [ k ] until number of elements until k > i ; Select arr [ j ] [ k - 1 ] th item ; Store the maxSum in dp [ i ] [ j + 1 ] ; Return the maximum sum ; Driver Code ; Function Call | #include <iostream> NEW_LINE using namespace std ; int max ( int a , int b ) { return a > b ? a : b ; } int maximumsum ( int arr [ ] [ 4 ] , int K , int N , int M ) { int sum = 0 , maxSum ; int i , j , k ; int dp [ K + 1 ] [ N + 1 ] ; for ( i = 0 ; i <= N ; i ++ ) dp [ 0 ] [ i ] = 0 ; for ( i = 0 ; i <= K ; i ++ ) dp [ i ] [ 0 ] = 0 ; for ( i = 1 ; i <= K ; i ++ ) { for ( j = 0 ; j < N ; j ++ ) { sum = 0 ; maxSum = dp [ i ] [ j ] ; for ( k = 1 ; k <= M && k <= i ; k ++ ) { sum += arr [ j ] [ k - 1 ] ; maxSum = max ( maxSum , sum + dp [ i - k ] [ j ] ) ; } dp [ i ] [ j + 1 ] = maxSum ; } } return dp [ K ] [ N ] ; } int main ( ) { int arr [ ] [ 4 ] = { { 10 , 10 , 100 , 30 } , { 80 , 50 , 10 , 50 } } ; int N = 2 , M = 4 ; int K = 5 ; cout << maximumsum ( arr , K , N , M ) ; return 0 ; } |
Subsequences of given string consisting of non | C ++ program to implement the above approach ; Function to find all the subsequences of the string with non - repeating characters ; Base case ; Insert current subsequence ; If str [ i ] is not present in the current subsequence ; Insert str [ i ] into the set ; Insert str [ i ] into the current subsequence ; Remove str [ i ] from current subsequence ; Remove str [ i ] from the set ; Not including str [ i ] from the current subsequence ; Utility function to print all subsequences of string with non - repeating characters ; Stores all possible subsequences with non - repeating characters ; Stores subsequence with non - repeating characters ; Traverse all possible subsequences containing non - repeating characters ; Print subsequence ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void FindSub ( set < string > & sub , set < char > & ch , string str , string res , int i ) { if ( i == str . length ( ) ) { sub . insert ( res ) ; return ; } if ( ! ch . count ( str [ i ] ) ) { ch . insert ( str [ i ] ) ; res . push_back ( str [ i ] ) ; FindSub ( sub , ch , str , res , i + 1 ) ; res . pop_back ( ) ; ch . erase ( str [ i ] ) ; } FindSub ( sub , ch , str , res , i + 1 ) ; } void printSubwithUniqueChar ( string str , int N ) { set < string > sub ; set < char > ch ; FindSub ( sub , ch , str , " " , 0 ) ; for ( auto subString : sub ) { cout << subString << " β " ; } } int main ( ) { string str = " abac " ; int N = str . length ( ) ; printSubwithUniqueChar ( str , N ) ; return 0 ; } |
Count lexicographically increasing K | C ++ program for the above approach ; Function to count K - length strings from first N alphabets ; To keep track of column sum in dp ; Auxiliary 2d dp array ; Initialize dp [ 0 ] [ i ] = 1 and update the column_sum ; Iterate for K times ; Iterate for N times ; dp [ i ] [ j ] : Stores the number of ways to form i - length strings consisting of j letters ; Update the column_sum ; Print number of ways to arrange K - length strings with N alphabets ; Driver Code ; Given N and K ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void waysToArrangeKLengthStrings ( int N , int K ) { int column_sum [ N + 1 ] = { 0 } , i , j ; int dp [ K + 1 ] [ N + 1 ] = { 0 } ; for ( i = 0 ; i <= N ; i ++ ) { dp [ 0 ] [ i ] = 1 ; column_sum [ i ] = 1 ; } for ( i = 1 ; i <= K ; i ++ ) { for ( j = 1 ; j <= N ; j ++ ) { dp [ i ] [ j ] += column_sum [ j - 1 ] ; column_sum [ j ] += dp [ i ] [ j ] ; } } cout << dp [ K ] [ N ] ; } int main ( ) { int N = 5 , K = 2 ; waysToArrangeKLengthStrings ( N , K ) ; return 0 ; } |
Count N | C ++ program for the above approach ; Function to count N - length strings consisting of vowels only sorted lexicographically ; Stores count of strings consisting of vowels sorted lexicographically of all possible lengths ; Initialize DP [ 1 ] [ 1 ] ; Traverse the matrix row - wise ; Base Case ; Return the result ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumberOfStrings ( int n ) { vector < vector < int > > DP ( n + 1 , vector < int > ( 6 ) ) ; DP [ 1 ] [ 1 ] = 1 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { for ( int j = 1 ; j < 6 ; j ++ ) { if ( i == 1 ) { DP [ i ] [ j ] = DP [ i ] [ j - 1 ] + 1 ; } else { DP [ i ] [ j ] = DP [ i ] [ j - 1 ] + DP [ i - 1 ] [ j ] ; } } } return DP [ n ] [ 5 ] ; } int main ( ) { int N = 2 ; cout << findNumberOfStrings ( N ) ; return 0 ; } |
Largest subtree sum for each vertex of given N | C ++ program for the above approach ; Function to perform the DFS Traversal on the given Tree ; To check if v is leaf vertex ; Initialize answer for vertex v ; Traverse adjacency list of v ; Update maximum subtree sum ; If v is leaf ; Function to calculate maximum subtree sum for each vertex ; Stores the adjacency list ; Add Edegs to the list ; Stores largest subtree sum for each vertex ; Calculate answer ; Print the result ; Driver Code ; Given nodes ; Give N edges ; Given values ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define V 3 NEW_LINE #define M 2 NEW_LINE void dfs ( int v , int p , vector < int > adj [ ] , int ans [ ] , int vals [ ] ) { bool isLeaf = 1 ; ans [ v ] = INT_MIN ; for ( int u : adj [ v ] ) { if ( u == p ) continue ; isLeaf = 0 ; dfs ( u , v , adj , ans , vals ) ; ans [ v ] = max ( ans [ u ] + vals [ v ] , max ( ans [ u ] , vals [ u ] ) ) ; } if ( isLeaf ) { ans [ v ] = vals [ v ] ; } } void printAnswer ( int n , int edges [ V ] [ M ] , int values [ ] ) { vector < int > adj [ n ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int u = edges [ i ] [ 0 ] - 1 ; int v = edges [ i ] [ 1 ] - 1 ; adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } int ans [ n ] ; dfs ( 0 , -1 , adj , ans , values ) ; for ( auto x : ans ) { cout << x << " β " ; } } int main ( ) { int N = 4 ; int edges [ V ] [ M ] = { { 1 , 2 } , { 1 , 3 } , { 3 , 4 } } ; int values [ ] = { 1 , -1 , 0 , 1 } ; printAnswer ( N , edges , values ) ; } |
Queries to count frequencies of a given character in a given range of indices | C ++ program for the above approach ; Function to print count of char y present in the range [ l , r ] ; Length of the string ; Stores the precomputed results ; Iterate the given string ; Increment dp [ i ] [ y - ' a ' ] by 1 ; Pre - compute ; Traverse each query ; Print the result for each query ; Driver Code ; Given string ; Given Queries ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void noOfChars ( string s , char queries [ ] [ 3 ] , int q ) { int n = s . length ( ) ; int dp [ n + 1 ] [ 26 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 0 ; i < n ; i ++ ) { dp [ i + 1 ] [ s [ i ] - ' a ' ] ++ ; for ( int j = 0 ; j < 26 ; j ++ ) { dp [ i + 1 ] [ j ] += dp [ i ] [ j ] ; } } for ( int i = 0 ; i < q ; i ++ ) { int l = ( int ) queries [ i ] [ 0 ] ; int r = ( int ) queries [ i ] [ 1 ] ; int c = queries [ i ] [ 2 ] - ' a ' ; cout << dp [ r ] - dp [ l - 1 ] << " β " ; } } int main ( ) { string S = " aabv " ; char queries [ 2 ] [ 3 ] = { { 1 , 2 , ' a ' } , { 2 , 3 , ' b ' } } ; noOfChars ( S , queries , 2 ) ; return 0 ; } |
Minimum cost required to rearrange a given array to make it equal to another given array | C ++ program for the above approach ; Function to find length of the longest common subsequence ; Find position where element is to be inserted ; Return the length of LCS ; Function to find the minimum cost required to convert the sequence A exactly same as B ; Auxiliary array ; Stores positions of elements of A [ ] ; Initialize index array with - 1 ; Update the index array with index of corresponding elements of B ; Place only A 's array values with its mapped values into nums array ; Find LCS ; No of elements to be added in array A [ ] ; Stores minimum cost ; Print the minimum cost ; Driver Code ; Given array A [ ] ; Given C ; Size of arr A ; Size of arr B ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findLCS ( int * nums , int N ) { int k = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int pos = lower_bound ( nums , nums + k , nums [ i ] ) - nums ; nums [ pos ] = nums [ i ] ; if ( k == pos ) { k = pos + 1 ; } } return k ; } int minimumCost ( int * A , int * B , int M , int N , int C ) { int nums [ 1000000 ] ; int index [ 1000000 ] ; memset ( index , -1 , sizeof ( index ) ) ; for ( int i = 0 ; i < N ; i ++ ) { index [ B [ i ] ] = i ; } int k = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( index [ A [ i ] ] != -1 ) { nums [ k ++ ] = index [ A [ i ] ] ; } } int lcs_length = findLCS ( nums , k ) ; int elements_to_be_added = N - lcs_length ; int min_cost = elements_to_be_added * C ; cout << min_cost ; } int main ( ) { int A [ ] = { 1 , 6 , 3 , 5 , 10 } ; int B [ ] = { 3 , 1 , 5 } ; int C = 2 ; int M = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int N = sizeof ( B ) / sizeof ( B [ 0 ] ) ; minimumCost ( A , B , M , N , C ) ; return 0 ; } |
Maximize count of array elements required to obtain given sum | C ++ 14 program for the above approach ; Function that count the maximum number of elements to obtain sum V ; Stores the maximum number of elements required to obtain V ; Base Case ; Initialize all table values as Infinite ; Find the max arr required for all values from 1 to V ; Go through all arr smaller than i ; If current coin value is less than i ; Update table [ i ] ; Return the final count ; Driver Code ; Given array ; Given sum V ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxCount ( vector < int > arr , int m , int V ) { vector < int > table ( V + 1 ) ; table [ 0 ] = 0 ; for ( int i = 1 ; i <= V ; i ++ ) table [ i ] = -1 ; for ( int i = 1 ; i <= V ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( arr [ j ] <= i ) { int sub_res = table [ i - arr [ j ] ] ; if ( sub_res != -1 && sub_res + 1 > table [ i ] ) table [ i ] = sub_res + 1 ; } } } return table [ V ] ; } int main ( ) { vector < int > arr = { 25 , 10 , 5 } ; int m = arr . size ( ) ; int V = 30 ; cout << ( maxCount ( arr , m , V ) ) ; return 0 ; } |
Longest Subsequence from a numeric String divisible by K | C ++ program for the above approach ; Function to if the integer representation of the current string is divisible by K ; Stores the integer representation of the string ; Check if the num is divisible by K ; Function to find the longest subsequence which is divisible by K ; If the number is divisible by K ; If current number is the maximum obtained so far ; Include the digit at current index ; Exclude the digit at current index ; Driver Code ; Printing the largest number which is divisible by K ; If no number is found to be divisible by K | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isdivisible ( string & newstr , long long K ) { long long num = 0 ; for ( int i = 0 ; i < newstr . size ( ) ; i ++ ) { num = num * 10 + newstr [ i ] - '0' ; } if ( num % K == 0 ) return true ; else return false ; } void findLargestNo ( string & str , string & newstr , string & ans , int index , long long K ) { if ( index == ( int ) str . length ( ) ) { if ( isdivisible ( newstr , K ) ) { if ( ( ans < newstr && ans . length ( ) == newstr . length ( ) ) || newstr . length ( ) > ans . length ( ) ) { ans = newstr ; } } return ; } string x = newstr + str [ index ] ; findLargestNo ( str , x , ans , index + 1 , K ) ; findLargestNo ( str , newstr , ans , index + 1 , K ) ; } int main ( ) { string str = "121400" ; string ans = " " , newstr = " " ; long long K = 8 ; findLargestNo ( str , newstr , ans , 0 , K ) ; if ( ans != " " ) cout << ans << endl ; else cout << -1 << endl ; } |
Maximize path sum from top | C ++ program to implement the above approach ; Function to get the maximum path sum from top - left cell to all other cells of the given matrix ; Store the maximum path sum ; Initialize the value of dp [ i ] [ j ] to 0. ; Base case ; Compute the value of dp [ i ] [ j ] using the recurrence relation ; Print maximum path sum from the top - left cell ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define SZ 100 NEW_LINE void pathSum ( const int mat [ SZ ] [ SZ ] , int N , int M ) { int dp [ N ] [ M ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = mat [ 0 ] [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = mat [ i ] [ 0 ] + dp [ i - 1 ] [ 0 ] ; } for ( int j = 1 ; j < M ; j ++ ) { dp [ 0 ] [ j ] = mat [ 0 ] [ j ] + dp [ 0 ] [ j - 1 ] ; } for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j < M ; j ++ ) { dp [ i ] [ j ] = mat [ i ] [ j ] + max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { cout << dp [ i ] [ j ] << " β " ; } cout << endl ; } } int main ( ) { int mat [ SZ ] [ SZ ] = { { 3 , 2 , 1 } , { 6 , 5 , 4 } , { 7 , 8 , 9 } } ; int N = 3 ; int M = 3 ; pathSum ( mat , N , M ) ; } |
Length of Longest Palindrome Substring | C ++ program for the above approach ; Function to find the length of the longest palindromic substring ; Length of string str ; Stores the dp states ; Initialise table [ ] [ ] as false ; All substrings of length 1 are palindromes ; Check for sub - string of length 2 ; If adjacent character are same ; Update table [ i ] [ i + 1 ] ; Check for lengths greater than 2 k is length of substring ; Fix the starting index ; Ending index of substring of length k ; Check for palindromic substring str [ i , j ] ; Mark true ; Update the maximum length ; Return length of LPS ; Driver Code ; Given string str ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int longestPalSubstr ( string str ) { int n = str . size ( ) ; bool table [ n ] [ n ] ; memset ( table , 0 , sizeof ( table ) ) ; int maxLength = 1 ; for ( int i = 0 ; i < n ; ++ i ) table [ i ] [ i ] = true ; int start = 0 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( str [ i ] == str [ i + 1 ] ) { table [ i ] [ i + 1 ] = true ; start = i ; maxLength = 2 ; } } for ( int k = 3 ; k <= n ; ++ k ) { for ( int i = 0 ; i < n - k + 1 ; ++ i ) { int j = i + k - 1 ; if ( table [ i + 1 ] [ j - 1 ] && str [ i ] == str [ j ] ) { table [ i ] [ j ] = true ; if ( k > maxLength ) { start = i ; maxLength = k ; } } } } return maxLength ; } int main ( ) { string str = " forgeeksskeegfor " ; cout << longestPalSubstr ( str ) ; return 0 ; } |
Maximize sum of an Array by flipping sign of all elements of a single subarray | C ++ program for the above approach ; Function to find the maximum sum after flipping a subarray ; Stores the total sum of array ; Initialize the maximum sum ; Iterate over all possible subarrays ; Initialize sum of the subarray before flipping sign ; Initialize sum of subarray after flipping sign ; Calculate the sum of original subarray ; Subtract the original subarray sum and add the flipped subarray sum to the total sum ; Return the max_sum ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumFlip ( int a [ ] , int n ) { int total_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) total_sum += a [ i ] ; int max_sum = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; int flip_sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += a [ j ] ; max_sum = max ( max_sum , total_sum - 2 * sum ) ; } } return max ( max_sum , total_sum ) ; } int main ( ) { int arr [ ] = { -2 , 3 , -1 , -4 , -2 } ; int N = sizeof ( arr ) / sizeof ( int ) ; cout << maxSumFlip ( arr , N ) ; } |
Minimum repeated addition of even divisors of N required to convert N to M | C ++ program for the above approach ; INF is the maximum value which indicates Impossible state ; Stores the dp states ; Recursive Function that considers all possible even divisors of cur ; Indicates impossible state ; Check dp [ cur ] is already calculated or not ; Initially it is set to INF that meanswe cur can 't be transform to M ; Loop to find even divisors of cur ; if i is divisor of cur ; if i is even ; Find recursively for cur + i ; Check another divisor ; Find recursively for cur + ( cur / i ) ; Finally store the current state result and return the answer ; Function that counts the minimum operation to reduce N to M ; Initialise dp state ; Function Call ; Driver Code ; Given N and M ; Function Call ; INF indicates impossible state | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int INF = 1e7 ; const int max_size = 100007 ; int dp [ max_size ] ; int min_op ( int cur , int M ) { if ( cur > M ) return INF ; if ( cur == M ) return 0 ; if ( dp [ cur ] != -1 ) return dp [ cur ] ; int op = INF ; for ( int i = 2 ; i * i <= cur ; i ++ ) { if ( cur % i == 0 ) { if ( i % 2 == 0 ) { op = min ( op , 1 + min_op ( cur + i , M ) ) ; } if ( ( cur / i ) != i && ( cur / i ) % 2 == 0 ) { op = min ( op , 1 + min_op ( cur + ( cur / i ) , M ) ) ; } } } return dp [ cur ] = op ; } int min_operations ( int N , int M ) { for ( int i = N ; i <= M ; i ++ ) { dp [ i ] = -1 ; } return min_op ( N , M ) ; } int main ( ) { int N = 6 , M = 24 ; int op = min_operations ( N , M ) ; if ( op >= INF ) cout << " - 1" ; else cout << op << " STRNEWLINE " ; return 0 ; } |
Maximize Sum possible from an Array by the given moves | C ++ program to implement the above approach ; Function to find the maximum sum possible by given moves from the array ; Checking for boundary ; If previously computed subproblem occurs ; If element can be moved left ; Calculate maximum possible sum by moving left from current index ; If element can be moved right ; Calculate maximum possible sum by moving right from current index and update the maximum sum ; Store the maximum sum ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int k = 1 ; const int m = 4 ; int maxValue ( int a [ ] , int n , int pos , int moves , int left , int dp [ ] [ k + 1 ] ) { if ( moves == 0 || ( pos > n - 1 pos < 0 ) ) return 0 ; if ( dp [ pos ] [ left ] != -1 ) return dp [ pos ] [ left ] ; int value = 0 ; if ( left > 0 && pos >= 1 ) value = max ( value , a [ pos ] + maxValue ( a , n , pos - 1 , moves - 1 , left - 1 , dp ) ) ; if ( pos <= n - 1 ) value = max ( value , a [ pos ] + maxValue ( a , n , pos + 1 , moves - 1 , left , dp ) ) ; return dp [ pos ] [ left ] = value ; } int main ( ) { int n = 5 ; int a [ ] = { 1 , 5 , 4 , 3 , 2 } ; int dp [ n + 1 ] [ k + 1 ] ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << ( a [ 0 ] + maxValue ( a , n , 1 , m , k , dp ) ) << endl ; } |
Maximize the Sum of a Subsequence from an Array based on given conditions | C ++ program to implement the above approach ; Function to select the array elements to maximize the sum of the selected elements ; If the entire array is solved ; Memoized subproblem ; Calculate sum considering the current element in the subsequence ; Calculate sum without considering the current element in the subsequence ; Update the maximum of the above sums in the dp [ ] [ ] table ; Driver Code ; Initialize the dp array ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 6 ; int maximumSum ( int a [ ] , int count , int index , int n , int dp [ N ] [ N ] ) { if ( index == n ) return 0 ; if ( dp [ index ] [ count ] != -1 ) return dp [ index ] [ count ] ; int take_element = a [ index ] * count + maximumSum ( a , count + 1 , index + 1 , n , dp ) ; int dont_take = maximumSum ( a , count , index + 1 , n , dp ) ; return dp [ index ] [ count ] = max ( take_element , dont_take ) ; } int main ( ) { int n = 5 ; int a [ ] = { -1 , -9 , 0 , 5 , -7 } ; int dp [ N ] [ N ] ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << ( maximumSum ( a , 1 , 0 , n , dp ) ) ; } |
Queries to find sum of distance of a given node to every leaf node in a Weighted Tree | C ++ program for the above problem ; MAX size ; graph with { destination , weight } ; ; for storing the sum for ith node ; leaves in subtree of ith . ; dfs to find sum of distance of leaves in the subtree of a node ; flag is the node is leaf or not ; ; skipping if parent ; setting flag to false ; doing dfs call ; doing calculation in postorder . ; if the node is leaf then we just increment the no . of leaves under the subtree of a node ; adding num of leaves ; calculating answer for the sum in the subtree ; dfs function to find the sum of distance of leaves outside the subtree ; number of leaves other than the leaves in the subtree of i ; adding the contribution of leaves outside to the ith node ; adding the leafs outside to ith node 's leaves. ; calculating the sum of distance of leaves in the subtree of a node assuming the root of the tree is 1 ; calculating the sum of distance of leaves outside the subtree of node assuming the root of the tree is 1 ; answering the queries ; ; Driver Code ; 1 ( 4 ) / \ ( 2 ) / \ 4 2 ( 5 ) / \ ( 3 ) / \ 5 3 ; initialising tree ; System . out . println ( v ) ; | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1e5 + 5 ; vector < vector < pair < int , int > > > v ( N ) ; vector < int > dp ( N ) ; vector < int > leaves ( N ) ; int n ; void dfs ( int a , int par ) { bool leaf = 1 ; for ( auto & i : v [ a ] ) { if ( i . first == par ) continue ; leaf = 0 ; dfs ( i . first , a ) ; } if ( leaf == 1 ) { leaves [ a ] += 1 ; } else { for ( auto & i : v [ a ] ) { if ( i . first == par ) continue ; leaves [ a ] += leaves [ i . first ] ; dp [ a ] = dp [ a ] + dp [ i . first ] + leaves [ i . first ] * i . second ; } } } void dfs2 ( int a , int par ) { for ( auto & i : v [ a ] ) { if ( i . first == par ) continue ; int leafOutside = leaves [ a ] - leaves [ i . first ] ; dp [ i . first ] += ( dp [ a ] - dp [ i . first ] ) ; dp [ i . first ] += i . second * ( leafOutside - leaves [ i . first ] ) ; leaves [ i . first ] += leafOutside ; dfs2 ( i . first , a ) ; } } void answerQueries ( vector < int > queries ) { dfs ( 1 , 0 ) ; dfs2 ( 1 , 0 ) ; for ( int i = 0 ; i < queries . size ( ) ; i ++ ) { cout << dp [ queries [ i ] ] << endl ; } } int main ( ) { n = 5 ; v [ 1 ] . push_back ( make_pair ( 4 , 4 ) ) ; v [ 4 ] . push_back ( make_pair ( 1 , 4 ) ) ; v [ 1 ] . push_back ( make_pair ( 2 , 2 ) ) ; v [ 2 ] . push_back ( make_pair ( 1 , 2 ) ) ; v [ 2 ] . push_back ( make_pair ( 3 , 3 ) ) ; v [ 3 ] . push_back ( make_pair ( 2 , 3 ) ) ; v [ 2 ] . push_back ( make_pair ( 5 , 5 ) ) ; v [ 5 ] . push_back ( make_pair ( 2 , 5 ) ) ; vector < int > queries = { 1 , 3 , 5 } ; answerQueries ( queries ) ; } |
Minimum changes required to make each path in a matrix palindrome | C ++ Program to implement the above approach ; Function for counting changes ; Maximum distance possible is ( n - 1 + m - 1 ) ; Stores the maximum element ; Update the maximum ; Stores frequencies of values for respective distances ; Initialize frequencies of cells as 0 ; Count frequencies of cell values in the matrix ; Increment frequency of value at distance i + j ; Store the most frequent value at i - th distance from ( 0 , 0 ) and ( N - 1 , M - 1 ) ; Calculate max frequency and total cells at distance i ; Count changes required to convert all cells at i - th distance to most frequent value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 7 NEW_LINE int countChanges ( int matrix [ ] [ N ] , int n , int m ) { int dist = n + m - 1 ; int Max_element = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { Max_element = max ( Max_element , matrix [ i ] [ j ] ) ; } } int freq [ dist ] [ Max_element + 1 ] ; for ( int i = 0 ; i < dist ; i ++ ) { for ( int j = 0 ; j < Max_element + 1 ; j ++ ) freq [ i ] [ j ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { freq [ i + j ] [ matrix [ i ] [ j ] ] ++ ; } } int min_changes_sum = 0 ; for ( int i = 0 ; i < dist / 2 ; i ++ ) { int maximum = 0 ; int total_values = 0 ; for ( int j = 0 ; j < Max_element + 1 ; j ++ ) { maximum = max ( maximum , freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ) ; total_values += freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ; } min_changes_sum += total_values - maximum ; } return min_changes_sum ; } int main ( ) { int mat [ ] [ N ] = { { 7 , 0 , 3 , 1 , 8 , 1 , 3 } , { 0 , 4 , 0 , 1 , 0 , 4 , 0 } , { 3 , 1 , 8 , 3 , 1 , 0 , 7 } } ; int minChanges = countChanges ( mat , 3 , 7 ) ; cout << minChanges ; return 0 ; } |
Count of numbers upto N having absolute difference of at most K between any two adjacent digits | C ++ program to get the count of numbers upto N having absolute difference at most K between any two adjacent digits ; Table to store solution of each subproblem ; Function to calculate all possible numbers ; Check if position reaches end that is is equal to length of N ; Check if the result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is false , means number has already become smaller so we can place any digit , otherwise N [ pos ] ; Chekc if start is false the number has not started yet ; Check if we do not start the number at pos then recur forward ; If we start the number we can place any digit from 1 to upper_limit ; Finding the new tight ; Condition if the number has already started ; We can place digit upto upperbound & absolute difference with previous digit much be atmost K ; Absolute difference atmost K ; Store the solution to this subproblem ; Driver code ; Initialising the table with - 1 ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long dp [ 1002 ] [ 10 ] [ 2 ] [ 2 ] ; long long possibleNumbers ( int pos , int previous , bool tight , bool start , string N , int K ) { if ( pos == N . length ( ) ) return 1 ; if ( dp [ pos ] [ previous ] [ tight ] [ start ] != -1 ) return dp [ pos ] [ previous ] [ tight ] [ start ] ; int res = 0 ; int upper_limit = ( tight ) ? ( N [ pos ] - '0' ) : 9 ; int new_tight ; if ( ! start ) { res = possibleNumbers ( pos + 1 , previous , false , false , N , K ) ; for ( int i = 1 ; i <= upper_limit ; i ++ ) { new_tight = ( tight && i == upper_limit ) ? 1 : 0 ; res += possibleNumbers ( pos + 1 , i , new_tight , true , N , K ) ; } } else { for ( int i = 0 ; i <= upper_limit ; i ++ ) { new_tight = ( tight && i == upper_limit ) ? 1 : 0 ; if ( abs ( i - previous ) <= K ) res += possibleNumbers ( pos + 1 , i , new_tight , true , N , K ) ; } } dp [ pos ] [ previous ] [ tight ] [ start ] = res ; return dp [ pos ] [ previous ] [ tight ] [ start ] ; } int main ( void ) { string N = "20" ; int K = 2 ; memset ( dp , -1 , sizeof dp ) ; cout << possibleNumbers ( 0 , 0 , true , false , N , K ) << endl ; } |
Minimum cost of reducing Array by merging any adjacent elements repetitively | C ++ program for the above approach ; Function to find the total minimum cost of merging two consecutive numbers ; Find the size of numbers [ ] ; If array is empty , return 0 ; To store the prefix Sum of numbers array numbers [ ] ; Traverse numbers [ ] to find the prefix sum ; dp table to memoised the value ; For single numbers cost is zero ; Iterate for length >= 1 ; Find sum in range [ i . . j ] ; Initialise dp [ i ] [ j ] to INT_MAX ; Iterate for all possible K to find the minimum cost ; Update the minimum sum ; Return the final minimum cost ; Driver Code ; Given set of numbers ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int mergeTwoNumbers ( vector < int > & numbers ) { int len , i , j , k ; int n = numbers . size ( ) ; if ( numbers . size ( ) == 0 ) { return 0 ; } vector < int > prefixSum ( n + 1 , 0 ) ; for ( int i = 1 ; i <= n ; i ++ ) { prefixSum [ i ] = prefixSum [ i - 1 ] + numbers [ i - 1 ] ; } vector < vector < int > > dp ( n + 1 , vector < int > ( n + 1 ) ) ; for ( int i = 1 ; i <= n ; i ++ ) { dp [ i ] [ i ] = 0 ; } for ( len = 2 ; len <= n ; len ++ ) { for ( i = 1 ; i <= n - len + 1 ; i ++ ) { j = i + len - 1 ; int sum = prefixSum [ j ] - prefixSum [ i - 1 ] ; dp [ i ] [ j ] = INT_MAX ; for ( k = i ; k < j ; k ++ ) { dp [ i ] [ j ] = min ( dp [ i ] [ j ] , dp [ i ] [ k ] + dp [ k + 1 ] [ j ] + sum ) ; } } } return dp [ 1 ] [ n ] ; } int main ( ) { vector < int > arr1 = { 6 , 4 , 4 , 6 } ; cout << mergeTwoNumbers ( arr1 ) << endl ; return 0 ; } |
Maximum sum possible for every node by including it in a segment of N | C ++ program to calculate the maximum sum possible for every node by including it in a segment of the N - Ary Tree ; Stores the maximum sum possible for every node by including them in a segment with their successors ; Stores the maximum sum possible for every node by including them in a segment with their ancestors ; Store the maximum sum for every node by including it in a segment with its successors ; Update the maximum sums for each node by including them in a sequence with their ancestors ; Condition to check , if current node is not root ; Add edges ; Function to find the maximum answer for each node ; Compute the maximum sums with successors ; Store the computed maximums ; Update the maximum sums by including their ancestors ; Print the desired result ; Driver Program ; Number of nodes ; graph ; Add edges ; Weight of each node ; Compute the max sum of segments for each node ; Print the answer for every node | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp1 [ 100005 ] ; int dp2 [ 100005 ] ; void dfs1 ( int u , int par , vector < int > g [ ] , int weight [ ] ) { dp1 [ u ] = weight [ u ] ; for ( auto c : g [ u ] ) { if ( c != par ) { dfs1 ( c , u , g , weight ) ; dp1 [ u ] += max ( 0 , dp1 ) ; } } } void dfs2 ( int u , int par , vector < int > g [ ] , int weight [ ] ) { if ( par != 0 ) { int maxSumAncestors = dp2 [ par ] - max ( 0 , dp1 [ u ] ) ; dp2 [ u ] = dp1 [ u ] + max ( 0 , maxSumAncestors ) ; } for ( auto c : g [ u ] ) { if ( c != par ) { dfs2 ( c , u , g , weight ) ; } } } void addEdge ( int u , int v , vector < int > g [ ] ) { g [ u ] . push_back ( v ) ; g [ v ] . push_back ( u ) ; } void maxSumSegments ( vector < int > g [ ] , int weight [ ] , int n ) { dfs1 ( 1 , 0 , g , weight ) ; for ( int i = 1 ; i <= n ; i ++ ) { dp2 [ i ] = dp1 [ i ] ; } dfs2 ( 1 , 0 , g , weight ) ; } void printAns ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) { cout << dp2 [ i ] << " β " ; } } int main ( ) { int n = 6 ; int u , v ; vector < int > g [ 100005 ] ; addEdge ( 1 , 2 , g ) ; addEdge ( 1 , 3 , g ) ; addEdge ( 2 , 4 , g ) ; addEdge ( 2 , 5 , g ) ; addEdge ( 3 , 6 , g ) ; addEdge ( 4 , 7 , g ) ; int weight [ n + 1 ] ; weight [ 1 ] = -8 ; weight [ 2 ] = 9 ; weight [ 3 ] = 7 ; weight [ 4 ] = -4 ; weight [ 5 ] = 5 ; weight [ 6 ] = -10 ; weight [ 7 ] = -6 ; maxSumSegments ( g , weight , n ) ; printAns ( n ) ; return 0 ; } |
Count array elements that can be maximized by adding any permutation of first N natural numbers | C ++ program for the above approach ; Function to get the count of values that can have the maximum value ; Sort array in decreasing order ; Stores the answer ; mark stores the maximum value till each index i ; Check if arr [ i ] can be maximum ; Update the mark ; Print the total count ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool cmp ( int x , int y ) { return x > y ; } void countMaximum ( int * a , int n ) { sort ( a , a + n , cmp ) ; int count = 0 ; int mark = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( ( a [ i ] + n >= mark ) ) { count += 1 ; } mark = max ( mark , a [ i ] + i + 1 ) ; } cout << count ; } int main ( ) { int arr [ ] = { 8 , 9 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countMaximum ( arr , N ) ; } |
Count of pairs in an Array with same number of set bits | C ++ Program to count possible number of pairs of elements with same number of set bits . ; Function to return the count of Pairs ; Get the maximum element ; Array to store count of bits of all elements upto maxm ; Store the set bits for powers of 2 ; Compute the set bits for the remaining elements ; Store the frequency of respective counts of set bits ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int N ) { int maxm = * max_element ( arr , arr + N ) ; int i , k ; int bitscount [ maxm + 1 ] = { 0 } ; for ( i = 1 ; i <= maxm ; i *= 2 ) bitscount [ i ] = 1 ; for ( i = 1 ; i <= maxm ; i ++ ) { if ( bitscount [ i ] == 1 ) k = i ; if ( bitscount [ i ] == 0 ) { bitscount [ i ] = bitscount [ k ] + bitscount [ i - k ] ; } } map < int , int > setbits ; for ( int i = 0 ; i < N ; i ++ ) { setbits [ bitscount [ arr [ i ] ] ] ++ ; } int ans = 0 ; for ( auto it : setbits ) { ans += it . second * ( it . second - 1 ) / 2 ; } return ans ; } int main ( ) { int N = 12 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 } ; cout << countPairs ( arr , N ) ; return 0 ; } |
Largest subarray sum of all connected components in undirected graph | C ++ implementation to find largest subarray sum among all connected components ; Function to traverse the undirected graph using the Depth first traversal ; Marking the visited vertex as true ; Store the connected chain ; Recursive call to the DFS algorithm ; Function to return maximum subarray sum of each connected component using Kadane 's Algorithm ; Following loop finds maximum subarray sum based on Kadane 's algorithm ; Global maximum subarray sum ; Returning the sum ; Function to find the maximum subarray sum among all connected components ; Initializing boolean array to mark visited vertices ; maxSum stores the maximum subarray sum ; Following loop invokes DFS algorithm ; Variable to hold temporary length ; Variable to hold temporary maximum subarray sum values ; Container to store each chain ; DFS algorithm ; Variable to hold each chain size ; Container to store values of vertices of individual chains ; Storing the values of each chain ; Function call to find maximum subarray sum of current connection ; Conditional to store current maximum subarray sum ; Printing global maximum subarray sum ; Driver code ; Initializing graph in the form of adjacency list ; Defining the number of edges and vertices ; Assigning the values for each vertex of the undirected graph ; Constructing the undirected graph | #include <bits/stdc++.h> NEW_LINE using namespace std ; void depthFirst ( int v , vector < int > graph [ ] , vector < bool > & visited , vector < int > & storeChain ) { visited [ v ] = true ; storeChain . push_back ( v ) ; for ( auto i : graph [ v ] ) { if ( visited [ i ] == false ) { depthFirst ( i , graph , visited , storeChain ) ; } } } int subarraySum ( int arr [ ] , int n ) { int maxSubarraySum = arr [ 0 ] ; int currentMax = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { currentMax = max ( arr [ i ] , arr [ i ] + currentMax ) ; maxSubarraySum = max ( maxSubarraySum , currentMax ) ; } return maxSubarraySum ; } void maxSubarraySum ( vector < int > graph [ ] , int vertices , vector < int > values ) { vector < bool > visited ( 1001 , false ) ; int maxSum = INT_MIN ; for ( int i = 1 ; i <= vertices ; i ++ ) { if ( visited [ i ] == false ) { int sizeChain ; int tempSum ; vector < int > storeChain ; depthFirst ( i , graph , visited , storeChain ) ; sizeChain = storeChain . size ( ) ; int chainValues [ sizeChain + 1 ] ; for ( int i = 0 ; i < sizeChain ; i ++ ) { int temp = values [ storeChain [ i ] - 1 ] ; chainValues [ i ] = temp ; } tempSum = subarraySum ( chainValues , sizeChain ) ; if ( tempSum > maxSum ) { maxSum = tempSum ; } } } cout << " Maximum β subarray β sum β among β all β " ; cout << " connected β components β = β " ; cout << maxSum ; } int main ( ) { vector < int > graph [ 1001 ] ; int E , V ; E = 4 ; V = 7 ; vector < int > values ; values . push_back ( 3 ) ; values . push_back ( 2 ) ; values . push_back ( 4 ) ; values . push_back ( -2 ) ; values . push_back ( 0 ) ; values . push_back ( -1 ) ; values . push_back ( -5 ) ; graph [ 1 ] . push_back ( 2 ) ; graph [ 2 ] . push_back ( 1 ) ; graph [ 3 ] . push_back ( 4 ) ; graph [ 4 ] . push_back ( 3 ) ; graph [ 4 ] . push_back ( 5 ) ; graph [ 5 ] . push_back ( 4 ) ; graph [ 6 ] . push_back ( 7 ) ; graph [ 7 ] . push_back ( 6 ) ; maxSubarraySum ( graph , V , values ) ; return 0 ; } |
Count of Binary strings of length N having atmost M consecutive 1 s or 0 s alternatively exactly K times | C ++ program to find the count of Binary strings of length N having atmost M consecutive 1 s or 0 s alternatively exactly K times ; Array to contain the final result ; Function to get the number of desirable binary strings ; if we reach end of string and groups are exhausted , return 1 ; if length is exhausted but groups are still to be made , return 0 ; if length is not exhausted but groups are exhausted , return 0 ; if both are negative just return 0 ; if already calculated , return it ; initialise answer for each state ; loop through every possible m ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 1000 ] [ 1000 ] ; int solve ( int n , int k , int m ) { if ( n == 0 && k == 0 ) return 1 ; if ( n == 0 && k != 0 ) return 0 ; if ( n != 0 && k == 0 ) return 0 ; if ( n < 0 k < 0 ) return 0 ; if ( dp [ n ] [ k ] ) return dp [ n ] [ k ] ; int ans = 0 ; for ( int j = 1 ; j <= m ; j ++ ) { ans += solve ( n - j , k - 1 , m ) ; } return dp [ n ] [ k ] = ans ; } int main ( ) { int N = 7 , K = 4 , M = 3 ; cout << solve ( N , K , M ) ; } |
Maximum neighbor element in a matrix within distance K | C ++ implementation to find the maximum neighbor element within the distance of less than K ; Function to print the matrix ; Loop to iterate over the matrix ; Function to find the maximum neighbor within the distance of less than equal to K ; Loop to find the maximum element within the distance of less than K ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printMatrix ( vector < vector < int > > A ) { for ( int i = 0 ; i < A . size ( ) ; i ++ ) { for ( int j = 0 ; j < A [ 0 ] . size ( ) ; j ++ ) cout << A [ i ] [ j ] << ' β ' ; cout << ' ' ; } } vector < vector < int > > getMaxNeighbour ( vector < vector < int > > & A , int K ) { vector < vector < int > > ans = A ; for ( int q = 1 ; q <= K ; q ++ ) { for ( int i = 0 ; i < A . size ( ) ; i ++ ) { for ( int j = 0 ; j < A [ 0 ] . size ( ) ; j ++ ) { int maxi = ans [ i ] [ j ] ; if ( i > 0 ) maxi = max ( maxi , ans [ i - 1 ] [ j ] ) ; if ( j > 0 ) maxi = max ( maxi , ans [ i ] [ j - 1 ] ) ; if ( i < A . size ( ) - 1 ) maxi = max ( maxi , ans [ i + 1 ] [ j ] ) ; if ( j < A [ 0 ] . size ( ) - 1 ) maxi = max ( maxi , ans [ i ] [ j + 1 ] ) ; A [ i ] [ j ] = maxi ; } } ans = A ; } return ans ; } int main ( ) { vector < vector < int > > B = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printMatrix ( getMaxNeighbour ( B , 2 ) ) ; return 0 ; } |
Number of distinct ways to represent a number as sum of K unique primes | C ++ program to count the Number of distinct ways to represent a number as K different primes ; Prime vector ; Sieve array of prime ; DP array ; Initialise all numbers as prime ; Sieve of Eratosthenes . ; Push all the primes into prime vector ; Function to get the number of distinct ways to get sum as K different primes ; If index went out of prime array size or the sum became larger than n return 0 ; If sum becomes equal to n and j becomes exactly equal to k . Return 1 , else if j is still not equal to k , return 0 ; If sum != n and still j as exceeded , return 0 ; If that state is already calculated , return directly the ans ; Include the current prime ; Exclude the current prime ; Return by memoizing the ans ; Driver code ; Precompute primes by sieve | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > prime ; bool isprime [ 1000 ] ; int dp [ 200 ] [ 20 ] [ 1000 ] ; void sieve ( ) { memset ( isprime , true , sizeof ( isprime ) ) ; for ( int i = 2 ; i * i <= 1000 ; i ++ ) { if ( isprime [ i ] ) { for ( int j = i * i ; j <= 1000 ; j += i ) { isprime [ j ] = false ; } } } for ( int i = 2 ; i <= 1000 ; i ++ ) { if ( isprime [ i ] ) { prime . push_back ( i ) ; } } } int CountWays ( int i , int j , int sum , int n , int k ) { if ( i > prime . size ( ) sum > n ) { return 0 ; } if ( sum == n ) { if ( j == k ) { return 1 ; } return 0 ; } if ( j == k ) return 0 ; if ( dp [ i ] [ j ] [ sum ] ) return dp [ i ] [ j ] [ sum ] ; int inc = 0 , exc = 0 ; inc = CountWays ( i + 1 , j + 1 , sum + prime [ i ] , n , k ) ; exc = CountWays ( i + 1 , j , sum , n , k ) ; return dp [ i ] [ j ] [ sum ] = inc + exc ; } int main ( ) { sieve ( ) ; int N = 100 , K = 5 ; cout << CountWays ( 0 , 0 , 0 , N , K ) ; } |
Count minimum factor jumps required to reach the end of an Array | C ++ program for bottom up approach ; Vector to store factors of each integer ; Initialize the dp array ; Precompute all the factors of every integer ; Function to count the minimum factor jump ; Initialise minimum jumps to reach each cell as INT_MAX ; 0 jumps required to reach the first cell ; Iterate over all cells ; calculating for each jump ; If a cell is in bound ; Return minimum jumps to reach last cell ; Driver code ; Pre - calculating the factors ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > factors [ 100005 ] ; int dp [ 100005 ] ; void precompute ( ) { for ( int i = 1 ; i <= 100000 ; i ++ ) { for ( int j = i ; j <= 100000 ; j += i ) factors [ j ] . push_back ( i ) ; } } int solve ( int arr [ ] , int n ) { for ( int i = 0 ; i <= 100005 ; i ++ ) { dp [ i ] = INT_MAX ; } dp [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( auto j : factors [ arr [ i ] ] ) { if ( i + j < n ) dp [ i + j ] = min ( dp [ i + j ] , 1 + dp [ i ] ) ; } } return dp [ n - 1 ] ; } int main ( ) { precompute ( ) ; int arr [ ] = { 2 , 8 , 16 , 55 , 99 , 100 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << solve ( arr , n ) ; } |
Find the length of the Largest subset such that all elements are Pairwise Coprime | C ++ implementation to Find the length of the Largest subset such that all elements are Pairwise Coprime ; Dynamic programming table ; Function to obtain the mask for any integer ; List of prime numbers till 50 ; Iterate through all prime numbers to obtain the mask ; Set this prime 's bit ON in the mask ; Return the mask value ; Function to count the number of ways ; Check if subproblem has been solved ; Excluding current element in the subset ; Check if there are no common prime factors then only this element can be included ; Calculate the new mask if this element is included ; Store and return the answer ; Function to find the count of subarray with all digits unique ; Initializing dp ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 5000 ] [ ( 1 << 10 ) + 5 ] ; int getmask ( int val ) { int mask = 0 ; int prime [ 15 ] = { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 } ; for ( int i = 0 ; i < 15 ; i ++ ) { if ( val % prime [ i ] == 0 ) { mask = mask | ( 1 << i ) ; } } return mask ; } int calculate ( int pos , int mask , int a [ ] , int n ) { if ( pos == n || mask == ( 1 << n - 1 ) ) return 0 ; if ( dp [ pos ] [ mask ] != -1 ) return dp [ pos ] [ mask ] ; int size = 0 ; size = max ( size , calculate ( pos + 1 , mask , a , n ) ) ; if ( ( getmask ( a [ pos ] ) & mask ) == 0 ) { int new_mask = ( mask | ( getmask ( a [ pos ] ) ) ) ; size = max ( size , 1 + calculate ( pos + 1 , new_mask , a , n ) ) ; } return dp [ pos ] [ mask ] = size ; } int largestSubset ( int a [ ] , int n ) { memset ( dp , -1 , sizeof ( dp ) ) ; return calculate ( 0 , 0 , a , n ) ; } int main ( ) { int A [ ] = { 2 , 3 , 13 , 5 , 14 , 6 , 7 , 11 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << largestSubset ( A , N ) ; return 0 ; } |
Maximum sum such that exactly half of the elements are selected and no two adjacent | C ++ program to find maximum sum possible such that exactly floor ( N / 2 ) elements are selected and no two selected elements are adjacent to each other ; Function return the maximum sum possible under given condition ; Base case ; When i is odd ; When i is even ; Maximum of if we pick last element or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaximumSum ( int a [ ] , int n ) { int dp [ n + 1 ] [ 2 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 2 ] [ 1 ] = a [ 1 ] ; dp [ 2 ] [ 0 ] = a [ 0 ] ; for ( int i = 3 ; i < n + 1 ; i ++ ) { if ( i & 1 ) { int temp = max ( { dp [ i - 3 ] [ 1 ] , dp [ i - 3 ] [ 0 ] , dp [ i - 2 ] [ 1 ] , dp [ i - 2 ] [ 0 ] } ) ; dp [ i ] [ 1 ] = a [ i - 1 ] + temp ; dp [ i ] [ 0 ] = max ( { a [ i - 2 ] + dp [ i - 2 ] [ 0 ] , a [ i - 2 ] + dp [ i - 3 ] [ 1 ] , a [ i - 2 ] + dp [ i - 3 ] [ 0 ] , a [ i - 3 ] + dp [ i - 3 ] [ 0 ] } ) ; } else { dp [ i ] [ 1 ] = a [ i - 1 ] + max ( { dp [ i - 2 ] [ 1 ] , dp [ i - 2 ] [ 0 ] , dp [ i - 1 ] [ 0 ] } ) ; dp [ i ] [ 0 ] = a [ i - 2 ] + dp [ i - 2 ] [ 0 ] ; } } return max ( dp [ n ] [ 1 ] , dp [ n ] [ 0 ] ) ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << MaximumSum ( A , N ) ; return 0 ; } |
Optimal Strategy for the Divisor game using Dynamic Programming | C ++ program for implementation of Optimal Strategy for the Divisor Game using Dynamic Programming ; Recursive function to find the winner ; check if N = 1 or N = 3 then player B wins ; check if N = 2 then player A wins ; check if current state already visited then return the previously obtained ans ; check if currently it is player A 's turn then initialise the ans to 0 ; Traversing across all the divisors of N which are less than N ; check if current value of i is a divisor of N ; check if it is player A 's turn then we need at least one true ; Else if it is player B 's turn then we need at least one false ; Return the current ans ; Driver code ; initialise N | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool divisorGame ( int N , bool A , int dp [ ] [ 2 ] ) { if ( N == 1 or N == 3 ) return false ; if ( N == 2 ) return true ; if ( dp [ N ] [ A ] != -1 ) return dp [ N ] [ A ] ; int ans = ( A == 1 ) ? 0 : 1 ; for ( int i = 1 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { if ( A ) ans |= divisorGame ( N - i , 0 , dp ) ; else ans &= divisorGame ( N - i , 1 , dp ) ; } } return dp [ N ] [ A ] = ans ; } int main ( ) { int N = 3 ; int dp [ N + 1 ] [ 2 ] ; memset ( dp , -1 , sizeof ( dp ) ) ; if ( divisorGame ( N , 1 , dp ) == true ) cout << " Player β A β wins " ; else cout << " Player β B β wins " ; return 0 ; } |
Find the count of mountains in a given Matrix | C ++ program find the count of mountains in a given Matrix ; Function to count number of mountains in a given matrix of size n ; form another matrix with one extra layer of border elements . Border elements will contain INT_MIN value . ; For border elements , set value as INT_MIN ; For rest elements , just copy it into new matrix ; Check for mountains in the modified matrix ; check for all directions ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; int countMountains ( int a [ ] [ MAX ] , int n ) { int A [ n + 2 ] [ n + 2 ] ; int count = 0 ; for ( int i = 0 ; i < n + 2 ; i ++ ) { for ( int j = 0 ; j < n + 2 ; j ++ ) { if ( ( i == 0 ) || ( j == 0 ) || ( i == n + 1 ) || ( j == n + 1 ) ) { A [ i ] [ j ] = INT_MIN ; } else { A [ i ] [ j ] = a [ i - 1 ] [ j - 1 ] ; } } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( ( A [ i ] [ j ] > A [ i - 1 ] [ j ] ) && ( A [ i ] [ j ] > A [ i + 1 ] [ j ] ) && ( A [ i ] [ j ] > A [ i ] [ j - 1 ] ) && ( A [ i ] [ j ] > A [ i ] [ j + 1 ] ) && ( A [ i ] [ j ] > A [ i - 1 ] [ j - 1 ] ) && ( A [ i ] [ j ] > A [ i + 1 ] [ j + 1 ] ) && ( A [ i ] [ j ] > A [ i - 1 ] [ j + 1 ] ) && ( A [ i ] [ j ] > A [ i + 1 ] [ j - 1 ] ) ) { count ++ ; } } } return count ; } int main ( ) { int a [ ] [ MAX ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int n = 3 ; cout << countMountains ( a , n ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.