text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Find the String having each substring with exactly K distinct characters | C ++ Program to Find the String having each substring with exactly K distinct characters ; Function to find the required output string ; Each element at index i is modulus of K ; Driver code ; initialise integers N and K
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findString ( int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { cout << char ( ' A ' + i % K ) ; } } int main ( ) { int N = 10 ; int K = 3 ; findString ( N , K ) ; return 0 ; }
Find total no of collisions taking place between the balls in which initial direction of each ball is given | C ++ implementation to Find total no of collisions taking place between the balls in which initial direction of each ball is given ; Function to count no of collision ; length of the string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( string s ) { int N , i , cnt = 0 , ans = 0 ; N = s . length ( ) ; for ( i = 0 ; i < N ; i ++ ) { if ( s [ i ] == ' R ' ) cnt ++ ; if ( s [ i ] == ' L ' ) ans += cnt ; } return ans ; } int main ( ) { string s = " RRLL " ; cout << count ( s ) << endl ; return 0 ; }
Maximum number on 7 | C ++ implementation to find the maximum number that can be using the N segments in N segments display ; Function to find the maximum number that can be displayed using the N segments ; Condition to check base case ; Condition to check if the number is even ; Condition to check if the number is odd ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void segments ( int n ) { if ( n == 1 n == 0 ) { return ; } if ( n % 2 == 0 ) { cout << "1" ; segments ( n - 2 ) ; } else if ( n % 2 == 1 ) { cout << "7" ; segments ( n - 3 ) ; } } int main ( ) { int n ; n = 11 ; segments ( n ) ; return 0 ; }
Minimum number of subsequences required to convert one string to another using Greedy Algorithm | C ++ implementation for minimum number of subsequences required to convert one string to another ; Function to find the minimum number of subsequences required to convert one string to another S2 == A and S1 == B ; At least 1 subsequence is required Even in best case , when A is same as B ; size of B ; size of A ; Create an 2D array next [ ] [ ] of size 26 * sizeOfB to store the next occurrence of a character ( ' a ' to ' z ' ) as an index [ 0 , sizeOfA - 1 ] ; Array Initialization with infinite ; Loop to Store the values of index ; If the value of next [ i ] [ j ] is infinite then update it with next [ i ] [ j + 1 ] ; Greedy algorithm to obtain the maximum possible subsequence of B to cover the remaining string of A using next subsequence ; Loop to iterate over the string A ; Condition to check if the character is not present in the string B ; Condition to check if there is an element in B matching with character A [ i ] on or next to B [ pos ] given by next [ A [ i ] - ' a ' ] [ pos ] ; Condition to check if reached at the end of B or no such element exists on or next to A [ pos ] , thus increment number by one and reinitialise pos to zero ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int findMinimumSubsequences ( string A , string B ) { int numberOfSubsequences = 1 ; int sizeOfB = B . size ( ) ; int sizeOfA = A . size ( ) ; int inf = 1000000 ; int next [ 26 ] [ sizeOfB ] ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < sizeOfB ; j ++ ) { next [ i ] [ j ] = inf ; } } for ( int i = 0 ; i < sizeOfB ; i ++ ) { next [ B [ i ] - ' a ' ] [ i ] = i ; } for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = sizeOfB - 2 ; j >= 0 ; j -- ) { if ( next [ i ] [ j ] == inf ) { next [ i ] [ j ] = next [ i ] [ j + 1 ] ; } } } int pos = 0 ; int i = 0 ; while ( i < sizeOfA ) { if ( pos == 0 && next [ A [ i ] - ' a ' ] [ pos ] == inf ) { numberOfSubsequences = -1 ; break ; } else if ( pos < sizeOfB && next [ A [ i ] - ' a ' ] [ pos ] < inf ) { int nextIndex = next [ A [ i ] - ' a ' ] [ pos ] + 1 ; pos = nextIndex ; i ++ ; } else { numberOfSubsequences ++ ; pos = 0 ; } } return numberOfSubsequences ; } int main ( ) { string A = " aacbe " ; string B = " aceab " ; cout << findMinimumSubsequences ( A , B ) ; return 0 ; }
Vertical and Horizontal retrieval ( MRT ) on Tapes | C ++ program to print Horizontal filling ; It is used for checking whether tape is full or not ; It is used for calculating total retrieval time ; It is used for calculating mean retrieval time ; vector is used because n number of records can insert in one tape with size constraint ; Null vector obtained to use fresh vector ' v ' ; initialize variables to 0 for each iteration ; sum is used for checking whether i 'th tape is full or not ; check sum less than size of tape ; increment in j for next record ; calculating total retrieval time ; MRT formula ; calculating mean retrieval time using formula ; v . size ( ) is function of vector is used to get size of vector ; Driver Code ; store the size of records [ ] ; store the size of tapes [ ] ; sorting of an array is required to attain greedy approach of algorithm
#include <bits/stdc++.h> NEW_LINE using namespace std ; void horizontalFill ( int records [ ] , int tape [ ] , int nt ) { int sum = 0 ; int Retrieval_Time = 0 ; double Mrt ; int current = 0 ; vector < int > v ; for ( int i = 0 ; i < nt ; i ++ ) { v . clear ( ) ; Retrieval_Time = 0 ; sum = 0 ; cout << " tape ▁ " << i + 1 << " ▁ : ▁ [ ▁ " ; sum += records [ current ] ; while ( sum <= tape [ i ] ) { cout << records [ current ] << " ▁ " ; v . push_back ( records [ current ] ) ; current ++ ; sum += records [ current ] ; } cout << " ] " ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { Retrieval_Time += v [ i ] * ( v . size ( ) - i ) ; } Mrt = ( double ) Retrieval_Time / v . size ( ) ; cout << " TABSYMBOL MRT ▁ : ▁ " << Mrt << endl ; } } int main ( ) { int records [ ] = { 15 , 2 , 8 , 23 , 45 , 50 , 60 , 120 } ; int tape [ ] = { 25 , 80 , 160 } ; int n = sizeof ( records ) / sizeof ( records [ 0 ] ) ; int m = sizeof ( tape ) / sizeof ( tape [ 0 ] ) ; sort ( records , records + n ) ; horizontalFill ( records , tape , m ) ; }
Circular Convolution using Matrix Method | C ++ program to compute circular convolution of two arrays ; Function to find circular convolution ; Finding the maximum size between the two input sequence sizes ; Copying elements of x to row_vec and padding zeros if size of x < maxSize ; Copying elements of h to col_vec and padding zeros if size of h is less than maxSize ; Generating 2D matrix of circularly shifted elements ; Computing result by matrix multiplication and printing results ; Driver program
#include <iostream> NEW_LINE using namespace std ; #define MAX_SIZE 10 NEW_LINE void convolution ( int * x , int * h , int n , int m ) { int row_vec [ MAX_SIZE ] , col_vec [ MAX_SIZE ] ; int out [ MAX_SIZE ] = { 0 } ; int circular_shift_mat [ MAX_SIZE ] [ MAX_SIZE ] ; int maxSize = n > m ? n : m ; for ( int i = 0 ; i < maxSize ; i ++ ) { if ( i >= n ) { row_vec [ i ] = 0 ; } else { row_vec [ i ] = x [ i ] ; } } for ( int i = 0 ; i < maxSize ; i ++ ) { if ( i >= m ) { col_vec [ i ] = 0 ; } else { col_vec [ i ] = h [ i ] ; } } int k = 0 , d = 0 ; for ( int i = 0 ; i < maxSize ; i ++ ) { int curIndex = k - d ; for ( int j = 0 ; j < maxSize ; j ++ ) { circular_shift_mat [ j ] [ i ] = row_vec [ curIndex % maxSize ] ; curIndex ++ ; } k = maxSize ; d ++ ; } for ( int i = 0 ; i < maxSize ; i ++ ) { for ( int j = 0 ; j < maxSize ; j ++ ) { out [ i ] += circular_shift_mat [ i ] [ j ] * col_vec [ j ] ; } cout << out [ i ] << " ▁ " ; } } int main ( ) { int x [ ] = { 5 , 7 , 3 , 2 } ; int n = sizeof ( x ) / sizeof ( int ) ; int h [ ] = { 1 , 5 } ; int m = sizeof ( h ) / sizeof ( int ) ; convolution ( x , h , n , m ) ; return 0 ; }
Maximize the number of palindromic Strings | C ++ program for the above approach ; To check if there is any string of odd length ; If there is at least 1 string of odd length . ; If all the strings are of even length . ; Count of 0 's in all the strings ; Count of 1 's in all the strings ; If z is even and o is even then ans will be N . ; Otherwise ans will be N - 1. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max_palindrome ( string s [ ] , int n ) { int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] . size ( ) % 2 != 0 ) { flag = 1 ; } } if ( flag == 1 ) { return n ; } int z = 0 , o = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < s [ i ] . size ( ) ; j ++ ) { if ( s [ i ] [ j ] == '0' ) z ++ ; else o ++ ; } } if ( o % 2 == 0 && z % 2 == 0 ) { return n ; } else { return n - 1 ; } } int main ( ) { int n = 3 ; string s [ n ] = { "1110" , "100110" , "010101" } ; cout << max_palindrome ( s , n ) ; return 0 ; }
Minimum possible travel cost among N cities | C ++ implementation of the approach ; Function to return the minimum cost to travel from the first city to the last ; To store the total cost ; Start from the first city ; If found any city with cost less than that of the previous boarded bus then change the bus ; Calculate the cost to travel from the currently boarded bus till the current city ; Update the currently boarded bus ; Finally calculate the cost for the last boarding bus till the ( N + 1 ) th city ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( vector < int > & cost , int n ) { int totalCost = 0 ; int boardingBus = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( cost [ boardingBus ] > cost [ i ] ) { totalCost += ( ( i - boardingBus ) * cost [ boardingBus ] ) ; boardingBus = i ; } } totalCost += ( ( n - boardingBus ) * cost [ boardingBus ] ) ; return totalCost ; } int main ( ) { vector < int > cost { 4 , 7 , 8 , 3 , 4 } ; int n = cost . size ( ) ; cout << minCost ( cost , n ) ; return 0 ; }
Minimum cells to be flipped to get a 2 * 2 submatrix with equal elements | C ++ implementation of the approach ; Function to return the minimum flips required such that the submatrix from mat [ i ] [ j ] to mat [ i + 1 ] [ j + 1 ] contains all equal elements ; Function to return the minimum number of slips required such that the matrix contains at least a single submatrix of size 2 * 2 with all equal elements ; To store the result ; For every submatrix of size 2 * 2 ; Update the count of flips required for the current submatrix ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minFlipsSub ( string mat [ ] , int i , int j ) { int cnt0 = 0 , cnt1 = 0 ; if ( mat [ i ] [ j ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i ] [ j + 1 ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i + 1 ] [ j ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i + 1 ] [ j + 1 ] == '1' ) cnt1 ++ ; else cnt0 ++ ; return min ( cnt0 , cnt1 ) ; } int minFlips ( string mat [ ] , int r , int c ) { int res = INT_MAX ; for ( int i = 0 ; i < r - 1 ; i ++ ) { for ( int j = 0 ; j < c - 1 ; j ++ ) { res = min ( res , minFlipsSub ( mat , i , j ) ) ; } } return res ; } int main ( ) { string mat [ ] = { "0101" , "0101" , "0101" } ; int r = sizeof ( mat ) / sizeof ( string ) ; int c = mat [ 0 ] . length ( ) ; cout << minFlips ( mat , r , c ) ; return 0 ; }
Count set bits in the Kth number after segregating even and odd from N natural numbers | C ++ implementation of the approach ; Function to return the kth element of the Odd - Even sequence of length n ; Finding the index from where the even numbers will be stored ; Return the kth element ; Function to return the count of set bits in the kth number of the odd even sequence of length n ; Required kth number ; Return the count of set bits ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findK ( int n , int k ) { int pos ; if ( n % 2 == 0 ) { pos = n / 2 ; } else { pos = ( n / 2 ) + 1 ; } if ( k <= pos ) { return ( k * 2 - 1 ) ; } else return ( ( k - pos ) * 2 ) ; } int countSetBits ( int n , int k ) { int kth = findK ( n , k ) ; return __builtin_popcount ( kth ) ; } int main ( ) { int n = 18 , k = 12 ; cout << countSetBits ( n , k ) ; return 0 ; }
Minimum cost to convert str1 to str2 with the given operations | C ++ implementation of the approach ; Function to return the minimum cost to convert str1 to sr2 ; For every character of str1 ; If current character is not equal in both the strings ; If the next character is also different in both the strings then these characters can be swapped ; Change the current character ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( string str1 , string str2 , int n ) { int cost = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str1 [ i ] != str2 [ i ] ) { if ( i < n - 1 && str1 [ i + 1 ] != str2 [ i + 1 ] ) { swap ( str1 [ i ] , str1 [ i + 1 ] ) ; cost ++ ; } else { cost ++ ; } } } return cost ; } int main ( ) { string str1 = " abb " , str2 = " bba " ; int n = str1 . length ( ) ; cout << minCost ( str1 , str2 , n ) ; return 0 ; }
Partition first N natural number into two sets such that their sum is not coprime | C ++ implementation of the approach ; Function to find the required sets ; Impossible case ; Sum of first n - 1 natural numbers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find_set ( int n ) { if ( n <= 2 ) { cout << " - 1" ; return ; } int sum1 = ( n * ( n - 1 ) ) / 2 ; int sum2 = n ; cout << sum1 << " ▁ " << sum2 ; } int main ( ) { int n = 8 ; find_set ( n ) ; return 0 ; }
Count common elements in two arrays containing multiples of N and M | C ++ implementation of the above approach ; Recursive function to find gcd using euclidean algorithm ; Function to find lcm of two numbers using gcd ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int lcm ( int n , int m ) { return ( n * m ) / gcd ( n , m ) ; } int main ( ) { int n = 2 , m = 3 , k = 5 ; cout << k / lcm ( n , m ) << endl ; return 0 ; }
Check whether a subsequence exists with sum equal to k if arr [ i ] > 2 * arr [ i | C ++ implementation of above approach ; Function to check whether sum of any set of the array element is equal to k or not ; Traverse the array from end to start ; if k is greater than arr [ i ] then subtract it from k ; If there is any subsequence whose sum is equal to k ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool CheckForSequence ( int arr [ ] , int n , int k ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( k >= arr [ i ] ) k -= arr [ i ] ; } if ( k != 0 ) return false ; else return true ; } int main ( ) { int A [ ] = { 1 , 3 , 7 , 15 , 31 } ; int n = sizeof ( A ) / sizeof ( int ) ; cout << ( CheckForSequence ( A , n , 18 ) ? " True " : " False " ) << endl ; return 0 ; }
Maximum possible sub | C ++ implementation of the approach ; Function to return the maximum sub - array sum after at most x swaps ; To store the required answer ; For all possible intervals ; Keep current ans as zero ; To store the integers which are not part of the sub - array currently under consideration ; To store elements which are part of the sub - array currently under consideration ; Create two sets ; Swap at most X elements ; Remove the minimum of the taken elements ; Add maximum of the discarded elements ; Update the answer ; Return the maximized sub - array sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int SubarraySum ( int a [ ] , int n , int x ) { int ans = -10000 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { int curans = 0 ; priority_queue < int , vector < int > > pq ; priority_queue < int , vector < int > , greater < int > > pq2 ; for ( int k = 0 ; k < n ; k ++ ) { if ( k >= i && k <= j ) { curans += a [ k ] ; pq2 . push ( a [ k ] ) ; } else pq . push ( a [ k ] ) ; } ans = max ( ans , curans ) ; for ( int k = 1 ; k <= x ; k ++ ) { if ( pq . empty ( ) || pq2 . empty ( ) || pq2 . top ( ) >= pq . top ( ) ) break ; curans -= pq2 . top ( ) ; pq2 . pop ( ) ; curans += pq . top ( ) ; pq . pop ( ) ; ans = max ( ans , curans ) ; } } } return ans ; } int main ( ) { int a [ ] = { 5 , -1 , 2 , 3 , 4 , -2 , 5 } , x = 2 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << SubarraySum ( a , n , x ) ; return 0 ; }
Generate an array of size K which satisfies the given conditions | C ++ implementation of the approach ; Function to generate and print the required array ; Initializing the array ; Finding r ( from above approach ) ; If r < 0 ; Finding ceiling and floor values ; Fill the array with ceiling values ; Fill the array with floor values ; Add 1 , 2 , 3 , ... with corresponding values ; There is no solution for below cases ; Modify A [ 1 ] and A [ k - 1 ] to get the required array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void generateArray ( int n , int k ) { vector < int > array ( k , 0 ) ; int remaining = n - int ( k * ( k + 1 ) / 2 ) ; if ( remaining < 0 ) cout << ( " NO " ) ; int right_most = remaining % k ; int high = ceil ( remaining / ( k * 1.0 ) ) ; int low = floor ( remaining / ( k * 1.0 ) ) ; for ( int i = k - right_most ; i < k ; i ++ ) array [ i ] = high ; for ( int i = 0 ; i < ( k - right_most ) ; i ++ ) array [ i ] = low ; for ( int i = 0 ; i < k ; i ++ ) array [ i ] += i + 1 ; if ( k - 1 != remaining or k == 1 ) { for ( int u : array ) cout << u << " ▁ " ; } else if ( k == 2 or k == 3 ) printf ( " - 1 STRNEWLINE " ) ; else { array [ 1 ] -= 1 ; array [ k - 1 ] += 1 ; for ( int u : array ) cout << u << " ▁ " ; } } int main ( ) { int n = 26 , k = 6 ; generateArray ( n , k ) ; return 0 ; }
Maximize the given number by replacing a segment of digits with the alternate digits given | C ++ implementation of the approach ; Function to return the maximized number ; Iterate till the end of the string ; Check if it is greater or not ; Replace with the alternate till smaller ; Return original s in case no change took place ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string get_maximum ( string s , int a [ ] ) { int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] - '0' < a [ s [ i ] - '0' ] ) { int j = i ; while ( j < n && ( s [ j ] - '0' <= a [ s [ j ] - '0' ] ) ) { s [ j ] = '0' + a [ s [ j ] - '0' ] ; j ++ ; } return s ; } } return s ; } int main ( ) { string s = "1337" ; int a [ ] = { 0 , 1 , 2 , 5 , 4 , 6 , 6 , 3 , 1 , 9 } ; cout << get_maximum ( s , a ) ; return 0 ; }
Number of times the largest perfect square number can be subtracted from N | C ++ implementation of the approach ; Function to return the count of steps ; Variable to store the count of steps ; Iterate while N > 0 ; Get the largest perfect square and subtract it from N ; Increment steps ; Return the required count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSteps ( int n ) { int steps = 0 ; while ( n ) { int largest = sqrt ( n ) ; n -= ( largest * largest ) ; steps ++ ; } return steps ; } int main ( ) { int n = 85 ; cout << countSteps ( n ) ; return 0 ; }
Maximum array sum that can be obtained after exactly k changes | C ++ implementation of the approach ; Utility function to return the sum of the array elements ; Function to return the maximized sum of the array after performing the given operation exactly k times ; Sort the array elements ; Change signs of the negative elements starting from the smallest ; If a single operation has to be performed then it must be performed on the smallest positive element ; To store the index of the minimum element ; Update the minimum index ; Perform remaining operation on the smallest element ; Return the sum of the updated array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumArr ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; return sum ; } int maxSum ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int i = 0 ; while ( i < n && k > 0 && arr [ i ] < 0 ) { arr [ i ] *= -1 ; k -- ; i ++ ; } if ( k % 2 == 1 ) { int min = 0 ; for ( i = 1 ; i < n ; i ++ ) if ( arr [ min ] > arr [ i ] ) min = i ; arr [ min ] *= -1 ; } return sumArr ( arr , n ) ; } int main ( ) { int arr [ ] = { -5 , 4 , 1 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 4 ; cout << maxSum ( arr , n , k ) << endl ; return 0 ; }
Given count of digits 1 , 2 , 3 , 4 , find the maximum sum possible | CPP program to maximum possible sum ; Function to find the maximum possible sum ; To store required sum ; Number of 234 's can be formed ; Sum obtained with 234 s ; Remaining 2 's ; Sum obtained with 12 s ; Return the required sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Maxsum ( int c1 , int c2 , int c3 , int c4 ) { int sum = 0 ; int two34 = min ( c2 , min ( c3 , c4 ) ) ; sum = two34 * 234 ; c2 -= two34 ; sum += min ( c2 , c1 ) * 12 ; return sum ; } int main ( ) { int c1 = 5 , c2 = 2 , c3 = 3 , c4 = 4 ; cout << Maxsum ( c1 , c2 , c3 , c4 ) ; return 0 ; }
Replace all elements by difference of sums of positive and negative numbers after that element | C ++ program to implement above approach ; Function to print the array elements ; Function to replace all elements with absolute difference of absolute sums of positive and negative elements ; calculate difference of both sums ; if i - th element is positive , add it to positive sum ; if i - th element is negative , add it to negative sum ; replace i - th elements with absolute difference ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void printArray ( int N , int arr [ ] ) { for ( int i = 0 ; i < N ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } void replacedArray ( int N , int arr [ ] ) { int pos_sum , neg_sum , i , j , diff ; pos_sum = 0 ; neg_sum = 0 ; for ( i = N - 1 ; i >= 0 ; i -- ) { diff = abs ( pos_sum ) - abs ( neg_sum ) ; if ( arr [ i ] > 0 ) pos_sum += arr [ i ] ; else neg_sum += arr [ i ] ; arr [ i ] = abs ( diff ) ; } } int main ( ) { int N = 5 ; int arr [ ] = { 1 , -1 , 2 , 3 , -2 } ; replacedArray ( N , arr ) ; printArray ( N , arr ) ; N = 6 ; int arr1 [ ] = { -3 , -4 , -2 , 5 , 1 , -2 } ; replacedArray ( N , arr1 ) ; printArray ( N , arr1 ) ; return 0 ; }
Count of pairs from 1 to a and 1 to b whose sum is divisible by N | C ++ implementation of above approach ; Function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; pairs from 1 to n * ( a / n ) and 1 to n * ( b / n ) ; pairs from 1 to n * ( a / n ) and n * ( b / n ) to b ; pairs from n * ( a / n ) to a and 1 to n * ( b / n ) ; pairs from n * ( a / n ) to a and n * ( b / n ) to b ; Return answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCountOfPairs ( int a , int b , int n ) { int ans = 0 ; ans += n * ( a / n ) * ( b / n ) ; ans += ( a / n ) * ( b % n ) ; ans += ( a % n ) * ( b / n ) ; ans += ( ( a % n ) + ( b % n ) ) / n ; return ans ; } int main ( ) { int a = 5 , b = 13 , n = 3 ; cout << findCountOfPairs ( a , b , n ) ; return 0 ; }
Generate array with minimum sum which can be deleted in P steps | C ++ implementation of above approach ; Function to find the required array ; calculating minimum possible sum ; Array ; place first P natural elements ; Fill rest of the elements with 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findArray ( int N , int P ) { int ans = ( P * ( P + 1 ) ) / 2 + ( N - P ) ; int arr [ N + 1 ] ; for ( int i = 1 ; i <= P ; i ++ ) arr [ i ] = i ; for ( int i = P + 1 ; i <= N ; i ++ ) arr [ i ] = 1 ; cout << " The ▁ Minimum ▁ Possible ▁ Sum ▁ is : ▁ " << ans << " STRNEWLINE " ; cout << " The ▁ Array ▁ Elements ▁ are : ▁ STRNEWLINE " ; for ( int i = 1 ; i <= N ; i ++ ) cout << arr [ i ] << ' ▁ ' ; } int main ( ) { int N = 5 , P = 3 ; findArray ( N , P ) ; return 0 ; }
Find Intersection of all Intervals | C ++ implementation of the approach ; Function to print the intersection ; First interval ; Check rest of the intervals and find the intersection ; If no intersection exists ; Else update the intersection ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findIntersection ( int intervals [ ] [ 2 ] , int N ) { int l = intervals [ 0 ] [ 0 ] ; int r = intervals [ 0 ] [ 1 ] ; for ( int i = 1 ; i < N ; i ++ ) { if ( intervals [ i ] [ 0 ] > r intervals [ i ] [ 1 ] < l ) { cout << -1 ; return ; } else { l = max ( l , intervals [ i ] [ 0 ] ) ; r = min ( r , intervals [ i ] [ 1 ] ) ; } } cout << " [ " << l << " , ▁ " << r << " ] " ; } int main ( ) { int intervals [ ] [ 2 ] = { { 1 , 6 } , { 2 , 8 } , { 3 , 10 } , { 5 , 8 } } ; int N = sizeof ( intervals ) / sizeof ( intervals [ 0 ] ) ; findIntersection ( intervals , N ) ; }
Maximum size of sub | C ++ implementation of the approach ; Function that compares a and b ; Function to return length of longest subarray that satisfies one of the given conditions ; Driver Code ; Print the required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cmp ( int a , int b ) { return ( a > b ) - ( a < b ) ; } int maxSubarraySize ( int arr [ ] , int n ) { int ans = 1 ; int anchor = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int c = cmp ( arr [ i - 1 ] , arr [ i ] ) ; if ( c == 0 ) anchor = i ; else if ( i == n - 1 || c * cmp ( arr [ i ] , arr [ i + 1 ] ) != -1 ) { ans = max ( ans , i - anchor + 1 ) ; anchor = i ; } } return ans ; } int main ( ) { int arr [ ] = { 9 , 4 , 2 , 10 , 7 , 8 , 8 , 1 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSubarraySize ( arr , n ) ; }
Maximum count of sub | C ++ implementation of the approach ; Function to return the count of the required sub - strings ; Iterate over all characters ; Count with current character ; If the substring has a length k then increment count with current character ; Update max count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubStrings ( string s , int k ) { int maxSubStr = 0 , n = s . size ( ) ; for ( int c = 0 ; c < 26 ; c ++ ) { char ch = ' a ' + c ; int curr = 0 ; for ( int i = 0 ; i <= n - k ; i ++ ) { if ( s [ i ] != ch ) continue ; int cnt = 0 ; while ( i < n && s [ i ] == ch && cnt != k ) { i ++ ; cnt ++ ; } i -- ; if ( cnt == k ) curr ++ ; } maxSubStr = max ( maxSubStr , curr ) ; } return maxSubStr ; } int main ( ) { string s = " aaacaabbaa " ; int k = 2 ; cout << maxSubStrings ( s , k ) ; return 0 ; }
Count valid pairs in the array satisfying given conditions | C ++ implementation of the approach ; Function to return total valid pairs ; Initialize count of all the elements ; frequency count of all the elements ; Add total valid pairs ; Exclude pairs made with a single element i . e . ( x , x ) ; Driver Code ; Function call to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int ValidPairs ( int arr [ ] , int n ) { int count [ 121 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) count [ arr [ i ] ] += 1 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] ) continue ; if ( abs ( arr [ i ] - arr [ j ] ) % 2 == 1 ) continue ; ans += count [ arr [ i ] ] * count [ arr [ j ] ] ; if ( arr [ i ] == arr [ j ] ) ans -= count [ arr [ i ] ] ; } return ans ; } int main ( ) { int arr [ ] = { 16 , 17 , 18 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << ( ValidPairs ( arr , n ) ) ; return 0 ; }
Distribution of candies according to ages of students | C ++ implementation of the approach ; Function to check The validity of distribution ; Stroring the max age of all students + 1 ; Stroring the max candy + 1 ; Creating the frequency array of the age of students ; Creating the frequency array of the packets of candies ; Pointer to tell whether we have reached the end of candy frequency array ; Flag to tell if distribution is possible or not ; Flag to tell if we can choose some candy packets for the students with age j ; If the quantity of packets is greater than or equal to the number of students of age j , then we can choose these packets for the students ; Start searching from k + 1 in next operation ; If we cannot choose any packets then the answer is NO ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void check_distribution ( int n , int k , int age [ ] , int candy [ ] ) { int mxage = * ( std :: max_element ( age , age + n ) ) + 1 ; int mxcandy = * ( std :: max_element ( candy , candy + k ) ) + 1 ; int fr1 [ mxage ] = { 0 } ; int fr2 [ mxcandy ] = { 0 } ; for ( int j = 0 ; j < n ; j ++ ) { fr1 [ age [ j ] ] += 1 ; } for ( int j = 0 ; j < k ; j ++ ) { fr2 [ candy [ j ] ] += 1 ; } k = 0 ; bool Tf = true ; for ( int j = 0 ; j < mxage ; j ++ ) { if ( fr1 [ j ] == 0 ) continue ; bool flag = false ; while ( k < mxcandy ) { if ( fr1 [ j ] <= fr2 [ k ] ) { flag = true ; break ; } k += 1 ; } k = k + 1 ; if ( flag == false ) { Tf = false ; break ; } } if ( Tf ) cout << " YES " << endl ; else cout << " NO " << endl ; } int main ( ) { int age [ ] = { 5 , 15 , 10 } ; int candy [ ] = { 2 , 2 , 2 , 3 , 3 , 4 } ; int n = sizeof ( age ) / sizeof ( age [ 0 ] ) ; int k = sizeof ( candy ) / sizeof ( candy [ 0 ] ) ; check_distribution ( n , k , age , candy ) ; return 0 ; }
Find a palindromic string B such that given String A is a subsequense of B | C ++ program to find a palindromic string B such that given String A is a subsequense of B ; Function to check if a string is palindrome ; Reversing a string ; check if reversed string is equal to given string ; Function to find a palindromic string B such that given String A is a subsequense of B ; Reversing the string A ; If the string A is already a palindrome return A ; else return B ; Swap values of left and right ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPalindrome ( string s ) { string x = s ; reverse ( s . begin ( ) , s . end ( ) ) ; return s == x ; } string findStringB ( string A ) { string B = A ; reverse ( A . begin ( ) , A . end ( ) ) ; A = A + B ; if ( checkPalindrome ( B ) ) return B ; return A ; } string reverse ( string input ) { string temparray = input ; int left , right = 0 ; right = temparray . length ( ) - 1 ; for ( left = 0 ; left < right ; left ++ , right -- ) swap ( temparray [ left ] , temparray [ right ] ) ; return temparray ; } int main ( int argc , char const * argv [ ] ) { string A = " ab " ; cout << findStringB ( A ) << endl ; return 0 ; }
Minimum number of 1 's to be replaced in a binary array | C ++ program to find minimum number of 1 ' s ▁ to ▁ be ▁ replaced ▁ to ▁ 0' s ; Function to find minimum number of 1 ' s ▁ to ▁ be ▁ replaced ▁ to ▁ 0' s ; return final answer ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minChanges ( int A [ ] , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n - 2 ; ++ i ) { if ( ( i - 1 >= 0 ) && A [ i - 1 ] == 1 && A [ i + 1 ] == 1 && A [ i ] == 0 ) { A [ i + 1 ] = 0 ; cnt ++ ; } } return cnt ; } int main ( ) { int A [ ] = { 1 , 1 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 0 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minChanges ( A , n ) ; return 0 ; }
Number of closing brackets needed to complete a regular bracket sequence | C ++ program to find number of closing brackets needed and complete a regular bracket sequence ; Function to find number of closing brackets and complete a regular bracket sequence ; Finding the length of sequence ; Counting opening brackets ; Counting closing brackets ; Checking if at any position the number of closing bracket is more then answer is impossible ; If possible , print ' s ' and required closing brackets . ; Driver code
#include <iostream> NEW_LINE using namespace std ; void completeSuquence ( string s ) { int n = s . length ( ) ; int open = 0 , close = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ( ' ) open ++ ; else close ++ ; if ( close > open ) { cout << " Impossible " << endl ; return ; } } cout << s ; for ( int i = 0 ; i < open - close ; i ++ ) cout << ' ) ' ; cout << endl ; } int main ( ) { string s = " ( ( ) ( ( ) ( " ; completeSuquence ( s ) ; return 0 ; }
Lexicographically smallest permutation with no digits at Original Index | C ++ program to find the smallest permutation ; Function to print the smallest permutation ; when n is even ; when n is odd ; handling last 3 digit ; add EOL and print result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string smallestPermute ( int n ) { char res [ n + 1 ] ; if ( n % 2 == 0 ) { for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = 48 + i + 2 ; else res [ i ] = 48 + i ; } } else { for ( int i = 0 ; i < n - 2 ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = 48 + i + 2 ; else res [ i ] = 48 + i ; } res [ n - 1 ] = 48 + n - 2 ; res [ n - 2 ] = 48 + n ; res [ n - 3 ] = 48 + n - 1 ; } res [ n ] = ' \0' ; return res ; } int main ( ) { int n = 7 ; cout << smallestPermute ( n ) ; return 0 ; }
Minimum array insertions required to make consecutive difference <= K | CPP implementation of above approach ; Function to return minimum number of insertions required ; Initialize insertions to 0 ; return total insertions ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minInsertions ( int H [ ] , int n , int K ) { int inser = 0 ; for ( int i = 1 ; i < n ; ++ i ) { float diff = abs ( H [ i ] - H [ i - 1 ] ) ; if ( diff <= K ) continue ; else inser += ceil ( diff / K ) - 1 ; } return inser ; } int main ( ) { int H [ ] = { 2 , 4 , 8 , 16 } , K = 3 ; int n = sizeof ( H ) / sizeof ( H [ 0 ] ) ; cout << minInsertions ( H , n , K ) ; return 0 ; }
Minimum number of operations required to reduce N to 1 | C ++ implementation of above approach ; Function that returns the minimum number of operations to be performed to reduce the number to 1 ; To stores the total number of operations to be performed ; if n is divisible by 3 then reduce it to n / 3 ; if n modulo 3 is 1 decrement it by 1 ; if n modulo 3 is 2 then increment it by 1 ; update the counter ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_minimum_operations ( long long n ) { int count = 0 ; while ( n > 1 ) { if ( n % 3 == 0 ) n /= 3 ; else if ( n % 3 == 1 ) n -- ; else { if ( n == 2 ) n -- ; else n ++ ; } count ++ ; } return count ; } int main ( ) { long long n = 4 ; long long ans = count_minimum_operations ( n ) ; cout << ans << endl ; return 0 ; }
Minimum number of operations required to reduce N to 1 | C ++ implementation of above approach ; Function that returns the minimum number of operations to be performed to reduce the number to 1 ; Base cases ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_minimum_operations ( long long n ) { if ( n == 2 ) { return 1 ; } else if ( n == 1 ) { return 0 ; } if ( n % 3 == 0 ) { return 1 + count_minimum_operations ( n / 3 ) ; } else if ( n % 3 == 1 ) { return 1 + count_minimum_operations ( n - 1 ) ; } else { return 1 + count_minimum_operations ( n + 1 ) ; } } int main ( ) { long long n = 4 ; long long ans = count_minimum_operations ( n ) ; cout << ans << endl ; return 0 ; }
Maximize the sum of array by multiplying prefix of array with | C ++ implementation of the approach ; To store sum ; To store ending indices of the chosen prefix array vect ; Adding the absolute value of a [ i ] ; If i == 0 then there is no index to be flipped in ( i - 1 ) position ; print the maximized sum ; print the ending indices of the chosen prefix arrays ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSum ( int * a , int n ) { vector < int > l ; int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) { s += abs ( a [ i ] ) ; if ( a [ i ] >= 0 ) continue ; if ( i == 0 ) l . push_back ( i + 1 ) ; else { l . push_back ( i + 1 ) ; l . push_back ( i ) ; } } cout << s << endl ; for ( int i = 0 ; i < l . size ( ) ; i ++ ) cout << l [ i ] << " ▁ " ; } int main ( ) { int n = 4 ; int a [ ] = { 1 , -2 , -3 , 4 } ; maxSum ( a , n ) ; }
Find the longest common prefix between two strings after performing swaps on second string | C ++ program to find the longest common prefix between two strings after performing swaps on the second string ; int a = x . length ( ) ; length of x int b = y . length ( ) ; length of y ; creating frequency array of characters of y ; storing the length of longest common prefix ; checking if the frequency of the character at position i in x in b is greater than zero or not if zero we increase the prefix count by 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void LengthLCP ( string x , string y ) { int fr [ 26 ] = { 0 } ; for ( int i = 0 ; i < b ; i ++ ) { fr [ y [ i ] - 97 ] += 1 ; } int c = 0 ; for ( int i = 0 ; i < a ; i ++ ) { if ( fr [ x [ i ] - 97 ] > 0 ) { c += 1 ; fr [ x [ i ] - 97 ] -= 1 ; } else break ; } cout << ( c ) << endl ; } int main ( ) { string x = " here " , y = " there " ; LengthLCP ( x , y ) ; return 0 ; }
All possible co | C ++ implementation of the approach ; Function to count possible pairs ; total count of numbers in range ; printing count of pairs ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CountPair ( int L , int R ) { int x = ( R - L + 1 ) ; cout << x / 2 << " STRNEWLINE " ; } int main ( ) { int L , R ; L = 1 , R = 8 ; CountPair ( L , R ) ; return 0 ; }
Problems not solved at the end of Nth day | C ++ program to find problems not solved at the end of Nth day ; Function to find problems not solved at the end of Nth day ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int problemsLeft ( int K , int P , int N ) { if ( K <= P ) return 0 ; else return ( K - P ) * N ; } int main ( ) { int K , P , N ; K = 4 ; P = 1 ; N = 10 ; cout << problemsLeft ( K , P , N ) ; return 0 ; }
Kruskal 's Algorithm (Simple Implementation for Adjacency Matrix) | Simple C ++ implementation for Kruskal 's algorithm ; Find set of vertex i ; Does union of i and j . It returns false if i and j are already in same set . ; Finds MST using Kruskal 's algorithm ; Initialize sets of disjoint sets . ; Include minimum weight edges one by one ; driver program to test above function ; Let us create the following graph 2 3 ( 0 ) -- ( 1 ) -- ( 2 ) | / \ | 6 | 8 / \ 5 | 7 | / \ | ( 3 ) -- -- -- - ( 4 ) 9 ; Print the solution
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define V 5 NEW_LINE int parent [ V ] ; int find ( int i ) { while ( parent [ i ] != i ) i = parent [ i ] ; return i ; } void union1 ( int i , int j ) { int a = find ( i ) ; int b = find ( j ) ; parent [ a ] = b ; } void kruskalMST ( int cost [ ] [ V ] ) { for ( int i = 0 ; i < V ; i ++ ) parent [ i ] = i ; int edge_count = 0 ; while ( edge_count < V - 1 ) { int min = INT_MAX , a = -1 , b = -1 ; for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { if ( find ( i ) != find ( j ) && cost [ i ] [ j ] < min ) { min = cost [ i ] [ j ] ; a = i ; b = j ; } } } union1 ( a , b ) ; printf ( " Edge ▁ % d : ( % d , ▁ % d ) ▁ cost : % d ▁ STRNEWLINE " , edge_count ++ , a , b , min ) ; mincost += min ; } printf ( " Minimum cost = % d " , mincost ) ; } int main ( ) { int cost [ ] [ V ] = { { INT_MAX , 2 , INT_MAX , 6 , INT_MAX } , { 2 , INT_MAX , 3 , 8 , 5 } , { INT_MAX , 3 , INT_MAX , INT_MAX , 7 } , { 6 , 8 , INT_MAX , INT_MAX , 9 } , { INT_MAX , 5 , 7 , 9 , INT_MAX } , } ; kruskalMST ( cost ) ; return 0 ; }
Number of chocolates left after k iterations | C ++ program to find remaining chocolates after k iterations ; Function to find the chocolates left ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int results ( int n , int k ) { return round ( pow ( n , ( 1.0 / pow ( 2 , k ) ) ) ) ; } int main ( ) { int k = 3 , n = 100000000 ; cout << " Chocolates ▁ left ▁ after ▁ " << k << " ▁ iterations ▁ are ▁ " << results ( n , k ) ; return 0 ; }
Subarray whose absolute sum is closest to K | C ++ code to find sub - array whose sum shows the minimum deviation ; Starting index , ending index , Deviation ; Iterate i and j to get all subarrays ; Found sub - array with less sum ; Exactly same sum ; Driver code ; Array to store return values
#include <bits/stdc++.h> NEW_LINE using namespace std ; int * getSubArray ( int arr [ ] , int n , int K ) { int i = -1 ; int j = -1 ; int currSum = 0 ; int * result = new int [ 3 ] { i , j , abs ( K - abs ( currSum ) ) } ; for ( i = 0 ; i < n ; i ++ ) { currSum = 0 ; for ( j = i ; j < n ; j ++ ) { currSum += arr [ j ] ; int currDev = abs ( K - abs ( currSum ) ) ; if ( currDev < result [ 2 ] ) { result [ 0 ] = i ; result [ 1 ] = j ; result [ 2 ] = currDev ; } if ( currDev == 0 ) return result ; } } return result ; } int main ( ) { int arr [ 8 ] = { 15 , -3 , 5 , 2 , 7 , 6 , 34 , -6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 50 ; int * ans = getSubArray ( arr , n , K ) ; if ( ans [ 0 ] == -1 ) { cout << " The ▁ empty ▁ array ▁ shows ▁ " << " minimum ▁ Deviation " ; } else { for ( int i = ans [ 0 ] ; i <= ans [ 1 ] ; i ++ ) cout << arr [ i ] << " ▁ " ; } return 0 ; }
Longest subsequence whose average is less than K | C ++ program to perform Q queries to find longest subsequence whose average is less than K ; Function to print the length for evey query ; sort array of N elements ; Array to store average from left ; Sort array of average ; number of queries ; print answer to every query using binary search ; Driver Code ; 4 queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubsequence ( int a [ ] , int n , int q [ ] , int m ) { sort ( a , a + n ) ; int sum = 0 ; int b [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; double av = ( double ) ( sum ) / ( double ) ( i + 1 ) ; b [ i ] = ( ( int ) ( av + 1 ) ) ; } sort ( b , b + n ) ; for ( int i = 0 ; i < m ; i ++ ) { int k = q [ i ] ; int longest = upper_bound ( b , b + n , k ) - b ; cout << " Answer ▁ to ▁ Query " << i + 1 << " : ▁ " << longest << endl ; } } int main ( ) { int a [ ] = { 1 , 3 , 2 , 5 , 4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int q [ ] = { 4 , 2 , 1 , 5 } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; longestSubsequence ( a , n , q , m ) ; return 0 ; }
Make array elements equal in Minimum Steps | C ++ program to make the array elements equal in minimum steps ; Returns the minimum steps required to make an array of N elements equal , where the first array element equals M ; Corner Case 1 : When N = 1 ; Corner Case 2 : When N = 2 else if ( N == 2 ) corner case 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int steps ( int N , int M ) { if ( N == 1 ) return 0 ; return M ; return 2 * M + ( N - 3 ) ; } int main ( ) { int N = 4 , M = 4 ; cout << steps ( N , M ) ; return 0 ; }
Minimum increment / decrement to make array non | CPP code to count the change required to convert the array into non - increasing array ; min heap ; Here in the loop we will check that whether the upcoming element of array is less than top of priority queue . If yes then we calculate the difference . After that we will remove that element and push the current element in queue . And the sum is incremented by the value of difference ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int DecreasingArray ( int a [ ] , int n ) { int sum = 0 , dif = 0 ; priority_queue < int , vector < int > , greater < int > > pq ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! pq . empty ( ) && pq . top ( ) < a [ i ] ) { dif = a [ i ] - pq . top ( ) ; sum += dif ; pq . pop ( ) ; } pq . push ( a [ i ] ) ; } return sum ; } int main ( ) { int a [ ] = { 3 , 1 , 2 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << DecreasingArray ( a , n ) ; return 0 ; }
Schedule jobs so that each server gets equal load | CPP program to schedule jobs so that each server gets equal load . ; Function to find new array a ; find sum S of both arrays a and b . ; Single element case . ; This checks whether sum s can be divided equally between all array elements . i . e . whether all elements can take equal value or not . ; Compute possible value of new array elements . ; Possibility 1 ; ensuring that all elements of array b are used . ; If a ( i ) already updated to x move to next element in array a . ; Possibility 2 ; Possibility 3 ; Possibility 4 ; If a ( i ) can not be made equal to x even after adding all possible elements from b ( i ) then print - 1. ; check whether all elements of b are used . ; Return the new array element value . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int a [ ] , int b [ ] , int n ) { int i ; long long int s = 0 ; for ( i = 0 ; i < n ; i ++ ) s += ( a [ i ] + b [ i ] ) ; if ( n == 1 ) return a [ 0 ] + b [ 0 ] ; if ( s % n != 0 ) return -1 ; int x = s / n ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] > x ) return -1 ; if ( i > 0 ) { a [ i ] += b [ i - 1 ] ; b [ i - 1 ] = 0 ; } if ( a [ i ] == x ) continue ; int y = a [ i ] + b [ i ] ; if ( i + 1 < n ) y += b [ i + 1 ] ; if ( y == x ) { a [ i ] = y ; b [ i ] = b [ i + 1 ] = 0 ; continue ; } if ( a [ i ] + b [ i ] == x ) { a [ i ] += b [ i ] ; b [ i ] = 0 ; continue ; } if ( i + 1 < n && a [ i ] + b [ i + 1 ] == x ) { a [ i ] += b [ i + 1 ] ; b [ i + 1 ] = 0 ; continue ; } return -1 ; } for ( i = 0 ; i < n ; i ++ ) if ( b [ i ] != 0 ) return -1 ; return x ; } int main ( ) { int a [ ] = { 6 , 14 , 21 , 1 } ; int b [ ] = { 15 , 7 , 10 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << solve ( a , b , n ) ; return 0 ; }
Check if it is possible to survive on Island | C ++ program to find the minimum days on which you need to buy food from the shop so that you can survive the next S days ; function to find the minimum days ; If we can not buy at least a week supply of food during the first week OR We can not buy a day supply of food on the first day then we can 't survive. ; If we can survive then we can buy ceil ( A / N ) times where A is total units of food required . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void survival ( int S , int N , int M ) { if ( ( ( N * 6 ) < ( M * 7 ) && S > 6 ) M > N ) cout << " No STRNEWLINE " ; else { int days = ( M * S ) / N ; if ( ( ( M * S ) % N ) != 0 ) days ++ ; cout << " Yes ▁ " << days << endl ; } } int main ( ) { int S = 10 , N = 16 , M = 2 ; survival ( S , N , M ) ; return 0 ; }
Lexicographically largest subsequence such that every character occurs at least k times | C ++ program to find lexicographically largest subsequence where every character appears at least k times . ; Find lexicographically largest subsequence of s [ 0. . n - 1 ] such that every character appears at least k times . The result is filled in t [ ] ; Starting from largest charter ' z ' to ' a ' ; Counting the frequency of the character ; If frequency is greater than k ; From the last point we leave ; check if string contain ch ; If yes , append to output string ; Update the last point . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void subsequence ( char s [ ] , char t [ ] , int n , int k ) { int last = 0 , cnt = 0 , new_last = 0 , size = 0 ; for ( char ch = ' z ' ; ch >= ' a ' ; ch -- ) { cnt = 0 ; for ( int i = last ; i < n ; i ++ ) { if ( s [ i ] == ch ) cnt ++ ; } if ( cnt >= k ) { for ( int i = last ; i < n ; i ++ ) { if ( s [ i ] == ch ) { t [ size ++ ] = ch ; new_last = i ; } } last = new_last ; } } t [ size ] = ' \0' ; } int main ( ) { char s [ ] = " banana " ; int n = sizeof ( s ) ; int k = 2 ; char t [ n ] ; subsequence ( s , t , n - 1 , k ) ; cout << t << endl ; return 0 ; }
Program for Least Recently Used ( LRU ) Page Replacement algorithm | C ++ implementation of above algorithm ; Function to find page faults using indexes ; To represent set of current pages . We use an unordered_set so that we quickly check if a page is present in set or not ; To store least recently used indexes of pages . ; Start from initial page ; Check if the set can hold more pages ; Insert it into set if not present already which represents page fault ; increment page fault ; Store the recently used index of each page ; If the set is full then need to perform lru i . e . remove the least recently used page and insert the current page ; Check if current page is not already present in the set ; Find the least recently used pages that is present in the set ; Remove the indexes page ; insert the current page ; Increment page faults ; Update the current page index ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int pageFaults ( int pages [ ] , int n , int capacity ) { unordered_set < int > s ; unordered_map < int , int > indexes ; int page_faults = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . size ( ) < capacity ) { if ( s . find ( pages [ i ] ) == s . end ( ) ) { s . insert ( pages [ i ] ) ; page_faults ++ ; } indexes [ pages [ i ] ] = i ; } else { if ( s . find ( pages [ i ] ) == s . end ( ) ) { int lru = INT_MAX , val ; for ( auto it = s . begin ( ) ; it != s . end ( ) ; it ++ ) { if ( indexes [ * it ] < lru ) { lru = indexes [ * it ] ; val = * it ; } } s . erase ( val ) ; s . insert ( pages [ i ] ) ; page_faults ++ ; } indexes [ pages [ i ] ] = i ; } } return page_faults ; } int main ( ) { int pages [ ] = { 7 , 0 , 1 , 2 , 0 , 3 , 0 , 4 , 2 , 3 , 0 , 3 , 2 } ; int n = sizeof ( pages ) / sizeof ( pages [ 0 ] ) ; int capacity = 4 ; cout << pageFaults ( pages , n , capacity ) ; return 0 ; }
Largest permutation after at most k swaps | C ++ Program to find the largest permutation after at most k swaps using unordered_map . ; Function to find the largest permutation after k swaps ; Storing the elements and their index in map ; If number of swaps allowed are equal to number of elements then the resulting permutation will be descending order of given permutation . ; if j is not at it 's best index ; Change the index of the element which was at position 0. Swap the element basically . ; decrement number of swaps ; Driver code ; K is the number of swaps ; n is the size of the array ; Function calling
#include <bits/stdc++.h> NEW_LINE #include <unordered_map> NEW_LINE using namespace std ; void bestpermutation ( int arr [ ] , int k , int n ) { unordered_map < int , int > h ; for ( int i = 0 ; i < n ; i ++ ) { h . insert ( make_pair ( arr [ i ] , i ) ) ; } if ( n <= k ) { sort ( arr , arr + n , greater < int > ( ) ) ; } else { for ( int j = n ; j >= 1 ; j -- ) { if ( k > 0 ) { int initial_index = h [ j ] ; int best_index = n - j ; if ( initial_index != best_index ) { h [ j ] = best_index ; int element = arr [ best_index ] ; h [ element ] = initial_index ; swap ( arr [ best_index ] , arr [ initial_index ] ) ; k -- ; } } } } } int main ( ) { int arr [ ] = { 3 , 1 , 4 , 2 , 5 } ; int k = 10 ; int n = sizeof ( arr ) / sizeof ( int ) ; bestpermutation ( arr , k , n ) ; cout << " Largest ▁ possible ▁ permutation ▁ after ▁ " << k << " ▁ swaps ▁ is ▁ " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Program for Best Fit algorithm in Memory Management | C ++ implementation of Best - Fit algorithm ; Function to allocate memory to blocks as per Best fit algorithm ; Stores block id of the block allocated to a process ; Initially no block is assigned to any process ; pick each process and find suitable blocks according to its size ad assign to it ; Find the best fit block for current process ; If we could find a block for current process ; allocate block j to p [ i ] process ; Reduce available memory in this block . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void bestFit ( int blockSize [ ] , int m , int processSize [ ] , int n ) { int allocation [ n ] ; memset ( allocation , -1 , sizeof ( allocation ) ) ; for ( int i = 0 ; i < n ; i ++ ) { int bestIdx = -1 ; for ( int j = 0 ; j < m ; j ++ ) { if ( blockSize [ j ] >= processSize [ i ] ) { if ( bestIdx == -1 ) bestIdx = j ; else if ( blockSize [ bestIdx ] > blockSize [ j ] ) bestIdx = j ; } } if ( bestIdx != -1 ) { allocation [ i ] = bestIdx ; blockSize [ bestIdx ] -= processSize [ i ] ; } } cout << " Process No . Process Size Block no . " ; for ( int i = 0 ; i < n ; i ++ ) { cout << " ▁ " << i + 1 << " TABSYMBOL TABSYMBOL " << processSize [ i ] << " TABSYMBOL TABSYMBOL " ; if ( allocation [ i ] != -1 ) cout << allocation [ i ] + 1 ; else cout << " Not ▁ Allocated " ; cout << endl ; } } int main ( ) { int blockSize [ ] = { 100 , 500 , 200 , 300 , 600 } ; int processSize [ ] = { 212 , 417 , 112 , 426 } ; int m = sizeof ( blockSize ) / sizeof ( blockSize [ 0 ] ) ; int n = sizeof ( processSize ) / sizeof ( processSize [ 0 ] ) ; bestFit ( blockSize , m , processSize , n ) ; return 0 ; }
Bin Packing Problem ( Minimize number of used Bins ) | C ++ program to find number of bins required using Best fit algorithm . ; Returns number of bins required using best fit online algorithm ; Initialize result ( Count of bins ) ; Create an array to store remaining space in bins there can be at most n bins ; Place items one by one ; Find the best bin that can accommodate weight [ i ] ; Initialize minimum space left and index of best bin ; If no bin could accommodate weight [ i ] , create a new bin ; else Assign the item to best bin ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int bestFit ( int weight [ ] , int n , int c ) { int res = 0 ; int bin_rem [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int j ; int min = c + 1 , bi = 0 ; for ( j = 0 ; j < res ; j ++ ) { if ( bin_rem [ j ] >= weight [ i ] && bin_rem [ j ] - weight [ i ] < min ) { bi = j ; min = bin_rem [ j ] - weight [ i ] ; } } if ( min == c + 1 ) { bin_rem [ res ] = c - weight [ i ] ; res ++ ; } bin_rem [ bi ] -= weight [ i ] ; } return res ; } int main ( ) { int weight [ ] = { 2 , 5 , 4 , 7 , 1 , 3 , 8 } ; int c = 10 ; int n = sizeof ( weight ) / sizeof ( weight [ 0 ] ) ; cout << " Number ▁ of ▁ bins ▁ required ▁ in ▁ Best ▁ Fit ▁ : ▁ " << bestFit ( weight , n , c ) ; return 0 ; }
Bin Packing Problem ( Minimize number of used Bins ) | C ++ program to find number of bins required using Worst fit algorithm . ; Returns number of bins required using worst fit online algorithm ; Initialize result ( Count of bins ) ; Create an array to store remaining space in bins there can be at most n bins ; Place items one by one ; Find the best bin that ca \ n accommodate weight [ i ] ; Initialize maximum space left and index of worst bin ; If no bin could accommodate weight [ i ] , create a new bin ; else Assign the item to best bin ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int worstFit ( int weight [ ] , int n , int c ) { int res = 0 ; int bin_rem [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int j ; int mx = -1 , wi = 0 ; for ( j = 0 ; j < res ; j ++ ) { if ( bin_rem [ j ] >= weight [ i ] && bin_rem [ j ] - weight [ i ] > mx ) { wi = j ; mx = bin_rem [ j ] - weight [ i ] ; } } if ( mx == -1 ) { bin_rem [ res ] = c - weight [ i ] ; res ++ ; } bin_rem [ wi ] -= weight [ i ] ; } return res ; } int main ( ) { int weight [ ] = { 2 , 5 , 4 , 7 , 1 , 3 , 8 } ; int c = 10 ; int n = sizeof ( weight ) / sizeof ( weight [ 0 ] ) ; cout << " Number ▁ of ▁ bins ▁ required ▁ in ▁ Worst ▁ Fit ▁ : ▁ " << worstFit ( weight , n , c ) ; return 0 ; }
Find minimum time to finish all jobs with given constraints | C ++ program to find minimum time to finish all jobs with given number of assignees ; Utility function to get maximum element in job [ 0. . n - 1 ] ; Returns true if it is possible to finish jobs [ ] within given time ' time ' ; cnt is count of current assignees required for jobs ; int curr_time = 0 ; time assigned to current assignee ; If time assigned to current assignee exceeds max , increment count of assignees . ; else { Else add time of job to current time and move to next job . ; Returns true if count is smaller than k ; Returns minimum time required to finish given array of jobs k -- > number of assignees T -- > Time required by every assignee to finish 1 unit m -- > Number of jobs ; Set start and end for binary search end provides an upper limit on time ; Find the job that takes maximum time ; Do binary search for minimum feasible time ; If it is possible to finish jobs in mid time ; ans = min ( ans , mid ) ; Update answer ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMax ( int arr [ ] , int n ) { int result = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > result ) result = arr [ i ] ; return result ; } bool isPossible ( int time , int K , int job [ ] , int n ) { int cnt = 1 ; for ( int i = 0 ; i < n ; ) { if ( curr_time + job [ i ] > time ) { curr_time = 0 ; cnt ++ ; } curr_time += job [ i ] ; i ++ ; } } return ( cnt <= K ) ; } int findMinTime ( int K , int T , int job [ ] , int n ) { int end = 0 , start = 0 ; for ( int i = 0 ; i < n ; ++ i ) end += job [ i ] ; int job_max = getMax ( job , n ) ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( mid >= job_max && isPossible ( mid , K , job , n ) ) { end = mid - 1 ; } else start = mid + 1 ; } return ( ans * T ) ; } int main ( ) { int job [ ] = { 10 , 7 , 8 , 12 , 6 , 8 } ; int n = sizeof ( job ) / sizeof ( job [ 0 ] ) ; int k = 4 , T = 5 ; cout << findMinTime ( k , T , job , n ) << endl ; return 0 ; }
Longest subarray with all even or all odd elements | C ++ implementation for the above approach ; Function to calculate longest substring with odd or even elements ; Initializing dp [ ] ; Initializing dp [ 0 ] with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp [ i ] with dp [ i - 1 ] + 1 ; Storing max element to ans ; Returning the final answer ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestOddEvenSubarray ( int A [ ] , int N ) { int dp [ N ] ; dp [ 0 ] = 1 ; int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( ( A [ i ] % 2 == 0 && A [ i - 1 ] % 2 == 0 ) || ( A [ i ] % 2 != 0 && A [ i - 1 ] % 2 != 0 ) ) { dp [ i ] = dp [ i - 1 ] + 1 ; } else dp [ i ] = 1 ; } for ( int i = 0 ; i < N ; i ++ ) ans = max ( ans , dp [ i ] ) ; return ans ; } int main ( ) { int A [ ] = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << LongestOddEvenSubarray ( A , N ) ; return 0 ; }
Count of subarrays with maximum value as K | C ++ implementation of the above approach ; Function to count the subarrays with maximum not greater than K ; If arr [ i ] > k then arr [ i ] cannot be a part of any subarray . ; Count the number of elements where arr [ i ] is not greater than k . ; Summation of all possible subarrays in the variable ans . ; Function to count the subarrays with maximum value is equal to K ; Stores count of subarrays with max <= k - 1. ; Stores count of subarrays with max >= k + 1. ; Stores count of subarrays with max = k . ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int totalSubarrays ( int arr [ ] , int n , int k ) { int ans = 0 , i = 0 ; while ( i < n ) { if ( arr [ i ] > k ) { i ++ ; continue ; } int count = 0 ; while ( i < n && arr [ i ] <= k ) { i ++ ; count ++ ; } ans += ( ( count * ( count + 1 ) ) / 2 ) ; } return ans ; } int countSubarrays ( int arr [ ] , int n , int k ) { int count1 = totalSubarrays ( arr , n , k - 1 ) ; int count2 = totalSubarrays ( arr , n , k ) ; int ans = count2 - count1 ; return ans ; } int main ( ) { int n = 4 , k = 3 ; int arr [ ] = { 2 , 1 , 3 , 4 } ; cout << countSubarrays ( arr , n , k ) ; return 0 ; }
Count N | C ++ program for the above approach ; Stores the dp - states ; Function to calculate the count of N - digit numbers that contains all digits from [ 0 - 9 ] atleast once ; If all digits are traversed ; Check if all digits are included in the mask ; If the state has already been computed ; If the current digit is 1 , any digit from [ 1 - 9 ] can be placed . If N == 1 , 0 can also be placed ; For other positions , any digit from [ 0 - 9 ] can be placed ; Return the answer ; Driver Code ; Initializing dp array with - 1. ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long dp [ 100 ] [ 1 << 10 ] ; long long countOfNumbers ( int digit , int mask , int N ) { if ( digit == N + 1 ) { if ( mask == ( 1 << 10 ) - 1 ) return 1 ; return 0 ; } long long & val = dp [ digit ] [ mask ] ; if ( val != -1 ) return val ; val = 0 ; if ( digit == 1 ) { for ( int i = ( N == 1 ? 0 : 1 ) ; i <= 9 ; ++ i ) { val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , N ) ; } } else { for ( int i = 0 ; i <= 9 ; ++ i ) { val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , N ) ; } } return val ; } int main ( ) { memset ( dp , -1 , sizeof dp ) ; int N = 10 ; cout << countOfNumbers ( 1 , 0 , N ) ; return 0 ; }
Maximum subsequence sum such that no three are consecutive in O ( 1 ) space | C ++ implementation for the above approach ; Function to calculate the maximum subsequence sum such that no three elements are consecutive ; when N is 1 , answer would be the only element present ; when N is 2 , answer would be sum of elements ; variable to store sum up to i - 3 ; variable to store sum up to i - 2 ; variable to store sum up to i - 1 ; variable to store the final sum of the subsequence ; find the maximum subsequence sum up to index i ; update first , second and third ; return ans ; ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumWO3Consec ( int A [ ] , int N ) { if ( N == 1 ) return A [ 0 ] ; if ( N == 2 ) return A [ 0 ] + A [ 1 ] ; int third = A [ 0 ] ; int second = third + A [ 1 ] ; int first = max ( second , A [ 1 ] + A [ 2 ] ) ; int sum = max ( max ( third , second ) , first ) ; for ( int i = 3 ; i < N ; i ++ ) { sum = max ( max ( first , second + A [ i ] ) , third + A [ i ] + A [ i - 1 ] ) ; third = second ; second = first ; first = sum ; } return sum ; } int main ( ) { int A [ ] = { 3000 , 2000 , 1000 , 3 , 10 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << maxSumWO3Consec ( A , N ) ; return 0 ; }
Minimum number of given operations required to reduce a number to 2 | C ++ program for the above approach ; Function to find the minimum number of operations required to reduce n to 2 ; Initialize a dp array ; Handle the base case ; Iterate in the range [ 2 , n ] ; Check if i * 5 <= n ; Check if i + 3 <= n ; Return the result ; Driver code ; Given Input ; Function Call ; Print the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinOperations ( int n ) { int i , dp [ n + 1 ] ; for ( i = 0 ; i < n + 1 ; i ++ ) { dp [ i ] = 999999 ; } dp [ 2 ] = 0 ; for ( i = 2 ; i < n + 1 ; i ++ ) { if ( i * 5 <= n ) { dp [ i * 5 ] = min ( dp [ i * 5 ] , dp [ i ] + 1 ) ; } if ( i + 3 <= n ) { dp [ i + 3 ] = min ( dp [ i + 3 ] , dp [ i ] + 1 ) ; } } return dp [ n ] ; } int main ( ) { int n = 28 ; int m = findMinOperations ( n ) ; if ( m != 9999 ) cout << m ; else cout << -1 ; return 0 ; }
Number of M | C ++ program for the above approach ; Function to find the number of M - length sorted arrays possible using numbers from the range [ 1 , N ] ; Create an array of size M + 1 ; Base cases ; Fill the dp table ; dp [ j ] will be equal to maximum number of sorted array of size j when elements are taken from 1 to i ; Here dp [ m ] will be equal to the maximum number of sorted arrays when element are taken from 1 to i ; Return the result ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSortedArrays ( int n , int m ) { vector < int > dp ( m + 1 , 0 ) ; dp [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { dp [ j ] = dp [ j - 1 ] + dp [ j ] ; } } return dp [ m ] ; } int main ( ) { int n = 2 , m = 3 ; cout << countSortedArrays ( n , m ) ; return 0 ; }
Split array into subarrays such that sum of difference between their maximums and minimums is maximum | C ++ program for the above approach ; Function to find maximum sum of difference between maximums and minimums in the splitted subarrays ; Base Case ; Traverse the array ; Stores the maximum and minimum elements upto the i - th index ; Traverse the range [ 0 , i ] ; Update the minimum ; Update the maximum ; Update dp [ i ] ; Return the maximum sum of difference ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getValue ( int arr [ ] , int N ) { int dp [ N ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] = 0 ; for ( int i = 1 ; i < N ; i ++ ) { int minn = arr [ i ] ; int maxx = arr [ i ] ; for ( int j = i ; j >= 0 ; j -- ) { minn = min ( arr [ j ] , minn ) ; maxx = max ( arr [ j ] , maxx ) ; dp [ i ] = max ( dp [ i ] , maxx - minn + ( ( j >= 1 ) ? dp [ j - 1 ] : 0 ) ) ; } } return dp [ N - 1 ] ; } int main ( ) { int arr [ ] = { 8 , 1 , 7 , 9 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getValue ( arr , N ) ; return 0 ; }
Length of longest subset consisting of A 0 s and B 1 s from an array of strings | C ++ program for the above approach ; Function to count 0 's in a string ; Stores count of 0 s ; Iterate over characters of string ; If current character is '0' ; Recursive function to find the length of longest subset from an array of strings with at most A 0 ' s ▁ and ▁ B ▁ 1' s ; If idx is equal to N or A + B is equal to 0 ; Stores the count of 0 's in arr[idx] ; Stores the count of 1 's in arr[idx] ; Stores the length of the subset if arr [ i ] is included ; If zero is less than or equal to A and one is less than or equal to B ; Stores the length of the subset if arr [ i ] is excluded ; Returns max of inc and exc ; Function to find the length of the longest subset from an array of strings with at most A 0 ' s ▁ and ▁ B ▁ 1' s ; Return ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count0 ( string s ) { int count = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == '0' ) { count ++ ; } } return count ; } int solve ( vector < string > vec , int A , int B , int idx ) { if ( idx == vec . size ( ) A + B == 0 ) { return 0 ; } int zero = count0 ( vec [ idx ] ) ; int one = vec [ idx ] . size ( ) - zero ; int inc = 0 ; if ( zero <= A && one <= B ) { inc = 1 + solve ( vec , A - zero , B - one , idx + 1 ) ; } int exc = solve ( vec , A , B , idx + 1 ) ; return max ( inc , exc ) ; } int MaxSubsetlength ( vector < string > arr , int A , int B ) { return solve ( arr , A , B , 0 ) ; } int main ( ) { vector < string > arr = { "1" , "0" , "10" } ; int A = 1 , B = 1 ; cout << MaxSubsetlength ( arr , A , B ) ; return 0 ; }
Maximum score possible by removing substrings made up of single distinct character | C ++ program for the above approach ; Function to check if the string s consists of a single distinct character or not ; Function to calculate the maximum score possible by removing substrings ; If string is empty ; If length of string is 1 ; Store the maximum result ; Try to remove all substrings that satisfy the condition and check for resultant string after removal ; Store the substring { s [ i ] , . . , s [ j ] } ; Check if the substring contains only a single distinct character ; Return the maximum score ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isUnique ( string s ) { set < char > Set ; for ( char c : s ) { Set . insert ( c ) ; } return Set . size ( ) == 1 ; } int maxScore ( string s , int a [ ] ) { int n = s . length ( ) ; if ( n == 0 ) return 0 ; if ( n == 1 ) return a [ 0 ] ; int mx = -1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { string sub = s . substr ( i , j + 1 ) ; if ( isUnique ( sub ) ) mx = max ( mx , a [ sub . length ( ) - 1 ] + maxScore ( s . substr ( 0 , i ) + s . substr ( j + 1 ) , a ) ) ; } } return mx ; } int main ( ) { string s = "011" ; int a [ ] = { 1 , 3 , 1 } ; cout << maxScore ( s , a ) - 1 ; return 0 ; }
Maximum score possible by removing substrings made up of single distinct character | C ++ program for the above approach ; Initialize a dictionary to store the precomputed results ; Function to calculate the maximum score possible by removing substrings ; If s is present in dp [ ] array ; Base Cases : ; If length of string is 0 ; If length of string is 1 ; Put head pointer at start ; Initialize the max variable ; Generate the substrings using two pointers ; If s [ head ] and s [ tail ] are different ; Move head to tail and break ; Store the substring ; Update the maximum ; Move the tail ; Store the score ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; map < string , int > dp ; int maxScore ( string s , vector < int > a ) { if ( dp . find ( s ) != dp . end ( ) ) return dp [ s ] ; int n = s . size ( ) ; if ( n == 0 ) return 0 ; if ( n == 1 ) return a [ 0 ] ; int head = 0 ; int mx = -1 ; while ( head < n ) { int tail = head ; while ( tail < n ) { if ( s [ tail ] != s [ head ] ) { head = tail ; break ; } string sub = s . substr ( head , tail + 1 ) ; mx = max ( mx , a [ sub . size ( ) - 1 ] + maxScore ( s . substr ( 0 , head ) + s . substr ( tail + 1 , s . size ( ) ) , a ) ) ; tail += 1 ; } if ( tail == n ) break ; } dp [ s ] = mx ; return mx ; } int main ( ) { string s = " abb " ; vector < int > a = { 1 , 3 , 1 } ; cout << ( maxScore ( s , a ) - 1 ) ; }
Count all unique outcomes possible by performing S flips on N coins | C ++ program for the above approach ; Dimensions of the DP table ; Stores the dp states ; Function to recursively count the number of unique outcomes possible by performing S flips on N coins ; Base Case ; If the count for the current state is not calculated , then calculate it recursively ; Otherwise return the already calculated value ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define size 1001 NEW_LINE int ans [ size ] [ size ] = { 0 } ; int numberOfUniqueOutcomes ( int n , int s ) { if ( s < n ) ans [ n ] [ s ] = 0 ; else if ( n == 1 n == s ) ans [ n ] [ s ] = 1 ; else if ( ! ans [ n ] [ s ] ) { ans [ n ] [ s ] = numberOfUniqueOutcomes ( n - 1 , s - 1 ) + numberOfUniqueOutcomes ( n - 1 , s - 2 ) ; } return ans [ n ] [ s ] ; } int main ( ) { int N = 5 , S = 8 ; cout << numberOfUniqueOutcomes ( N , S ) ; return 0 ; }
Minimize removals to remove another string as a subsequence of a given string | C ++ implementation of the above approach ; Function to print the minimum number of character removals required to remove X as a subsequence from the string str ; Length of the string str ; Length of the string X ; Stores the dp states ; Fill first row of dp [ ] [ ] ; If X [ j ] matches with str [ 0 ] ; If str [ i ] is equal to X [ j ] ; Update state after removing str [ i [ ; Update state after keeping str [ i ] ; If str [ i ] is not equal to X [ j ] ; Print the minimum number of characters removals ; Driver Code ; Input ; Function call to get minimum number of character removals
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMinimumRemovals ( string str , string X ) { int N = str . size ( ) ; int M = X . size ( ) ; int dp [ N ] [ M ] = { } ; for ( int j = 0 ; j < M ; j ++ ) { if ( str [ 0 ] == X [ j ] ) { dp [ 0 ] [ j ] = 1 ; } } for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( str [ i ] == X [ j ] ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + 1 ; if ( j != 0 ) dp [ i ] [ j ] = min ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - 1 ] ) ; } else { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } } } cout << dp [ N - 1 ] [ M - 1 ] ; } int main ( ) { string str = " btagd " ; string X = " bad " ; printMinimumRemovals ( str , X ) ; return 0 ; }
Railway Station | TCS CodeVita 2020 | C ++ program of the above approach ; Dp table for memoization ; Function to count the number of ways to N - th station ; Base Cases ; If current state is already evaluated ; Count ways in which train 1 can be chosen ; Count ways in which train 2 can be chosen ; Count ways in which train 3 can be chosen ; Store the current state ; Return the number of ways ; Driver Code ; Given Input ; Initialize DP table with - 1 ; Function call to count the number of ways to reach the n - th station
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100000 ] ; int findWays ( int x ) { if ( x < 0 ) return 0 ; if ( x == 0 ) return 1 ; if ( x == 1 ) return 2 ; if ( x == 2 ) return 4 ; if ( dp [ x ] != -1 ) return dp [ x ] ; int count = findWays ( x - 1 ) ; count += findWays ( x - 2 ) ; count += findWays ( x - 3 ) ; dp [ x ] = count ; return dp [ x ] ; } int main ( ) { int n = 4 ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << findWays ( n ) << " STRNEWLINE " ; }
Maximum sum not exceeding K possible for any rectangle of a Matrix | C ++ program for the above approach ; Function to find the maximum possible sum of arectangle which is less than K ; Stores the values ( cum_sum - K ) ; Insert 0 into the set sumSet ; Traverse over the rows ; Get cumulative sum from [ 0 to i ] ; Search for upperbound of ( cSum - K ) in the hashmap ; If upper_bound of ( cSum - K ) exists , then update max sum ; Insert cummulative value in the hashmap ; Return the maximum sum which is less than K ; Function to find the maximum sum of rectangle such that its sum is no larger than K ; Stores the number of rows and columns ; Store the required result ; Set the left column ; Set the right column for the left column set by outer loop ; Calculate sum between the current left and right for every row ; Stores the sum of rectangle ; Update the overall maximum sum ; Print the result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubarraySum ( vector < int > & sum , int k , int row ) { int curSum = 0 , curMax = INT_MIN ; set < int > sumSet ; sumSet . insert ( 0 ) ; for ( int r = 0 ; r < row ; ++ r ) { curSum += sum [ r ] ; auto it = sumSet . lower_bound ( curSum - k ) ; if ( it != sumSet . end ( ) ) { curMax = max ( curMax , curSum - * it ) ; } sumSet . insert ( curSum ) ; } return curMax ; } void maxSumSubmatrix ( vector < vector < int > > & matrix , int k ) { int row = matrix . size ( ) ; int col = matrix [ 0 ] . size ( ) ; int ret = INT_MIN ; for ( int i = 0 ; i < col ; ++ i ) { vector < int > sum ( row , 0 ) ; for ( int j = i ; j < col ; ++ j ) { for ( int r = 0 ; r < row ; ++ r ) { sum [ r ] += matrix [ r ] [ j ] ; } int curMax = maxSubarraySum ( sum , k , row ) ; ret = max ( ret , curMax ) ; } } cout << ret ; } int main ( ) { vector < vector < int > > matrix = { { 1 , 0 , 1 } , { 0 , -2 , 3 } } ; int K = 2 ; maxSumSubmatrix ( matrix , K ) ; return 0 ; }
Maximum sum submatrix | C ++ program for the above approach ; Function to find maximum continuous maximum sum in the array ; Stores current and maximum sum ; Traverse the array v ; Add the value of the current element ; Update the maximum sum ; Return the maximum sum ; Function to find the maximum submatrix sum ; Store the rows and columns of the matrix ; Create an auxiliary matrix ; Traverse the matrix , prefix and initialize it will all 0 s ; Calculate prefix sum of all rows of matrix A [ ] [ ] and store in matrix prefix [ ] ; Update the prefix [ ] [ ] ; Store the maximum submatrix sum ; Iterate for starting column ; Iterate for last column ; To store current array elements ; Traverse every row ; Store the sum of the kth row ; Update the prefix sum ; Push it in a vector ; Update the maximum overall sum ; Print the answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int kadane ( vector < int > v ) { int currSum = 0 ; int maxSum = INT_MIN ; for ( int i = 0 ; i < ( int ) v . size ( ) ; i ++ ) { currSum += v [ i ] ; if ( currSum > maxSum ) { maxSum = currSum ; } if ( currSum < 0 ) { currSum = 0 ; } } return maxSum ; } void maxSubmatrixSum ( vector < vector < int > > A ) { int r = A . size ( ) ; int c = A [ 0 ] . size ( ) ; int * * prefix = new int * [ r ] ; for ( int i = 0 ; i < r ; i ++ ) { prefix [ i ] = new int ; for ( int j = 0 ; j < c ; j ++ ) { prefix [ i ] [ j ] = 0 ; } } for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { if ( j == 0 ) prefix [ i ] [ j ] = A [ i ] [ j ] ; else prefix [ i ] [ j ] = A [ i ] [ j ] + prefix [ i ] [ j - 1 ] ; } } int maxSum = INT_MIN ; for ( int i = 0 ; i < c ; i ++ ) { for ( int j = i ; j < c ; j ++ ) { vector < int > v ; for ( int k = 0 ; k < r ; k ++ ) { int el = 0 ; if ( i == 0 ) el = prefix [ k ] [ j ] ; else el = prefix [ k ] [ j ] - prefix [ k ] [ i - 1 ] ; v . push_back ( el ) ; } maxSum = max ( maxSum , kadane ( v ) ) ; } } cout << maxSum << " STRNEWLINE " ; } int main ( ) { vector < vector < int > > matrix = { { 0 , -2 , -7 , 0 } , { 9 , 2 , -6 , 2 } , { -4 , 1 , -4 , 1 } , { -1 , 8 , 0 , -2 } } ; maxSubmatrixSum ( matrix ) ; return 0 ; }
Minimize cost of painting N houses such that adjacent houses have different colors | C ++ program for the above approach ; Function to find the minimum cost of coloring the houses such that no two adjacent houses has the same color ; Corner Case ; Auxiliary 2D dp array ; Base Case ; If current house is colored with red the take min cost of previous houses colored with ( blue and green ) ; If current house is colored with blue the take min cost of previous houses colored with ( red and green ) ; If current house is colored with green the take min cost of previous houses colored with ( red and blue ) ; Print the min cost of the last painted house ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( vector < vector < int > > & costs , int N ) { if ( N == 0 ) return 0 ; vector < vector < int > > dp ( N , vector < int > ( 3 , 0 ) ) ; dp [ 0 ] [ 0 ] = costs [ 0 ] [ 0 ] ; dp [ 0 ] [ 1 ] = costs [ 0 ] [ 1 ] ; dp [ 0 ] [ 2 ] = costs [ 0 ] [ 2 ] ; for ( int i = 1 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = min ( dp [ i - 1 ] [ 1 ] , dp [ i - 1 ] [ 2 ] ) + costs [ i ] [ 0 ] ; dp [ i ] [ 1 ] = min ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 2 ] ) + costs [ i ] [ 1 ] ; dp [ i ] [ 2 ] = min ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) + costs [ i ] [ 2 ] ; } cout << min ( dp [ N - 1 ] [ 0 ] , min ( dp [ N - 1 ] [ 1 ] , dp [ N - 1 ] [ 2 ] ) ) ; } int main ( ) { vector < vector < int > > costs { { 14 , 2 , 11 } , { 11 , 14 , 5 } , { 14 , 3 , 10 } } ; int N = costs . size ( ) ; minCost ( costs , N ) ; return 0 ; }
Minimize count of flips required to make sum of the given array equal to 0 | C ++ program for the above approach ; Initialize dp [ ] [ ] ; Function to find the minimum number of operations to make sum of A [ ] 0 ; Initialize answer ; Base case ; Otherwise , return 0 ; Pre - computed subproblem ; Recurrence relation for finding the minimum of the sum of subsets ; Return the result ; Function to find the minimum number of elements required to be flipped to amke sum the array equal to 0 ; Find the sum of array ; Initialise dp [ ] [ ] with - 1 ; No solution exists ; Otherwise ; If sum is odd , no subset is possible ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 2001 ] [ 2001 ] ; int solve ( vector < int > & A , int i , int sum , int N ) { int res = 2001 ; if ( sum < 0 or ( i == N and sum != 0 ) ) { return 2001 ; } if ( sum == 0 or i >= N ) { return dp [ i ] [ sum ] = 0 ; } if ( dp [ i ] [ sum ] != -1 ) { return dp [ i ] [ sum ] ; } res = min ( solve ( A , i + 1 , sum - A [ i ] , N ) + 1 , solve ( A , i + 1 , sum , N ) ) ; return dp [ i ] [ sum ] = res ; } void minOp ( vector < int > & A , int N ) { int sum = 0 ; for ( auto it : A ) { sum += it ; } if ( sum % 2 == 0 ) { memset ( dp , -1 , sizeof ( dp ) ) ; int ans = solve ( A , 0 , sum / 2 , N ) ; if ( ans < 0 ans > N ) { cout << " - 1" << endl ; } else { cout << ans << endl ; } } else { cout << " - 1" << endl ; } } int main ( ) { vector < int > A = { 2 , 3 , 1 , 4 } ; int N = A . size ( ) ; minOp ( A , N ) ; return 0 ; }
Count subsequences having average of its elements equal to K | C ++ program for the above approach ; Stores the dp states ; Function to find the count of subsequences having average K ; Base condition ; Three loops for three states ; Recurrence relation ; Stores the sum of dp [ n ] [ j ] [ K * j ] all possible values of j with average K and sum K * j ; Iterate over the range [ 1 , N ] ; Return the final count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 101 ] [ 101 ] [ 1001 ] ; int countAverage ( int n , int K , int * arr ) { dp [ 0 ] [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int k = 0 ; k < n ; k ++ ) { for ( int s = 0 ; s <= 1000 ; s ++ ) { dp [ i + 1 ] [ k + 1 ] [ s + arr [ i ] ] += dp [ i ] [ k ] [ s ] ; dp [ i + 1 ] [ k ] [ s ] += dp [ i ] [ k ] [ s ] ; } } } int cnt = 0 ; for ( int j = 1 ; j <= n ; j ++ ) { cnt += dp [ n ] [ j ] [ K * j ] ; } return cnt ; } int main ( ) { int arr [ ] = { 9 , 7 , 8 , 9 } ; int K = 8 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countAverage ( N , K , arr ) ; return 0 ; }
Count ways to remove pairs from a matrix such that remaining elements can be grouped in vertical or horizontal pairs | C ++ program for the above approach ; Function to count ways to remove pairs such that the remaining elements can be arranged in pairs vertically or horizontally ; Store the size of matrix ; If N is odd , then no such pair exists ; Store the number of required pairs ; Initialize an auxiliary matrix and fill it with 0 s ; Traverse the matrix v [ ] [ ] ; Check if i + j is odd or even ; Increment the value dp [ v [ i ] [ j ] - 1 ] [ 0 ] by 1 ; Increment the value dp [ v [ i ] [ j ] - 1 ] [ 1 ] by 1 ; Iterate in range [ 0 , k - 1 ] using i ; Iterate in range [ i + 1 , k - 1 ] using j ; Update the ans ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void numberofpairs ( vector < vector < int > > v , int k ) { int n = v . size ( ) ; if ( n % 2 == 1 ) { cout << 0 ; return ; } int ans = 0 ; int dp [ k ] [ 2 ] ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = 0 ; j < 2 ; j ++ ) { dp [ i ] [ j ] = 0 ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( ( i + j ) % 2 == 0 ) dp [ v [ i ] [ j ] - 1 ] [ 0 ] ++ ; else dp [ v [ i ] [ j ] - 1 ] [ 1 ] ++ ; } } for ( int i = 0 ; i < k ; i ++ ) { for ( int j = i + 1 ; j < k ; j ++ ) { ans += dp [ i ] [ 0 ] * dp [ j ] [ 1 ] ; ans += dp [ i ] [ 1 ] * dp [ j ] [ 0 ] ; } } cout << ans ; } int main ( ) { vector < vector < int > > mat = { { 1 , 2 } , { 3 , 4 } } ; int K = 4 ; numberofpairs ( mat , K ) ; return 0 ; }
Maximize sum by selecting X different | C ++ program for the above approach ; Store overlapping subproblems of the recurrence relation ; Function to find maximum sum of at most N with different index array elements such that at most X are from A [ ] , Y are from B [ ] and Z are from C [ ] ; Base Cases ; If the subproblem already computed ; Selecting i - th element from A [ ] ; Selecting i - th element from B [ ] ; Selecting i - th element from C [ ] ; i - th elements not selected from any of the arrays ; Select the maximum sum from all the possible calls ; Driver Code ; Given X , Y and Z ; Given A [ ] ; Given B [ ] ; Given C [ ] ; Given Size ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 50 ] [ 50 ] [ 50 ] [ 50 ] ; int FindMaxS ( int X , int Y , int Z , int n , vector < int > & A , vector < int > & B , vector < int > & C ) { if ( X < 0 or Y < 0 or Z < 0 ) return INT_MIN ; if ( n < 0 ) return 0 ; if ( dp [ n ] [ X ] [ Y ] [ Z ] != -1 ) { return dp [ n ] [ X ] [ Y ] [ Z ] ; } int ch = A [ n ] + FindMaxS ( X - 1 , Y , Z , n - 1 , A , B , C ) ; int ca = B [ n ] + FindMaxS ( X , Y - 1 , Z , n - 1 , A , B , C ) ; int co = C [ n ] + FindMaxS ( X , Y , Z - 1 , n - 1 , A , B , C ) ; int no = FindMaxS ( X , Y , Z , n - 1 , A , B , C ) ; int maximum = max ( ch , max ( ca , max ( co , no ) ) ) ; return dp [ n ] [ X ] [ Y ] [ Z ] = maximum ; } int main ( ) { int X = 1 ; int Y = 1 ; int Z = 1 ; vector < int > A = { 10 , 0 , 5 } ; vector < int > B = { 5 , 10 , 0 } ; vector < int > C = { 0 , 5 , 10 } ; int n = B . size ( ) ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << FindMaxS ( X , Y , Z , n - 1 , A , B , C ) ; }
Minimize swaps of adjacent characters to sort every possible rearrangement of given Binary String | C ++ program for the above approach ; Precalculate the values of power of 2 ; Function to calculate 2 ^ N % mod ; Function to find sum of inversions ; Initialise a list of 0 s and ? s ; Traverse the string in the reversed manner ; If the current character is 1 ; Effectively calculate a * b ^ ( b - 1 ) ; If the current character is 0 ; Increment count of zeroes ; Double count the zeroes ; Find b * 2 ^ ( b - 1 ) ; Increment count of questions ; Return the final count ; Driver Code ; Given string S ; Function Call
#include <bits/stdc++.h> NEW_LINE #define MOD 1000000007 NEW_LINE using namespace std ; vector < int > MEM = { 1 , 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 , 512 , 1024 , 2048 , 4096 } ; int mod_pow2 ( int n ) { while ( n >= MEM . size ( ) ) MEM . push_back ( ( MEM [ -1 ] * 2 ) % MOD ) ; return MEM [ n ] ; } int inversions ( string bstr ) { int total = 0 , zeros = 0 , questions = 0 ; reverse ( bstr . begin ( ) , bstr . end ( ) ) ; for ( char x : bstr ) { int q ; if ( x == '1' ) { int z = zeros * mod_pow2 ( questions ) ; if ( questions == 0 ) q = 0 ; else q = questions * mod_pow2 ( questions - 1 ) ; total = ( total + z + q ) % MOD ; } else if ( x == '0' ) { zeros += 1 ; } else { total *= 2 ; int z = zeros * mod_pow2 ( questions ) ; if ( questions == 0 ) q = 0 ; else q = questions * mod_pow2 ( questions - 1 ) ; total = ( total + z + q ) % MOD ; questions += 1 ; } } return total ; } int main ( ) { string S = " ? 0 ? " ; cout << inversions ( S ) ; }
Minimum removals required to convert given array to a Mountain Array | C ++ program of the above approach ; Utility function to count array elements required to be removed to make array a mountain array ; Stores length of increasing subsequence from [ 0 , i - 1 ] ; Stores length of increasing subsequence from [ i + 1 , n - 1 ] ; Iterate for each position up to N - 1 to find the length of subsequence ; If j is less than i , then i - th position has leftIncreasing [ j ] + 1 lesser elements including itself ; Check if it is the maximum obtained so far ; Search for increasing subsequence from right ; Find the position following the peak condition and have maximum leftIncreasing [ i ] + rightIncreasing [ i ] ; Function to count elements to be removed to make array a mountain array ; Print the answer ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minRemovalsUtil ( int arr [ ] , int n ) { int result = 0 ; if ( n < 3 ) { return -1 ; } int leftIncreasing [ n ] = { 0 } ; int rightIncreasing [ n ] = { 0 } ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ j ] < arr [ i ] ) { leftIncreasing [ i ] = max ( leftIncreasing [ i ] , leftIncreasing [ j ] + 1 ) ; } } } for ( int i = n - 2 ; i >= 0 ; i -- ) { for ( int j = n - 1 ; j > i ; j -- ) { if ( arr [ j ] < arr [ i ] ) { rightIncreasing [ i ] = max ( rightIncreasing [ i ] , rightIncreasing [ j ] + 1 ) ; } } } for ( int i = 0 ; i < n ; i ++ ) { if ( leftIncreasing [ i ] != 0 && rightIncreasing [ i ] != 0 ) { result = max ( result , leftIncreasing [ i ] + rightIncreasing [ i ] ) ; } } return n - ( result + 1 ) ; } void minRemovals ( int arr [ ] , int n ) { int ans = minRemovalsUtil ( arr , n ) ; cout << ans ; } int main ( ) { int arr [ ] = { 2 , 1 , 1 , 5 , 6 , 2 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minRemovals ( arr , n ) ; return 0 ; }
Minimum number of jumps to obtain an element of opposite parity | C ++ program for the above approach ; Bfs for odd numbers are source ; Initialize queue ; Stores for each node , the nodes visited and their distances ; If parity is 0 -> odd Otherwise -> even ; Perform multi - source bfs ; Extract the front element of the queue ; Traverse nodes connected to the current node ; If u is not visited ; If element with opposite parity is obtained ; Store its distance from source in ans [ ] ; Push the current neighbour to the queue ; Function to find the minimum jumps required by each index to reach element of opposite parity ; Initialise Inverse Graph ; Stores the result for each index ; For the jumped index ; If the ind is valid then add reverse directed edge ; Multi - source bfs with odd numbers as source by passing 0 ; Multi - source bfs with even numbers as source by passing 1 ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void bfs ( int n , vector < int > & a , vector < int > invGr [ ] , vector < int > & ans , int parity ) { queue < int > q ; vector < int > vis ( n + 1 , 0 ) ; vector < int > dist ( n + 1 , 0 ) ; for ( int i = 1 ; i <= n ; i ++ ) { if ( ( a [ i ] + parity ) & 1 ) { q . push ( i ) ; vis [ i ] = 1 ; } } while ( ! q . empty ( ) ) { int v = q . front ( ) ; q . pop ( ) ; for ( int u : invGr [ v ] ) { if ( ! vis [ u ] ) { dist [ u ] = dist [ v ] + 1 ; vis [ u ] = 1 ; if ( ( a [ u ] + parity ) % 2 == 0 ) { if ( ans [ u ] == -1 ) ans [ u ] = dist [ u ] ; } q . push ( u ) ; } } } } void minJumps ( vector < int > & a , vector < int > & jump , int n ) { vector < int > invGr [ n + 1 ] ; vector < int > ans ( n + 1 , -1 ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int ind : { i + jump [ i ] , i - jump [ i ] } ) { if ( ind >= 1 and ind <= n ) { invGr [ ind ] . push_back ( i ) ; } } } bfs ( n , a , invGr , ans , 0 ) ; bfs ( n , a , invGr , ans , 1 ) ; for ( int i = 1 ; i <= n ; i ++ ) { cout << ans [ i ] << ' ▁ ' ; } } int main ( ) { vector < int > arr = { 0 , 4 , 2 , 5 , 2 , 1 } ; vector < int > jump = { 0 , 1 , 2 , 3 , 1 , 2 } ; int N = arr . size ( ) ; minJumps ( arr , jump , N - 1 ) ; return 0 ; }
Longest subsequence having maximum GCD between any pair of distinct elements | C ++ program for the above approach ; Function to find GCD of pair with maximum GCD ; Stores maximum element of arr [ ] ; Find the maximum element ; Maintain a count array ; Store the frequency of arr [ ] ; Stores the multiples of a number ; Iterate over the range [ MAX , 1 ] ; Iterate from current potential GCD till it is less than MAX ; A multiple found ; Increment potential GCD by itself io check i , 2 i , 3 i ... ; If 2 multiples found max GCD found ; Function to find longest subsequence such that GCD of any two distinct integers is maximum ; Base Cases ; Compare current GCD to the maximum GCD ; If true increment and move the pointer ; Return max of either subsequences ; Driver Code ; Sorted array ; Function call to calculate GCD of pair with maximum GCD ; Print the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxGCD ( int arr [ ] , int N ) { int high = 0 ; for ( int i = 0 ; i < N ; i ++ ) { high = max ( high , arr [ i ] ) ; } int count [ high + 1 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { count [ arr [ i ] ] += 1 ; } int counter = 0 ; for ( int i = high ; i > 0 ; i -- ) { int j = i ; while ( j <= high ) { if ( count [ j ] > 0 ) counter += count [ j ] ; j += i ; if ( counter == 2 ) return i ; } counter = 0 ; } } int maxlen ( int i , int j , int arr [ ] , int arr1 [ ] , int N , int maxgcd ) { int a = 1 ; if ( i >= N or j >= N ) return 0 ; if ( __gcd ( arr [ i ] , arr1 [ j ] ) == maxgcd && arr [ i ] != arr1 [ j ] ) { a = max ( a , 1 + maxlen ( i , j + 1 , arr , arr1 , N , maxgcd ) ) ; return a ; } return max ( maxlen ( i + 1 , j , arr , arr1 , N , maxgcd ) , maxlen ( i , j + 1 , arr , arr1 , N , maxgcd ) ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 8 , 5 , 6 } ; int arr1 [ ] = { 1 , 2 , 8 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sort ( arr , arr + n ) ; sort ( arr1 , arr1 + n ) ; int maxgcd = findMaxGCD ( arr , n ) ; cout << maxlen ( 0 , 0 , arr , arr1 , n , maxgcd ) + 1 ; }
Count unique paths is a matrix whose product of elements contains odd number of divisors | C ++ program for the above approach ; Stores the results ; Count of unique product paths ; Function to check whether number is perfect square or not ; If square root is an integer ; Function to calculate and store all the paths product in vector ; Store the value a [ 0 ] [ 0 ] ; Initialize first row of dp ; Find prefix product ; Initialize first column of dp ; Find the prefix product ; Iterate over range ( 1 , 1 ) to ( N , M ) ; Copy dp [ i - 1 ] [ j ] in top [ ] ; Copy dp [ i ] [ j - 1 ] into left [ ] ; Compute the values of current state and store it in curr [ ] ; Find the product of a [ i ] [ j ] with elements at top [ ] ; Find the product of a [ i ] [ j ] with elements at left [ ] ; Update the current state ; Traverse dp [ m - 1 ] [ n - 1 ] ; Check if perfect square ; Driver Code ; Given matrix mat [ ] [ ] ; Function Call ; Print the final count
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < vector < int > > > dp ( 105 , vector < vector < int > > ( 105 ) ) ; int countPaths = 0 ; bool isPerfectSquare ( int n ) { long double sr = sqrt ( n ) ; return ( ( sr - floor ( sr ) ) == 0 ) ; } void countUniquePaths ( int a [ ] [ 105 ] , int m , int n , int ans ) { dp [ 0 ] [ 0 ] . push_back ( a [ 0 ] [ 0 ] ) ; for ( int i = 1 ; i < m ; i ++ ) { a [ i ] [ 0 ] *= a [ i - 1 ] [ 0 ] ; dp [ i ] [ 0 ] . push_back ( a [ i ] [ 0 ] ) ; } for ( int i = 1 ; i < n ; i ++ ) { a [ 0 ] [ i ] *= a [ 0 ] [ i - 1 ] ; dp [ 0 ] [ i ] . push_back ( a [ 0 ] [ i ] ) ; } for ( int i = 1 ; i < m ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) { vector < int > top = dp [ i - 1 ] [ j ] ; vector < int > left = dp [ i ] [ j - 1 ] ; vector < int > curr ; for ( int k = 0 ; k < top . size ( ) ; k ++ ) { curr . push_back ( top [ k ] * a [ i ] [ j ] ) ; } for ( int k = 0 ; k < left . size ( ) ; k ++ ) { curr . push_back ( left [ k ] * a [ i ] [ j ] ) ; } dp [ i ] [ j ] = curr ; } } for ( auto i : dp [ m - 1 ] [ n - 1 ] ) { if ( isPerfectSquare ( i ) ) { countPaths ++ ; } } } int main ( ) { int M = 3 , N = 4 ; int mat [ M ] [ 105 ] = { { 1 , 2 , 3 , 1 } , { 3 , 1 , 2 , 4 } , { 2 , 3 , 1 , 1 } } ; countUniquePaths ( mat , M , N , 1 ) ; cout << countPaths ; return 0 ; }
Generate a combination of minimum coins that sums to a given value | C ++ program for the above approach ; dp array to memoize the results ; List to store the result ; Function to find the minimum number of coins to make the sum equals to X ; Base case ; If previously computed subproblem occurred ; Initialize result ; Try every coin that has smaller value than n ; Check for INT_MAX to avoid overflow and see if result can be minimized ; Memoizing value of current state ; Function to find the possible combination of coins to make the sum equal to X ; Base Case ; Print Solutions ; Try every coin that has value smaller than n ; Add current denominations ; Backtrack ; Function to find the minimum combinations of coins for value X ; Initialize dp with - 1 ; Min coins ; If no solution exists ; Backtrack to find the solution ; Driver code ; Set of possible denominations ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100000 NEW_LINE int dp [ MAX + 1 ] ; list < int > denomination ; int countMinCoins ( int n , int C [ ] , int m ) { if ( n == 0 ) { dp [ 0 ] = 0 ; return 0 ; } if ( dp [ n ] != -1 ) return dp [ n ] ; int ret = INT_MAX ; for ( int i = 0 ; i < m ; i ++ ) { if ( C [ i ] <= n ) { int x = countMinCoins ( n - C [ i ] , C , m ) ; if ( x != INT_MAX ) ret = min ( ret , 1 + x ) ; } } dp [ n ] = ret ; return ret ; } void findSolution ( int n , int C [ ] , int m ) { if ( n == 0 ) { for ( auto it : denomination ) { cout << it << ' ▁ ' ; } return ; } for ( int i = 0 ; i < m ; i ++ ) { if ( n - C [ i ] >= 0 and dp [ n - C [ i ] ] + 1 == dp [ n ] ) { denomination . push_back ( C [ i ] ) ; findSolution ( n - C [ i ] , C , m ) ; break ; } } } void countMinCoinsUtil ( int X , int C [ ] , int N ) { memset ( dp , -1 , sizeof ( dp ) ) ; int isPossible = countMinCoins ( X , C , N ) ; if ( isPossible == INT_MAX ) { cout << " - 1" ; } else { findSolution ( X , C , N ) ; } } int main ( ) { int X = 21 ; int arr [ ] = { 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countMinCoinsUtil ( X , arr , N ) ; return 0 ; }
Count all possible paths from top left to bottom right of a Matrix without crossing the diagonal | C ++ Program to implement the above approach ; Function to calculate Binomial Coefficient C ( n , r ) ; C ( n , r ) = C ( n , n - r ) ; [ n * ( n - 1 ) * -- - * ( n - r + 1 ) ] / [ r * ( r - 1 ) * -- -- * 1 ] ; Function to calculate the total possible paths ; Update n to n - 1 as ( N - 1 ) catalan number is the result ; Stores 2 nCn ; Stores Nth Catalan number ; Stores the required answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binCoff ( int n , int r ) { int val = 1 ; int i ; if ( r > ( n - r ) ) { r = ( n - r ) ; } for ( i = 0 ; i < r ; i ++ ) { val *= ( n - i ) ; val /= ( i + 1 ) ; } return val ; } int findWays ( int n ) { n -- ; int a , b , ans ; a = binCoff ( 2 * n , n ) ; b = a / ( n + 1 ) ; ans = b ; return ans ; } int main ( ) { int n = 4 ; cout << findWays ( n ) ; return 0 ; }
Minimum operations to transform given string to another by moving characters to front or end | C ++ program for the above approach ; Function that finds the minimum number of steps to find the minimum characters must be moved to convert string s to t ; r = maximum value over all dp [ i ] [ j ] computed so far ; dp [ i ] [ j ] stores the longest contiguous suffix of T [ 0. . j ] that is subsequence of S [ 0. . i ] ; Update the maximum length ; Return the resulting length ; Driver Code ; Given string s , t ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 1010 ] [ 1010 ] ; int solve ( string s , string t ) { int n = s . size ( ) ; int r = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { dp [ i ] [ j ] = 0 ; if ( i > 0 ) { dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j ] ) ; } if ( s [ i ] == t [ j ] ) { int ans = 1 ; if ( i > 0 && j > 0 ) { ans = 1 + dp [ i - 1 ] [ j - 1 ] ; } dp [ i ] [ j ] = max ( dp [ i ] [ j ] , ans ) ; r = max ( r , dp [ i ] [ j ] ) ; } } } return ( n - r ) ; } int main ( ) { string s = " abcde " ; string t = " edacb " ; cout << solve ( s , t ) ; return 0 ; }
Longest substring whose characters can be rearranged to form a Palindrome | C ++ program for the above approach ; Function to get the length of longest substring whose characters can be arranged to form a palindromic string ; To keep track of the last index of each xor ; Initialize answer with 0 ; Now iterate through each character of the string ; Convert the character from [ a , z ] to [ 0 , 25 ] ; Turn the temp - th bit on if character occurs odd number of times and turn off the temp - th bit off if the character occurs ever number of times ; If a mask is present in the index Therefore a palindrome is found from index [ mask ] to i ; If x is not found then add its position in the index dict . ; Check for the palindrome of odd length ; We cancel the occurrence of a character if it occurs odd number times ; Driver code ; Given String ; Length of given string ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubstring ( string s , int n ) { map < int , int > index ; int answer = 0 ; int mask = 0 ; index [ mask ] = -1 ; for ( int i = 0 ; i < n ; i ++ ) { int temp = ( int ) s [ i ] - 97 ; mask ^= ( 1 << temp ) ; if ( index [ mask ] ) { answer = max ( answer , i - index [ mask ] ) ; } else index [ mask ] = i ; for ( int j = 0 ; j < 26 ; j ++ ) { int mask2 = mask ^ ( 1 << j ) ; if ( index [ mask2 ] ) { answer = max ( answer , i - index [ mask2 ] ) ; } } } return answer ; } int main ( ) { string s = " adbabd " ; int n = s . size ( ) ; cout << ( longestSubstring ( s , n ) ) ; }
Count of N | C ++ program for the above approach ; Function to find count of N - digit numbers with single digit XOR ; dp [ i ] [ j ] stores the number of i - digit numbers with XOR equal to j ; For 1 - 9 store the value ; Iterate till N ; Calculate XOR ; Store in DP table ; Initialize count ; Print the answer ; Driver Code ; Given number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countNums ( int N ) { int dp [ N ] [ 16 ] ; memset ( dp , 0 , sizeof ( dp [ 0 ] [ 0 ] ) * N * 16 ) ; for ( int i = 1 ; i <= 9 ; i ++ ) dp [ 0 ] [ i ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { for ( int k = 0 ; k < 16 ; k ++ ) { int xo = j ^ k ; dp [ i ] [ xo ] += dp [ i - 1 ] [ k ] ; } } } int count = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) count += dp [ N - 1 ] [ i ] ; cout << ( count ) << endl ; } int main ( ) { int N = 1 ; countNums ( N ) ; }
Count of numbers upto M divisible by given Prime Numbers | C ++ program for the above approach ; Function to count the numbers that are divisible by the numbers in the array from range 1 to M ; Initialize the count variable ; Iterate over [ 1 , M ] ; Iterate over array elements arr [ ] ; Check if i is divisible by a [ j ] ; Increment the count ; Return the answer ; Driver code ; Given array arr [ ] ; Given Number M ; Function Call
#include <iostream> NEW_LINE using namespace std ; int count ( int a [ ] , int M , int N ) { int cnt = 0 ; for ( int i = 1 ; i <= M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i % a [ j ] == 0 ) { cnt ++ ; break ; } } } return cnt ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 7 } ; int m = 100 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << count ( arr , m , n ) ; return 0 ; }
Count of numbers upto N digits formed using digits 0 to K | C ++ implementation to count the numbers upto N digits such that no two zeros are adjacent ; Function to count the numbers upto N digits such that no two zeros are adjacent ; Condition to check if only one element remains ; If last element is non zero , return K - 1 ; If last element is 0 ; Condition to check if value calculated already ; If last element is non zero , then two cases arise , current element can be either zero or non zero ; Memoize this case ; If last is 0 , then current can only be non zero ; Memoize and return ; Driver Code ; Given N and K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 15 ] [ 10 ] ; int solve ( int n , int last , int k ) { if ( n == 1 ) { if ( last == k ) { return ( k - 1 ) ; } else { return 1 ; } } if ( dp [ n ] [ last ] ) return dp [ n ] [ last ] ; if ( last == k ) { return dp [ n ] [ last ] = ( k - 1 ) * solve ( n - 1 , k , k ) + ( k - 1 ) * solve ( n - 1 , 1 , k ) ; } else { return dp [ n ] [ last ] = solve ( n - 1 , k , k ) ; } } int main ( ) { int n = 2 , k = 3 ; int x = solve ( n , k , k ) + solve ( n , 1 , k ) ; cout << x ; }
Count of occurrences of each prefix in a string using modified KMP algorithm | C ++ program for the above approach ; Function to print the count of all prefix in the given string ; Iterate over string s ; Print the prefix and their frequency ; Function to implement the LPS array to store the longest prefix which is also a suffix for every substring of the string S ; Array to store LPS values ; Value of lps [ 0 ] is 0 by definition ; Find the values of LPS [ i ] for the rest of the string using two pointers and DP ; Initially set the value of j as the longest prefix that is also a suffix for i as LPS [ i - 1 ] ; Check if the suffix of length j + 1 is also a prefix ; If s [ i ] = s [ j ] then , assign LPS [ i ] as j + 1 ; If we reached j = 0 , assign LPS [ i ] as 0 as there was no prefix equal to suffix ; Return the calculated LPS array ; Function to count the occurrence of all the prefix in the string S ; Call the prefix_function to get LPS ; To store the occurrence of all the prefix ; Count all the suffixes that are also prefix ; Add the occurences of i to smaller prefixes ; Adding 1 to all occ [ i ] for all the orignal prefix ; Function Call to print the occurence of all the prefix ; Driver Code ; Given String ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print ( vector < int > & occ , string & s ) { for ( int i = 1 ; i <= int ( s . size ( ) ) ; i ++ ) { cout << s . substr ( 0 , i ) << " ▁ occurs ▁ " << occ [ i ] << " ▁ times . " << endl ; } } vector < int > prefix_function ( string & s ) { vector < int > LPS ( s . size ( ) ) ; LPS [ 0 ] = 0 ; for ( int i = 1 ; i < int ( s . size ( ) ) ; i ++ ) { int j = LPS [ i - 1 ] ; while ( j > 0 && s [ i ] != s [ j ] ) { j = LPS [ j - 1 ] ; } if ( s [ i ] == s [ j ] ) { LPS [ i ] = j + 1 ; } else { LPS [ i ] = 0 ; } } return LPS ; } void count_occurence ( string & s ) { int n = s . size ( ) ; vector < int > LPS = prefix_function ( s ) ; vector < int > occ ( n + 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { occ [ LPS [ i ] ] ++ ; } for ( int i = n - 1 ; i > 0 ; i -- ) { occ [ LPS [ i - 1 ] ] += occ [ i ] ; } for ( int i = 0 ; i <= n ; i ++ ) occ [ i ] ++ ; print ( occ , s ) ; } int main ( ) { string A = " ABACABA " ; count_occurence ( A ) ; return 0 ; }
Maximum sum by picking elements from two arrays in order | Set 2 | C ++ program to find maximum sum possible by selecting an element from one of two arrays for every index ; Function to calculate maximum sum ; Maximum elements that can be chosen from array A ; Maximum elements that can be chosen from array B ; Stores the maximum sum possible ; Fill the dp [ ] [ ] for base case when all elements are selected from A [ ] ; Fill the dp [ ] [ ] for base case when all elements are selected from B [ ] ; Return the final answer ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( int A [ ] , int B [ ] , int length , int X , int Y ) { int l = length ; int l1 = min ( length , X ) ; int l2 = min ( length , Y ) ; int dp [ l1 + 1 ] [ l2 + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = 0 ; int max_sum = INT_MIN ; for ( int i = 1 ; i <= l1 ; i ++ ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + A [ i - 1 ] ; max_sum = max ( max_sum , dp [ i ] [ 0 ] ) ; } for ( int i = 1 ; i <= l2 ; i ++ ) { dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + B [ i - 1 ] ; max_sum = max ( max_sum , dp [ 0 ] [ i ] ) ; } for ( int i = 1 ; i <= l1 ; i ++ ) { for ( int j = 1 ; j <= l2 ; j ++ ) { if ( i + j <= l ) dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] + A [ i + j - 1 ] , dp [ i ] [ j - 1 ] + B [ i + j - 1 ] ) ; max_sum = max ( dp [ i ] [ j ] , max_sum ) ; } } return max_sum ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 } ; int B [ ] = { 5 , 4 , 3 , 2 , 1 } ; int X = 3 , Y = 2 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << maximumSum ( A , B , N , X , Y ) ; return 0 ; }
Min number of operations to reduce N to 0 by subtracting any digits from N | C ++ program for the above approach ; Function to reduce an integer N to Zero in minimum operations by removing digits from N ; Initialise dp [ ] to steps ; Iterate for all elements ; For each digit in number i ; Either select the number or do not select it ; dp [ N ] will give minimum step for N ; Driver Code ; Given Number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int reduceZero ( int N ) { vector < int > dp ( N + 1 , 1e9 ) ; dp [ 0 ] = 0 ; for ( int i = 0 ; i <= N ; i ++ ) { for ( char c : to_string ( i ) ) { dp [ i ] = min ( dp [ i ] , dp [ i - ( c - '0' ) ] + 1 ) ; } } return dp [ N ] ; } int main ( ) { int N = 25 ; cout << reduceZero ( N ) ; return 0 ; }
Pentanacci Numbers | C ++ 14 implementation to print Nth Pentanacci numbers . ; Function to print Nth Pentanacci number ; Initialize first five numbers to base cases ; Declare a current variable ; Loop to add previous five numbers for each number starting from 5 and then assign first , second , third , fourth to second , third , fourth and curr to fifth respectively ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printpenta ( int n ) { if ( n < 0 ) return ; int first = 0 ; int second = 0 ; int third = 0 ; int fourth = 0 ; int fifth = 1 ; int curr = 0 ; if ( n == 0 n == 1 n == 2 n == 3 ) cout << first << " STRNEWLINE " ; else if ( n == 5 ) cout << fifth << " STRNEWLINE " ; else { for ( int i = 5 ; i < n ; i ++ ) { curr = first + second + third + fourth + fifth ; first = second ; second = third ; third = fourth ; fourth = fifth ; fifth = curr ; } cout << curr << " STRNEWLINE " ; } } int main ( ) { int n = 10 ; printpenta ( n ) ; return 0 ; }
Count of binary strings of length N with even set bit count and at most K consecutive 1 s | C ++ program for the above approach ; Table to store solution of each subproblem ; Function to calculate the possible binary strings ; If number of ones is equal to K ; pos : current position Base Case : When n length is traversed ; sum : count of 1 ' s ▁ ▁ Return ▁ the ▁ count ▁ ▁ of ▁ 1' s obtained ; If the subproblem has already been solved ; Return the answer ; Recursive call when current position is filled with 1 ; Recursive call when current position is filled with 0 ; Store the solution to this subproblem ; Driver Code ; Initialising the table with - 1
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100001 ] [ 20 ] [ 2 ] ; int possibleBinaries ( int pos , int ones , int sum , int k ) { if ( ones == k ) return 0 ; if ( pos == 0 ) return ( sum == 0 ) ? 1 : 0 ; if ( dp [ pos ] [ ones ] [ sum ] != -1 ) return dp [ pos ] [ ones ] [ sum ] ; int ret = possibleBinaries ( pos - 1 , ones + 1 , ( sum + 1 ) % 2 , k ) + possibleBinaries ( pos - 1 , 0 , sum , k ) ; dp [ pos ] [ ones ] [ sum ] = ret ; return dp [ pos ] [ ones ] [ sum ] ; } int main ( ) { int N = 3 ; int K = 2 ; memset ( dp , -1 , sizeof dp ) ; cout << possibleBinaries ( N , 0 , 0 , K ) ; }
Sum of absolute difference of all pairs raised to power K | C ++ program for the above approach ; Since K can be 100 max ; Constructor ; Initializing with - 1 ; Making vector A as 1 - Indexing ; To Calculate the value nCk ; Since nCj = ( n - 1 ) Cj + ( n - 1 ) C ( j - 1 ) ; ; Function that summation of absolute differences of all pairs raised to the power k ; Sort the given array ; Precomputation part , O ( n * k ) ; Traverse the array arr [ ] ; For each K ; Return the final answer ; Driver Code ; Given N and K ; Given array ; Creation of Object of class ; Function Call
#include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; class Solution { public : ll ncr [ 101 ] [ 101 ] ; int n , k ; vector < ll > A ; Solution ( int N , int K , vector < ll > B ) { memset ( ncr , -1 , sizeof ( ncr ) ) ; n = N ; k = K ; A = B ; A . insert ( A . begin ( ) , 0 ) ; } ll f ( int N , int K ) ; ll pairsPower ( ) ; } ; ll Solution :: f ( int n , int k ) { if ( k == 0 ) return 1LL ; if ( n == k ) return 1LL ; if ( n < k ) return 0 ; if ( ncr [ n ] [ k ] != -1 ) return ncr [ n ] [ k ] ; return ncr [ n ] [ k ] = f ( n - 1 , k ) + f ( n - 1 , k - 1 ) ; } ll Solution :: pairsPower ( ) { ll pre [ n + 1 ] [ k + 1 ] ; ll ans = 0 ; sort ( A . begin ( ) + 1 , A . end ( ) ) ; for ( int i = 1 ; i <= n ; ++ i ) { pre [ i ] [ 0 ] = 1LL ; for ( int j = 1 ; j <= k ; j ++ ) { pre [ i ] [ j ] = A [ i ] * pre [ i ] [ j - 1 ] ; } if ( i != 1 ) { for ( int j = 0 ; j <= k ; ++ j ) pre [ i ] [ j ] = pre [ i ] [ j ] + pre [ i - 1 ] [ j ] ; } } for ( int i = n ; i >= 2 ; -- i ) { for ( int j = 0 ; j <= k ; j ++ ) { ll val = f ( k , j ) ; ll val1 = pow ( A [ i ] , k - j ) * pre [ i - 1 ] [ j ] ; val = val * val1 ; if ( j % 2 == 0 ) ans = ( ans + val ) ; else ans = ( ans - val ) ; } } ans = 2LL * ans ; return ans ; } int main ( ) { int N = 3 ; int K = 3 ; vector < ll > arr = { 1 , 2 , 3 } ; Solution obj ( N , K , arr ) ; cout << obj . pairsPower ( ) << endl ; return 0 ; }
Count of ways to traverse a Matrix and return to origin in K steps | C ++ program to count total number of ways to return to origin after completing given number of steps . ; Function Initialize dp [ ] [ ] [ ] array with - 1 ; Function returns the total count ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD 1000000007 NEW_LINE long long dp [ 101 ] [ 101 ] [ 101 ] ; int N , M , K ; void Initialize ( ) { for ( int i = 0 ; i <= 100 ; i ++ ) for ( int j = 0 ; j <= 100 ; j ++ ) for ( int z = 0 ; z <= 100 ; z ++ ) dp [ i ] [ j ] [ z ] = -1 ; } int CountWays ( int i , int j , int k ) { if ( i >= N i < 0 j > = M j < 0 k < 0 ) return 0 ; if ( i == 0 && j == 0 && k == 0 ) return 1 ; if ( dp [ i ] [ j ] [ k ] != -1 ) return dp [ i ] [ j ] [ k ] ; else dp [ i ] [ j ] [ k ] = ( CountWays ( i + 1 , j , k - 1 ) % MOD + CountWays ( i - 1 , j , k - 1 ) % MOD + CountWays ( i , j - 1 , k - 1 ) % MOD + CountWays ( i , j + 1 , k - 1 ) % MOD + CountWays ( i , j , k - 1 ) % MOD ) % MOD ; return dp [ i ] [ j ] [ k ] ; } int main ( ) { N = 3 ; M = 3 ; K = 4 ; Initialize ( ) ; cout << CountWays ( 0 , 0 , K ) << " STRNEWLINE " ; return 0 ; }
Count of subsequences of length atmost K containing distinct prime elements | C ++ Program to find the count of distinct prime subsequences at most of of length K from a given array ; Initialize all indices as true ; A value in prime [ i ] will finally be false if i is not a prime , else true ; If prime [ p ] is true , then it is a prime ; Update all multiples of p as false , i . e . non - prime ; Returns number of subsequences of maximum length k and contains distinct primes ; Store the primes in the given array ; Sort the primes ; Store the frequencies of all the distinct primes ; Store the frequency of primes ; Store the sum of all frequencies ; Store the length of subsequence at every instant ; Store the frequency ; Store the previous count of updated DP ; Calculate total subsequences of current of_length ; Add the number of subsequences to the answer ; Update the value in dp [ i ] ; Store the updated dp [ i ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime [ 100001 ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p * p <= 100000 ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= 100000 ; i += p ) prime [ i ] = false ; } } } int distinctPrimeSubSeq ( int a [ ] , int n , int k ) { SieveOfEratosthenes ( ) ; vector < int > primes ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ a [ i ] ] ) primes . push_back ( a [ i ] ) ; } int l = primes . size ( ) ; sort ( primes . begin ( ) , primes . end ( ) ) ; vector < int > b ; vector < int > dp ; int sum = 0 ; for ( int i = 0 ; i < l ; ) { int count = 1 , x = a [ i ] ; i ++ ; while ( i < l && a [ i ] == x ) { count ++ ; i ++ ; } b . push_back ( count ) ; dp . push_back ( count ) ; sum += count ; } int of_length = 2 ; int len = dp . size ( ) ; int ans = 0 ; while ( of_length <= k ) { int freq = 0 ; int prev = 0 ; for ( int i = 0 ; i < ( len - 1 ) ; i ++ ) { freq += dp [ i ] ; int j = sum - freq ; int subseq = b [ i ] * j ; ans += subseq ; dp [ i ] = subseq ; prev += dp [ i ] ; } len -- ; sum = prev ; of_length ++ ; } ans += ( l + 1 ) ; return ans ; } int main ( ) { int a [ ] = { 1 , 2 , 2 , 3 , 3 , 4 , 5 } ; int n = sizeof ( a ) / sizeof ( int ) ; int k = 3 ; cout << distinctPrimeSubSeq ( a , n , k ) ; return 0 ; }
Minimize prize count required such that smaller value gets less prize in an adjacent pair | C ++ implementation to find the minimum prizes required such that adjacent smaller elements gets less number of prizes ; Function to find the minimum number of required such that adjacent smaller elements gets less number of prizes ; Loop to iterate over every elements of the array ; Loop to find the consecutive smaller elements at left ; Loop to find the consecutive smaller elements at right ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinPrizes ( int arr [ ] , int n ) { int totalPrizes = 0 , j , x , y ; for ( int i = 0 ; i < n ; i ++ ) { x = 1 ; j = i ; while ( j > 0 && arr [ j ] > arr [ j - 1 ] ) { x ++ ; j -- ; } j = i ; y = 1 ; while ( j < n - 1 && arr [ j ] > arr [ j + 1 ] ) { y ++ ; j ++ ; } totalPrizes += max ( { x , y } ) ; } cout << totalPrizes << endl ; return 0 ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMinPrizes ( arr , n ) ; }
Number of ways to split N as sum of K numbers from the given range | C ++ implementation to count the number of ways to divide N in K groups such that each group has elements in range [ L , R ] ; DP Table ; Function to count the number of ways to divide the number N in K groups such that each group has number of elements in range [ L , R ] ; Base Case ; if N is divides completely into less than k groups ; If the subproblem has been solved , use the value ; put all possible values greater equal to prev ; Function to count the number of ways to divide the number N ; Initialize DP Table as - 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1000000007 ; int dp [ 1000 ] [ 1000 ] ; int calculate ( int pos , int left , int k , int L , int R ) { if ( pos == k ) { if ( left == 0 ) return 1 ; else return 0 ; } if ( left == 0 ) return 0 ; if ( dp [ pos ] [ left ] != -1 ) return dp [ pos ] [ left ] ; int answer = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( i > left ) break ; answer = ( answer + calculate ( pos + 1 , left - i , k , L , R ) ) % mod ; } return dp [ pos ] [ left ] = answer ; } int countWaystoDivide ( int n , int k , int L , int R ) { memset ( dp , -1 , sizeof ( dp ) ) ; return calculate ( 0 , n , k , L , R ) ; } int main ( ) { int N = 12 ; int K = 3 ; int L = 1 ; int R = 5 ; cout << countWaystoDivide ( N , K , L , R ) ; return 0 ; }
Minimum number of squares whose sum equals to given number N | set 2 | C ++ program to represent N as the sum of minimum square numbers . ; Function for finding minimum square numbers ; A [ i ] of array arr store minimum count of square number to get i ; sqrNum [ i ] store last square number to get i ; Initialize ; Find minimum count of square number for all value 1 to n ; In worst case it will be arr [ i - 1 ] + 1 we use all combination of a [ i - 1 ] and add 1 ; Check for all square number less or equal to i ; if it gives less count then update it ; Vector v stores optimum square number whose sum give N ; Driver code ; Calling function ; Printing vector
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > minSqrNum ( int n ) { int arr [ n + 1 ] , k ; int sqrNum [ n + 1 ] ; vector < int > v ; arr [ 0 ] = 0 ; sqrNum [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { arr [ i ] = arr [ i - 1 ] + 1 ; sqrNum [ i ] = 1 ; k = 1 ; while ( k * k <= i ) { if ( arr [ i ] > arr [ i - k * k ] + 1 ) { arr [ i ] = arr [ i - k * k ] + 1 ; sqrNum [ i ] = k * k ; } k ++ ; } } while ( n > 0 ) { v . push_back ( sqrNum [ n ] ) ; n -= sqrNum [ n ] ; } return v ; } int main ( ) { int n = 10 ; vector < int > v ; v = minSqrNum ( n ) ; for ( auto i = v . begin ( ) ; i != v . end ( ) ; i ++ ) { cout << * i ; if ( i + 1 != v . end ( ) ) cout << " ▁ + ▁ " ; } return 0 ; }