text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Length of longest sub | C ++ implementation of the above approach ; Function to find maximum distance between unequal elements ; Calculate maxMean ; Iterate over array and calculate largest subarray with all elements greater or equal to maxMean ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubarray ( int arr [ ] , int n ) { int maxMean = 0 ; for ( int i = 1 ; i < n ; i ++ ) maxMean = max ( maxMean , ( arr [ i ] + arr [ i - 1 ] ) / 2 ) ; int ans = 0 ; int subarrayLength = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] >= maxMean ) ans = max ( ans , ++ subarrayLength ) ; else subarrayLength = 0 ; return ans ; } int main ( ) { int arr [ ] = { 4 , 3 , 3 , 2 , 1 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestSubarray ( arr , n ) ; return 0 ; }
Maximum distance between two unequal elements | C ++ implementation of the approach ; Function to return the maximum distance between two unequal elements ; If first and last elements are unequal they are maximum distance apart ; Fix first element as one of the elements and start traversing from the right ; Break for the first unequal element ; To store the distance from the first element ; Fix last element as one of the elements and start traversing from the left ; Break for the first unequal element ; To store the distance from the last element ; Maximum possible distance ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDistance ( int arr [ ] , int n ) { if ( arr [ 0 ] != arr [ n - 1 ] ) return ( n - 1 ) ; int i = n - 1 ; while ( i > 0 ) { if ( arr [ i ] != arr [ 0 ] ) break ; i -- ; } int distFirst = ( i == 0 ) ? -1 : i ; i = 0 ; while ( i < n - 1 ) { if ( arr [ i ] != arr [ n - 1 ] ) break ; i ++ ; } int distLast = ( i == n - 1 ) ? -1 : ( n - 1 - i ) ; int maxDist = max ( distFirst , distLast ) ; return maxDist ; } int main ( ) { int arr [ ] = { 4 , 4 , 1 , 2 , 1 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxDistance ( arr , n ) ; return 0 ; }
Minimum number of pairs required to make two strings same | C ++ implementation of the approach ; Function which will check if there is a path between a and b by using BFS ; Function to return the minimum number of pairs ; To store the count of pairs ; Iterating through the strings ; Check if we can add an edge in the graph ; Return the count of pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPath ( char a , char b , map < char , vector < char > > & G ) { map < char , bool > visited ; deque < char > queue ; queue . push_back ( a ) ; visited [ a ] = true ; while ( ! queue . empty ( ) ) { int n = queue . front ( ) ; queue . pop_front ( ) ; if ( n == b ) return true ; for ( auto i : G [ n ] ) { if ( visited [ i ] == false ) { queue . push_back ( i ) ; visited [ i ] = true ; } } } return false ; } int countPairs ( string s1 , string s2 , map < char , vector < char > > & G , int x ) { int count = 0 ; for ( int i = 0 ; i < x ; i ++ ) { char a = s1 [ i ] ; char b = s2 [ i ] ; if ( G . find ( a ) != G . end ( ) and G . find ( b ) == G . end ( ) and a != b ) { G [ a ] . push_back ( b ) ; G [ b ] . push_back ( a ) ; count ++ ; } else if ( G . find ( b ) != G . end ( ) and G . find ( a ) == G . end ( ) and a != b ) { G [ b ] . push_back ( a ) ; G [ a ] . push_back ( b ) ; count ++ ; } else if ( G . find ( a ) == G . end ( ) and G . find ( b ) == G . end ( ) and a != b ) { G [ a ] . push_back ( b ) ; G [ b ] . push_back ( a ) ; count ++ ; } else { if ( ! checkPath ( a , b , G ) and a != b ) { G [ a ] . push_back ( b ) ; G [ b ] . push_back ( a ) ; count ++ ; } } } return count ; } int main ( ) { string s1 = " abb " , s2 = " dad " ; int x = s1 . length ( ) ; map < char , vector < char > > G ; cout << countPairs ( s1 , s2 , G , x ) << endl ; return 0 ; }
Generate an array of K elements such that sum of elements is N and the condition a [ i ] < a [ i + 1 ] <= 2 * a [ i ] is met | Set 2 | C ++ implementation of the approach ; Function that print the desired array which satisfies the given conditions ; If the lowest filling condition is void , then it is not possible to generate the required array ; Increase all the elements by cnt ; Start filling from the back till the number is a [ i + 1 ] <= 2 * a [ i ] ; Get the number to be filled ; If it is less than the remaining numbers to be filled ; less than remaining numbers to be filled ; Get the sum of the array ; If this condition is void at any stage during filling up , then print - 1 ; Else add it to the sum ; If the sum condition is not satisified , then print - 1 ; Print the generated array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int n , int k ) { int mini = 0 ; int x1 = 1 ; int a [ k ] ; for ( int i = 1 ; i <= k ; i ++ ) { mini += x1 ; a [ i - 1 ] = x1 ; x1 += 1 ; } if ( n < mini ) { cout << " - 1" ; return ; } int rem = n - mini ; int cnt = rem / k ; rem = rem % k ; for ( int i = 0 ; i < k ; i ++ ) a [ i ] += cnt ; for ( int i = k - 1 ; i > 0 && rem > 0 ; i -- ) { int xx = a [ i - 1 ] * 2 ; int left = xx - a [ i ] ; if ( rem >= left ) { a [ i ] = xx ; rem -= left ; } else { a [ i ] += rem ; rem = 0 ; } } int sum = a [ 0 ] ; for ( int i = 1 ; i < k ; i ++ ) { if ( a [ i ] > 2 * a [ i - 1 ] ) { cout << " - 1" ; return ; } sum += a [ i ] ; } if ( sum != n ) { cout << " - 1" ; return ; } for ( int i = 0 ; i < k ; i ++ ) cout << a [ i ] << " ▁ " ; } int main ( ) { int n = 26 , k = 6 ; solve ( n , k ) ; return 0 ; }
Minimizing array sum by applying XOR operation on all elements of the array | C ++ implementation of the approach ; Function to return the minimized sum ; To store the frequency of bit in every element ; Finding element X ; Taking XOR of elements and finding sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 25 ; int getMinSum ( int arr [ ] , int n ) { int bits_count [ MAX ] , max_bit = 0 , sum = 0 , ans = 0 ; memset ( bits_count , 0 , sizeof ( bits_count ) ) ; for ( int d = 0 ; d < n ; d ++ ) { int e = arr [ d ] , f = 0 ; while ( e > 0 ) { int rem = e % 2 ; e = e / 2 ; if ( rem == 1 ) { bits_count [ f ] += rem ; } f ++ ; } max_bit = max ( max_bit , f ) ; } for ( int d = 0 ; d < max_bit ; d ++ ) { int temp = pow ( 2 , d ) ; if ( bits_count [ d ] > n / 2 ) ans = ans + temp ; } for ( int d = 0 ; d < n ; d ++ ) { arr [ d ] = arr [ d ] ^ ans ; sum = sum + arr [ d ] ; } return sum ; } int main ( ) { int arr [ ] = { 3 , 5 , 7 , 11 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getMinSum ( arr , n ) ; return 0 ; }
Maximum money that can be withdrawn in two steps | C ++ implementation of the approach ; Function to return the maximum coins we can get ; Update elements such that X > Y ; Take from the maximum ; Refill ; Again , take the maximum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxCoins ( int X , int Y ) { if ( X < Y ) swap ( X , Y ) ; int coins = X ; X -- ; coins += max ( X , Y ) ; return coins ; } int main ( ) { int X = 7 , Y = 5 ; cout << maxCoins ( X , Y ) ; return 0 ; }
Minimum value of X to make all array elements equal by either decreasing or increasing by X | C ++ program to implement the above approach ; Function that returns the minimum value of X ; Declare a set ; Iterate in the array element and insert them into the set ; If unique elements is 1 ; Unique elements is 2 ; Get both el2 and el1 ; Check if they are even ; If there are 3 unique elements ; Get three unique elements ; Check if their difference is same ; More than 3 unique elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinimumX ( int a [ ] , int n ) { set < int > st ; for ( int i = 0 ; i < n ; i ++ ) st . insert ( a [ i ] ) ; if ( st . size ( ) == 1 ) return 0 ; if ( st . size ( ) == 2 ) { int el1 = * st . begin ( ) ; int el2 = * st . rbegin ( ) ; if ( ( el2 - el1 ) % 2 == 0 ) return ( el2 - el1 ) / 2 ; else return ( el2 - el1 ) ; } if ( st . size ( ) == 3 ) { auto it = st . begin ( ) ; int el1 = * it ; it ++ ; int el2 = * it ; it ++ ; int el3 = * it ; if ( ( el2 - el1 ) == ( el3 - el2 ) ) return el2 - el1 ; else return -1 ; } return -1 ; } int main ( ) { int a [ ] = { 1 , 4 , 4 , 7 , 4 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findMinimumX ( a , n ) ; return 0 ; }
Maximum elements which can be crossed using given units of a and b | C ++ program to implement the above approach ; Function to find the number of elements crossed ; Keep a copy of a ; Iterate in the binary array ; If no a and b left to use ; If there is no a ; use b and increase a by 1 if arr [ i ] is 1 ; simply use b ; Use a if theres no b ; Increase a and use b if arr [ i ] == 1 ; Use a ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findElementsCrossed ( int arr [ ] , int a , int b , int n ) { int aa = a ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a == 0 && b == 0 ) break ; else if ( a == 0 ) { if ( arr [ i ] == 1 ) { b -= 1 ; a = min ( aa , a + 1 ) ; } else b -= 1 ; } else if ( b == 0 ) a -- ; else if ( arr [ i ] == 1 && a < aa ) { b -= 1 ; a = min ( aa , a + 1 ) ; } else a -- ; ans ++ ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 0 , 0 , 1 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int a = 1 ; int b = 2 ; cout << findElementsCrossed ( arr , a , b , n ) ; return 0 ; }
Move all zeros to start and ones to end in an Array of random integers | C ++ implementation of the approach ; Utility function to print the contents of an array ; Function that pushes all the zeros to the start and ones to the end of an array ; To store the count of elements which are not equal to 1 ; Traverse the array and calculate count of elements which are not 1 ; Now all non - ones elements have been shifted to front and ' count1' is set as index of first 1. Make all elements 1 from count to end . ; Initialize lastNonBinary position to zero ; Traverse the array and pull non - zero elements to the required indices ; Ignore the 1 's ; Mark the position Of last NonBinary integer ; Place non - zero element to their required indices ; Put zeros to start of array ; Driver code
#include <iostream> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } void pushBinaryToBorder ( int arr [ ] , int n ) { int count1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] != 1 ) arr [ count1 ++ ] = arr [ i ] ; while ( count1 < n ) arr [ count1 ++ ] = 1 ; int lastNonOne = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( arr [ i ] == 1 ) continue ; if ( ! lastNonOne ) { lastNonOne = i ; } if ( arr [ i ] != 0 ) arr [ lastNonOne -- ] = arr [ i ] ; } while ( lastNonOne >= 0 ) arr [ lastNonOne -- ] = 0 ; } int main ( ) { int arr [ ] = { 1 , 2 , 0 , 0 , 0 , 3 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pushBinaryToBorder ( arr , n ) ; printArr ( arr , n ) ; return 0 ; }
Count the pairs of vowels in the given string | C ++ implementation of the approach ; Function that return true if character ch is a vowel ; Function to return the count of adjacent vowel pairs in the given string ; If current character and the character after it are both vowels ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char ch ) { switch ( ch ) { case ' a ' : case ' e ' : case ' i ' : case ' o ' : case ' u ' : return true ; default : return false ; } } int vowelPairs ( string s , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( isVowel ( s [ i ] ) && isVowel ( s [ i + 1 ] ) ) cnt ++ ; } return cnt ; } int main ( ) { string s = " abaebio " ; int n = s . length ( ) ; cout << vowelPairs ( s , n ) ; return 0 ; }
Minimum possible final health of the last monster in a game | C ++ implementation of the approach ; Function to return the gcd of two numbers ; Function to return the minimum possible health for the monster ; gcd of first and second element ; gcd for all subsequent elements ; 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 solve ( int * health , int n ) { int currentgcd = gcd ( health [ 0 ] , health [ 1 ] ) ; for ( int i = 2 ; i < n ; ++ i ) { currentgcd = gcd ( currentgcd , health [ i ] ) ; } return currentgcd ; } int main ( ) { int health [ ] = { 4 , 6 , 8 , 12 } ; int n = sizeof ( health ) / sizeof ( health [ 0 ] ) ; cout << solve ( health , n ) ; return 0 ; }
Divide array into increasing and decreasing subsequence without changing the order | C ++ implementation of the approach ; Function to print strictly increasing and strictly decreasing sequence if possible ; Arrays to store strictly increasing and decreasing sequence ; Initializing last element of both sequence ; Iterating through the array ; If current element can be appended to both the sequences ; If next element is greater than the current element Then append it to the strictly increasing array ; Otherwise append it to the strictly decreasing array ; If current element can be appended to the increasing sequence only ; If current element can be appended to the decreasing sequence only ; Else we can not make such sequences from the given array ; Print the required sequences ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Find_Sequence ( int arr [ ] , int n ) { vector < int > inc_arr , dec_arr ; int flag = 0 ; long inc = -1 , dec = 1e7 ; for ( int i = 0 ; i < n ; i ++ ) { if ( inc < arr [ i ] && arr [ i ] < dec ) { if ( arr [ i ] < arr [ i + 1 ] ) { inc = arr [ i ] ; inc_arr . emplace_back ( arr [ i ] ) ; } else { dec = arr [ i ] ; dec_arr . emplace_back ( arr [ i ] ) ; } } else if ( inc < arr [ i ] ) { inc = arr [ i ] ; inc_arr . emplace_back ( arr [ i ] ) ; } else if ( dec > arr [ i ] ) { dec = arr [ i ] ; dec_arr . emplace_back ( arr [ i ] ) ; } else { cout << -1 << endl ; flag = 1 ; break ; } } if ( ! flag ) { for ( auto i = inc_arr . begin ( ) ; i != inc_arr . end ( ) ; i ++ ) cout << * i << " ▁ " ; cout << endl ; for ( auto i = dec_arr . begin ( ) ; i != dec_arr . end ( ) ; i ++ ) cout << * i << " ▁ " ; cout << endl ; } } int main ( ) { int arr [ ] = { 5 , 1 , 3 , 6 , 8 , 2 , 9 , 0 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Find_Sequence ( arr , n ) ; }
Find the sum of digits of a number at even and odd places | C ++ implementation of the approach ; Function to return the reverse of a number ; Function to find the sum of the odd and even positioned digits in a number ; If c is even number then it means digit extracted is at even place ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int reverse ( int n ) { int rev = 0 ; while ( n != 0 ) { rev = ( rev * 10 ) + ( n % 10 ) ; n /= 10 ; } return rev ; } void getSum ( int n ) { n = reverse ( n ) ; int sumOdd = 0 , sumEven = 0 , c = 1 ; while ( n != 0 ) { if ( c % 2 == 0 ) sumEven += n % 10 ; else sumOdd += n % 10 ; n /= 10 ; c ++ ; } cout << " Sum ▁ odd ▁ = ▁ " << sumOdd << " STRNEWLINE " ; cout << " Sum ▁ even ▁ = ▁ " << sumEven ; } int main ( ) { int n = 457892 ; getSum ( n ) ; return 0 ; }
Find the sum of digits of a number at even and odd places | C ++ implementation of the approach ; Function to find the sum of the odd and even positioned digits in a number ; If n is odd then the last digit will be odd positioned ; To store the respective sums ; While there are digits left process ; If current digit is odd positioned ; Even positioned digit ; Invert state ; Remove last digit ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getSum ( int n ) { bool isOdd = ( n % 2 == 1 ) ? true : false ; int sumOdd = 0 , sumEven = 0 ; while ( n != 0 ) { if ( isOdd ) sumOdd += n % 10 ; else sumEven += n % 10 ; isOdd = ! isOdd ; n /= 10 ; } cout << " Sum ▁ odd ▁ = ▁ " << sumOdd << " STRNEWLINE " ; cout << " Sum ▁ even ▁ = ▁ " << sumEven ; } int main ( ) { int n = 457892 ; getSum ( n ) ; return 0 ; }
Count the number of currency notes needed | C ++ implementation of the approach ; Function to return the amount of notes with value A required ; If possible ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int bankNotes ( int A , int B , int S , int N ) { int numerator = S - ( B * N ) ; int denominator = A - B ; if ( numerator % denominator == 0 ) return ( numerator / denominator ) ; return -1 ; } int main ( ) { int A = 1 , B = 2 , S = 7 , N = 5 ; cout << bankNotes ( A , B , S , N ) << endl ; }
Divide a number into two parts | C ++ implementation of the approach ; Function to print the two parts ; Find the position of 4 ; If current character is not '4' but appears after the first occurrence of '4' ; Print both the parts ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void twoParts ( string str ) { int flag = 0 ; string a = " " ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == '4' ) { str [ i ] = '3' ; a += '1' ; flag = 1 ; } else if ( flag ) a += '0' ; } cout << str << " ▁ " << a ; } int main ( ) { string str = "9441" ; twoParts ( str ) ; return 0 ; }
Length of the longest substring with no consecutive same letters | C ++ implementation of the approach ; Function to return the length of the required sub - string ; Get the length of the string ; Iterate in the string ; Check for not consecutive ; If cnt greater than maxi ; Re - initialize ; Check after iteration is complete ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubstring ( string s ) { int cnt = 1 ; int maxi = 1 ; int n = s . length ( ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] != s [ i - 1 ] ) cnt ++ ; else { maxi = max ( cnt , maxi ) ; cnt = 1 ; } } maxi = max ( cnt , maxi ) ; return maxi ; } int main ( ) { string s = " ccccdeededff " ; cout << longestSubstring ( s ) ; return 0 ; }
Minimum number of changes such that elements are first Negative and then Positive | C ++ implementation of the approach ; Function to return the count of minimum operations required ; To store the count of negative integers on the right of the current index ( inclusive ) ; Find the count of negative integers on the right ; If current element is negative ; To store the count of positive elements ; Find the positive integers on the left ; If current element is positive ; Update the answer ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Minimum_Operations ( int a [ ] , int n ) { int np [ n + 1 ] ; np [ n ] = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { np [ i ] = np [ i + 1 ] ; if ( a [ i ] <= 0 ) np [ i ] ++ ; } int pos = 0 ; int ans = n ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( a [ i ] >= 0 ) pos ++ ; ans = min ( ans , pos + np [ i + 1 ] ) ; } return ans ; } int main ( ) { int a [ ] = { -1 , 0 , 1 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << Minimum_Operations ( a , n ) ; return 0 ; }
Sum of elements in an array whose difference with the mean of another array is less than k | C ++ implementation of the approach ; Function for finding sum of elements whose diff with mean is not more than k ; Find the mean of second array ; Find sum of elements from array1 whose difference with mean in not more than k ; Return result ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findSumofEle ( int arr1 [ ] , int m , int arr2 [ ] , int n , int k ) { float arraySum = 0 ; for ( int i = 0 ; i < n ; i ++ ) arraySum += arr2 [ i ] ; float mean = arraySum / n ; int sumOfElements = 0 ; float difference ; for ( int i = 0 ; i < m ; i ++ ) { difference = arr1 [ i ] - mean ; if ( ( difference < 0 ) && ( k > ( -1 ) * difference ) ) { sumOfElements += arr1 [ i ] ; } if ( ( difference >= 0 ) && ( k > difference ) ) { sumOfElements += arr1 [ i ] ; } } return sumOfElements ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 3 , 4 , 7 , 9 } ; int arr2 [ ] = { 0 , 1 , 2 , 1 , 1 , 4 } ; int k = 2 ; int m , n ; m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << findSumofEle ( arr1 , m , arr2 , n , k ) ; return 0 ; }
Find n positive integers that satisfy the given equations | C ++ implementation of the approach ; Function to find n positive integers that satisfy the given conditions ; To store n positive integers ; Place N - 1 one 's ; If can not place ( y - ( n - 1 ) ) as the Nth integer ; Place Nth integer ; To store the sum of squares of N integers ; If it is less than x ; Print the required integers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findIntegers ( int n , int x , int y ) { vector < int > ans ; for ( int i = 0 ; i < n - 1 ; i ++ ) ans . push_back ( 1 ) ; if ( y - ( n - 1 ) <= 0 ) { cout << " - 1" ; return ; } ans . push_back ( y - ( n - 1 ) ) ; int store = 0 ; for ( int i = 0 ; i < n ; i ++ ) store += ans [ i ] * ans [ i ] ; if ( store < x ) { cout << " - 1" ; return ; } for ( int i = 0 ; i < n ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { int n = 3 , x = 254 , y = 18 ; findIntegers ( n , x , y ) ; return 0 ; }
Find the minimum number of steps to reach M from N | CPP program to find minimum number of steps to reach M from N ; Function to find a minimum number of steps to reach M from N ; Continue till m is greater than n ; If m is odd ; add one ; divide m by 2 ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Minsteps ( int n , int m ) { int ans = 0 ; while ( m > n ) { if ( m & 1 ) { m ++ ; ans ++ ; } m /= 2 ; ans ++ ; } return ans + n - m ; } int main ( ) { int n = 4 , m = 6 ; cout << Minsteps ( n , m ) ; return 0 ; }
Find the number of jumps to reach X in the number line from zero | C ++ program to find the number of jumps to reach X in the number line from zero ; Utility function to calculate sum of numbers from 1 to x ; Function to find the number of jumps to reach X in the number line from zero ; First make number positive Answer will be same either it is Positive or negative ; To store required answer ; Continue till number is lesser or not in same parity ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getsum ( int x ) { return ( x * ( x + 1 ) ) / 2 ; } int countJumps ( int n ) { n = abs ( n ) ; int ans = 0 ; while ( getsum ( ans ) < n or ( getsum ( ans ) - n ) & 1 ) ans ++ ; return ans ; } int main ( ) { int n = 9 ; cout << countJumps ( n ) ; return 0 ; }
Maximum number of candies that can be bought | C ++ implementation of the approach ; Function to return the maximum candies that can be bought ; Buy all the candies of the last type ; Starting from second last ; Amount of candies of the current type that can be bought ; Add candies of current type that can be bought ; Update the previous bought amount ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxCandies ( int arr [ ] , int n ) { int prevBought = arr [ n - 1 ] ; int candies = prevBought ; for ( int i = n - 2 ; i >= 0 ; i -- ) { int x = min ( prevBought - 1 , arr [ i ] ) ; if ( x >= 0 ) { candies += x ; prevBought = x ; } } return candies ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 3 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxCandies ( arr , n ) ; 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 absolute sums of positive and negative elements in range i + 1 to N ; calculate difference of both sums ; 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 ; for ( i = 0 ; i < N ; i ++ ) { pos_sum = 0 ; neg_sum = 0 ; for ( j = i + 1 ; j < N ; j ++ ) { if ( arr [ j ] > 0 ) pos_sum += arr [ j ] ; else neg_sum += arr [ j ] ; } diff = abs ( pos_sum ) - abs ( neg_sum ) ; 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 ; }
Minimum cuts required to convert a palindromic string to a different palindromic string | CPP program to solve the above problem ; Function to check if string is palindrome or not ; Function to check if it is possible to get result by making just one cut ; Appending last element in front ; Removing last element ; Checking whether string s2 is palindrome and different from s . ; If length is <= 3 then it is impossible ; Array to store frequency of characters ; Store count of characters in a array ; Condition for edge cases ; Return 1 if it is possible to get palindromic string in just one cut . Else we can always reached in two cuttings . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string s ) { for ( int i = 0 ; i < s . length ( ) ; ++ i ) { if ( s [ i ] != s [ s . length ( ) - i - 1 ] ) { return false ; } } return true ; } bool ans ( string s ) { string s2 = s ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { s2 = s2 . back ( ) + s2 ; s2 . pop_back ( ) ; if ( s != s2 && isPalindrome ( s2 ) ) { return true ; } } return false ; } int solve ( string s ) { if ( s . length ( ) <= 3 ) { return -1 ; } int cnt [ 25 ] = { } ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { cnt [ s [ i ] - ' a ' ] ++ ; } if ( * max_element ( cnt , cnt + 25 ) >= ( s . length ( ) - 1 ) ) { return -1 ; } else { return ( ans ( s ) ? 1 : 2 ) ; } } int main ( ) { string s = " nolon " ; cout << solve ( s ) ; return 0 ; }
Minimum cuts required to convert a palindromic string to a different palindromic string | CPP program to solve the above problem ; Recursive function to find minimum number of cuts if length of string is even ; If length is odd then return 2 ; To check if half of palindromic string is itself a palindrome ; If not then return 1 ; Else call function with half palindromic string ; Function to find minimum number of cuts If length of string is odd ; If length is <= 3 then it is impossible ; Array to store frequency of characters ; Store count of characters in a array ; Condition for edge cases ; If length is even ; If length is odd ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solveEven ( string s ) { if ( s . length ( ) % 2 == 1 ) return 2 ; string ls = s . substr ( 0 , s . length ( ) / 2 ) ; string rs = s . substr ( s . length ( ) / 2 , s . length ( ) ) ; if ( ls != rs ) return 1 ; return solveEven ( ls ) ; } int solveOdd ( string s ) { return 2 ; } int solve ( string s ) { if ( s . length ( ) <= 3 ) { return -1 ; } int cnt [ 25 ] = { } ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { cnt [ s [ i ] - ' a ' ] ++ ; } if ( * max_element ( cnt , cnt + 25 ) >= s . length ( ) - 1 ) { return -1 ; } if ( s . length ( ) % 2 == 0 ) return solveEven ( s ) ; if ( s . length ( ) % 2 == 1 ) return solveOdd ( s ) ; } int main ( ) { string s = " nolon " ; cout << solve ( s ) ; return 0 ; }
Minimum changes required such that the string satisfies the given condition | C ++ implementation of the approach ; Function to return the minimum changes required ; To store the count of minimum changes , number of ones and the number of zeroes ; First character has to be '1' ; If condition fails changes need to be made ; Return the required count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minChanges ( string str , int n ) { int count = 0 , zeros = 0 , ones = 0 ; if ( str [ 0 ] != '1' ) { count ++ ; ones ++ ; } for ( int i = 1 ; i < n ; i ++ ) { if ( str [ i ] == '0' ) zeros ++ ; else ones ++ ; if ( zeros > ones ) { zeros -- ; ones ++ ; count ++ ; } } return count ; } int main ( ) { string str = "0000" ; int n = str . length ( ) ; cout << minChanges ( str , n ) ; return 0 ; }
Count possible moves in the given direction in a grid | C ++ implementation of the above approach ; Function to return the count of possible steps in a single direction ; It can cover infinite steps ; We are approaching towards X = N ; We are approaching towards X = 1 ; Function to return the count of steps ; Take the minimum of both moves independently ; Update count and current positions ; Driver code
#include <bits/stdc++.h> NEW_LINE #define int long long NEW_LINE using namespace std ; int steps ( int cur , int x , int n ) { if ( x == 0 ) return INT_MAX ; if ( x > 0 ) return abs ( ( n - cur ) / x ) ; else return abs ( ( cur - 1 ) / x ) ; } int countSteps ( int curx , int cury , int n , int m , vector < pair < int , int > > moves ) { int count = 0 ; int k = moves . size ( ) ; for ( int i = 0 ; i < k ; i ++ ) { int x = moves [ i ] . first ; int y = moves [ i ] . second ; int stepct = min ( steps ( curx , x , n ) , steps ( cury , y , m ) ) ; count += stepct ; curx += stepct * x ; cury += stepct * y ; } return count ; } main ( ) { int n = 4 , m = 5 , x = 1 , y = 1 ; vector < pair < int , int > > moves = { { 1 , 1 } , { 1 , 1 } , { 0 , -2 } } ; int k = moves . size ( ) ; cout << countSteps ( x , y , n , m , moves ) ; return 0 ; }
Minimum number of elements that should be removed to make the array good | C ++ implementation of the approach ; Function to return the minimum number of elements that must be removed to make the given array good ; Count frequency of each element ; For each element check if there exists another element that makes a valid pair ; If does not exist then increment answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumRemoval ( int n , int a [ ] ) { map < int , int > c ; for ( int i = 0 ; i < n ; i ++ ) c [ a [ i ] ] ++ ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { bool ok = false ; for ( int j = 0 ; j < 31 ; j ++ ) { int x = ( 1 << j ) - a [ i ] ; if ( c . count ( x ) && ( c [ x ] > 1 || ( c [ x ] == 1 && x != a [ i ] ) ) ) { ok = true ; break ; } } if ( ! ok ) ans ++ ; } return ans ; } int main ( ) { int a [ ] = { 4 , 7 , 1 , 5 , 4 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << minimumRemoval ( n , a ) ; return 0 ; }
Minimum elements to be removed such that sum of adjacent elements is always odd | C ++ implementation of the above approach ; Returns the minimum number of eliminations ; Stores the previous element ; Stores the new value ; Check if the previous and current values are of same parity ; Previous value is now the current value ; Return the counter variable ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_elimination ( int n , int arr [ ] ) { int count = 0 ; int prev_val = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { int curr_val = arr [ i ] ; if ( curr_val % 2 == prev_val % 2 ) count ++ ; prev_val = curr_val ; } return count ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 7 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << min_elimination ( n , arr ) ; return 0 ; }
Count all possible N digit numbers that satisfy the given condition | C ++ implementation of above approach ; Function to return the count of required numbers ; If N is odd then return 0 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string getCount ( int N ) { if ( N % 2 == 1 ) return 0 ; string result = "9" ; for ( int i = 1 ; i <= N / 2 - 1 ; i ++ ) result += "0" ; return result ; } int main ( ) { int N = 4 ; cout << getCount ( N ) ; return 0 ; }
Maximum number of teams that can be formed with given persons | C ++ implementation of the approach ; Function that returns true if it possible to form a team with the given n and m ; 1 person of Type1 and 2 persons of Type2 can be chosen ; 1 person of Type2 and 2 persons of Type1 can be chosen ; Cannot from a team ; Function to return the maximum number of teams that can be formed ; To store the required count of teams formed ; Choose 2 persons of Type1 ; And 1 person of Type2 ; Choose 2 persons of Type2 ; And 1 person of Type1 ; Another team has been formed ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool canFormTeam ( int n , int m ) { if ( n >= 1 && m >= 2 ) return true ; if ( m >= 1 && n >= 2 ) return true ; return false ; } int maxTeams ( int n , int m ) { int count = 0 ; while ( canFormTeam ( n , m ) ) { if ( n > m ) { n -= 2 ; m -= 1 ; } else { m -= 2 ; n -= 1 ; } count ++ ; } return count ; } int main ( ) { int n = 4 , m = 5 ; cout << maxTeams ( n , m ) ; return 0 ; }
Find the Side of the smallest Square that can contain given 4 Big Squares | C ++ program to Find the Side of the smallest Square that can contain given 4 Big Squares ; Function to find the maximum of two values ; Function to find the smallest side of the suitable suitcase ; sort array to find the smallest and largest side of suitcases ; side of the suitcase will be smallest if they arranged in 2 x 2 way so find all possible sides of that arrangement ; since suitcase should be square so find maximum of all four side ; now find greatest side and that will be the smallest square ; return the result ; Driver program ; Get the side of the 4 small squares ; Find the smallest side ; Get the side of the 4 small squares ; Find the smallest side
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int max ( long long a , long long b ) { if ( a > b ) return a ; else return b ; } long long int smallestSide ( long long int a [ ] ) { sort ( a , a + 4 ) ; long long side1 , side2 , side3 , side4 , side11 , side12 , sideOfSquare ; side1 = a [ 0 ] + a [ 3 ] ; side2 = a [ 1 ] + a [ 2 ] ; side3 = a [ 0 ] + a [ 1 ] ; side4 = a [ 2 ] + a [ 3 ] ; side11 = max ( side1 , side2 ) ; side12 = max ( side3 , side4 ) ; sideOfSquare = max ( side11 , side12 ) ; return sideOfSquare ; } int main ( ) { long long int side [ 4 ] ; cout << " Test ▁ Case ▁ 1 STRNEWLINE " ; side [ 0 ] = 2 ; side [ 1 ] = 2 ; side [ 2 ] = 2 ; side [ 3 ] = 2 ; cout << smallestSide ( side ) << endl ; cout << " Test Case 2 " side [ 0 ] = 100000000000000 ; side [ 1 ] = 123450000000000 ; side [ 2 ] = 987650000000000 ; side [ 3 ] = 987654321000000 ; cout << smallestSide ( side ) << endl ; return 0 ; }
Rectangle with minimum possible difference between the length and the width | C ++ implementation of the approach ; Function to print the length ( l ) and breadth ( b ) of the rectangle having area = N and | l - b | as minimum as possible ; i is a factor ; l >= sqrt ( area ) >= i ; so here l is + ve always ; Here l and b are length and breadth of the rectangle ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find_rectangle ( int area ) { int l , b ; int M = sqrt ( area ) , ans ; for ( int i = M ; i >= 1 ; i -- ) { if ( area % i == 0 ) { l = ( area / i ) ; b = i ; break ; } } cout << " l ▁ = ▁ " << l << " , ▁ b ▁ = ▁ " << b << endl ; } int main ( ) { int area = 99 ; find_rectangle ( area ) ; return 0 ; }
Rectangle with minimum possible difference between the length and the width | C ++ implementation of the approach ; Function to print the length ( l ) and breadth ( b ) of the rectangle having area = N and | l - b | as minimum as possible ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find_rectangle ( int area ) { for ( int i = ceil ( sqrt ( area ) ) ; i <= area ; i ++ ) { if ( area / i * i == area ) { printf ( " % d ▁ % d " , i , area / i ) ; return ; } } } int main ( ) { int area = 99 ; find_rectangle ( area ) ; return 0 ; }
Largest sub | C ++ implementation of the approach ; Function to return the size of the required sub - set ; Sort the array ; Set to store the contents of the required sub - set ; Insert the elements satisfying the conditions ; Return the size of the set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sizeSubSet ( int a [ ] , int k , int n ) { sort ( a , a + n ) ; unordered_set < int > s ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % k != 0 || s . count ( a [ i ] / k ) == 0 ) s . insert ( a [ i ] ) ; } return s . size ( ) ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 2 ; cout << sizeSubSet ( a , k , n ) ; return 0 ; }
Minimum number of sets with numbers less than Y | C ++ program to find the minimum number sets with consecutive numbers and less than Y ; Function to find the minimum number of shets ; Variable to count the number of sets ; Iterate in the string ; Add the number to string ; Mark that we got a number ; else Every time it exceeds ; Check if previous was anytime less than Y ; Current number ; Check for current number ; Check for last added number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumSets ( string s , int y ) { int cnt = 0 ; int num = 0 ; int l = s . length ( ) ; int f = 0 ; for ( int i = 0 ; i < l ; i ++ ) { num = num * 10 + ( s [ i ] - '0' ) ; if ( num <= y ) f = 1 ; { if ( f ) cnt += 1 ; num = s [ i ] - '0' ; f = 0 ; if ( num <= y ) f = 1 ; else num = 0 ; } } if ( f ) cnt += 1 ; return cnt ; } int main ( ) { string s = "1234" ; int y = 30 ; cout << minimumSets ( s , y ) ; return 0 ; }
Find the non decreasing order array from given array | C ++ implementation of the approach ; Utility function to print the contents of the array ; Function to build array B [ ] ; Lower and upper limits ; To store the required array ; Apply greedy approach ; Print the built array b [ ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int b [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << b [ i ] << " ▁ " ; } void ModifiedArray ( int a [ ] , int n ) { int l = 0 , r = INT_MAX ; int b [ n ] = { 0 } ; for ( int i = 0 ; i < n / 2 ; i ++ ) { b [ i ] = max ( l , a [ i ] - r ) ; b [ n - i - 1 ] = a [ i ] - b [ i ] ; l = b [ i ] ; r = b [ n - i - 1 ] ; } printArr ( b , n ) ; } int main ( ) { int a [ ] = { 5 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; ModifiedArray ( a , 2 * n ) ; return 0 ; }
Count of lines required to write the given String | CPP implementation of the approach ; Function to return the number of lines required ; If string is empty ; Initialize lines and width ; Iterate through S ; Return lines and width used ; Driver Code ; Function call to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; pair < int , int > numberOfLines ( string S , int * widths ) { if ( S . empty ( ) ) return { 0 , 0 } ; int lines = 1 , width = 0 ; for ( auto character : S ) { int w = widths [ character - ' a ' ] ; width += w ; if ( width >= 10 ) { lines ++ ; width = w ; } } return { lines , width } ; } int main ( ) { string S = " bbbcccdddaa " ; int widths [ ] = { 4 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } ; pair < int , int > ans = numberOfLines ( S , widths ) ; cout << ans . first << " ▁ " << ans . second << endl ; return 0 ; }
Check if elements of an array can be arranged satisfying the given condition | C ++ implementation of the approach ; Function to return true if the elements can be arranged in the desired order ; If 2 * x is not found to pair ; Remove an occurrence of x and an occurrence of 2 * x ; Driver Code ; Function call to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; string canReorder ( int A [ ] , int n ) { map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ A [ i ] ] ++ ; sort ( A , A + n ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( m [ A [ i ] ] == 0 ) continue ; if ( m [ 2 * A [ i ] ] ) { count += 2 ; m [ A [ i ] ] -= 1 ; m [ 2 * A [ i ] ] -= 1 ; } } if ( count == n ) return " true " ; else return " false " ; } int main ( ) { int A [ ] = { 4 , -2 , 2 , -4 } ; int n = sizeof ( A ) / sizeof ( int ) ; cout << ( canReorder ( A , n ) ) ; return 0 ; }
Maximum sum of all elements of array after performing given operations | CPP program to find the maximum sum after given operations ; Function to calculate Maximum Subarray Sum or Kadane 's Algorithm ; Function to find the maximum sum after given operations ; To store sum of all elements ; Maximum sum of a subarray ; Calculate the sum of all elements ; Driver Code ; size of an array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubArraySum ( int a [ ] , int size ) { int max_so_far = INT_MIN , max_ending_here = 0 ; for ( int i = 0 ; i < size ; i ++ ) { max_ending_here = max_ending_here + a [ i ] ; if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; if ( max_ending_here < 0 ) max_ending_here = 0 ; } return max_so_far ; } int maxSum ( int a [ ] , int n ) { int S = 0 ; int S1 = maxSubArraySum ( a , n ) ; for ( int i = 0 ; i < n ; i ++ ) S += a [ i ] ; return ( 2 * S1 - S ) ; } int main ( ) { int a [ ] = { -35 , 32 , -24 , 0 , 27 , -10 , 0 , -19 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maxSum ( a , n ) ; return 0 ; }
Minimize the difference between minimum and maximum elements | C ++ program to minimize the difference between minimum and maximum elements ; Function to minimize the difference between minimum and maximum elements ; Find max and min elements of the array ; Check whether the difference between the max and min element is less than or equal to k or not ; Calculate average of max and min ; If the array element is greater than the average then decrease it by k ; If the array element is smaller than the average then increase it by k ; Find max and min of the modified array ; return the new difference ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimizeDiff ( int * arr , int n , int k ) { int max = * ( max_element ( arr , arr + n ) ) ; int min = * ( min_element ( arr , arr + n ) ) ; if ( ( max - min ) <= k ) { return ( max - min ) ; } int avg = ( max + min ) / 2 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > avg ) arr [ i ] -= k ; else arr [ i ] += k ; } max = * ( max_element ( arr , arr + n ) ) ; min = * ( min_element ( arr , arr + n ) ) ; return ( max - min ) ; } int main ( ) { int arr [ ] = { 3 , 16 , 12 , 9 , 20 } ; int n = 5 ; int k = 3 ; cout << " Max ▁ height ▁ difference ▁ = ▁ " << minimizeDiff ( arr , n , k ) << endl ; return 0 ; }
Maximum litres of water that can be bought with N Rupees | CPP implementation of the above approach ; if buying glass bottles is profitable ; Glass bottles that can be bought ; Change budget according the bought bottles ; Plastic bottles that can be bought ; if only plastic bottles need to be bought ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxLitres ( int budget , int plastic , int glass , int refund ) { if ( glass - refund < plastic ) { int ans = max ( ( budget - refund ) / ( glass - refund ) , 0 ) ; budget -= ans * ( glass - refund ) ; ans += budget / plastic ; cout << ans << endl ; } else cout << ( budget / plastic ) << endl ; } int main ( ) { int budget = 10 , plastic = 11 , glass = 9 , refund = 8 ; maxLitres ( budget , plastic , glass , refund ) ; }
Find number from given list for which value of the function is closest to A | C ++ program to find number from given list for which value of the function is closest to A ; Function to find number from given list for which value of the function is closest to A ; Stores the final index ; Declaring a variable to store the minimum absolute difference ; Finding F ( n ) ; Updating the index of the answer if new absolute difference is less than tmp ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int leastValue ( int P , int A , int N , int a [ ] ) { int ans = -1 ; float tmp = ( float ) INFINITY ; for ( int i = 0 ; i < N ; i ++ ) { float t = P - a [ i ] * 0.006 ; if ( abs ( t - A ) < tmp ) { tmp = abs ( t - A ) ; ans = i ; } } return a [ ans ] ; } int main ( ) { int N = 2 , P = 12 , A = 2005 ; int a [ ] = { 1000 , 2000 } ; cout << leastValue ( P , A , N , a ) << endl ; }
Find permutation of n which is divisible by 3 but not divisible by 6 | C ++ program to find permutation of n which is divisible by 3 but not divisible by 6 ; Function to find the permutation ; length of integer ; if integer is even ; return odd integer ; rotate integer ; return - 1 in case no required permutation exists ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findPermutation ( int n ) { int len = ceil ( log10 ( n ) ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( n % 2 != 0 ) { return n ; } else { n = ( n / 10 ) + ( n % 10 ) * pow ( 10 , len - i - 1 ) ; continue ; } } return -1 ; } int main ( ) { int n = 132 ; cout << findPermutation ( n ) ; return 0 ; }
Maximum score after flipping a Binary Matrix atmost K times | C ++ program to find the maximum score after flipping a Binary Matrix atmost K times ; Function to find maximum score of matrix ; find value of rows having first column value equal to zero ; update those rows which lead to maximum score after toggle ; Calculating answer ; check if K > 0 we can toggle if necessary . ; return max answer possible ; Driver program ; function call to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int n = 3 ; const int m = 4 ; int maxMatrixScore ( int A [ n ] [ m ] , int K ) { map < int , int > update ; for ( int i = 0 ; i < n ; ++ i ) { if ( A [ i ] [ 0 ] == 0 ) { int ans = 0 ; for ( int j = 1 ; j < m ; ++ j ) ans = ans + A [ i ] [ j ] * pow ( 2 , m - j - 1 ) ; update [ ans ] = i ; } } map < int , int > :: iterator it = update . begin ( ) ; while ( K > 0 && it != update . end ( ) ) { int idx = it -> second ; for ( int j = 0 ; j < m ; ++ j ) A [ idx ] [ j ] = ( A [ idx ] [ j ] + 1 ) % 2 ; it ++ ; K -- ; } int ans = 0 ; for ( int j = 0 ; j < m ; ++ j ) { int zero = 0 , one = 0 ; for ( int i = 0 ; i < n ; ++ i ) { A [ i ] [ j ] == 0 ? zero ++ : one ++ ; } if ( K > 0 && zero > one ) { ans += zero * pow ( 2 , m - j - 1 ) ; K -- ; } else ans += one * pow ( 2 , m - j - 1 ) ; } return ans ; } int main ( ) { int A [ n ] [ m ] = { { 0 , 0 , 1 , 1 } , { 1 , 0 , 1 , 0 } , { 1 , 1 , 0 , 0 } } ; int K = 2 ; cout << maxMatrixScore ( A , K ) ; return 0 ; }
Check if it is possible to serve customer queue with different notes | C ++ implementation of the approach ; Function that returns true is selling of the tickets is possible ; Nothing to return to the customer ; Check if 25 can be returned to customer . ; Try returning one 50 and one 25 ; Try returning three 25 ; If the loop did not break , all the tickets were sold ; Driver Program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSellingPossible ( int n , int a [ ] ) { int i , c25 = 0 , c50 = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 25 ) c25 ++ ; else if ( a [ i ] == 50 ) { c50 ++ ; if ( c25 == 0 ) break ; c25 -- ; } else { if ( c50 > 0 && c25 > 0 ) { c50 -- ; c25 -- ; } else if ( c25 >= 3 ) c25 -= 3 ; else break ; } } if ( i == n ) return true ; else return false ; } int main ( ) { int a [ ] = { 25 , 25 , 50 , 100 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( isSellingPossible ( n , a ) ) { cout << " YES " ; } else { cout << " NO " ; } }
Check if a cell can be visited more than once in a String | C ++ program to check if any cell of the string can be visited more than once ; Function to check if any cell can be visited more than once ; Array to mark cells ; Traverse the string ; Increase the visit count of the left and right cells within the array which can be visited ; If any cell can be visited more than once Return True ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkIfOverlap ( string str ) { int len = str . length ( ) ; int visited [ len + 1 ] = { 0 } ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == ' . ' ) continue ; for ( int j = max ( 0 , i - str [ i ] ) ; j <= min ( len , i + str [ i ] ) ; j ++ ) visited [ j ] ++ ; } for ( int i = 0 ; i < len ; i ++ ) { if ( visited [ i ] > 1 ) { return true ; } } return false ; } int main ( ) { string str = " . 2 . . 2 . " ; if ( checkIfOverlap ( str ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Check if a number has digits in the given Order | CPP program to check if the digits are in the given order ; Check if the digits follow the correct order ; to store the previous digit ; pointer to tell what type of sequence are we dealing with ; check if we have same digit as the previous digit ; checking the peak point of the number ; check if we have same digit as the previous digit ; check if the digit is greater than the previous one If true , then break from the loop as we are in descending order part ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isCorrectOrder ( int n ) { bool flag = true ; int prev = -1 ; int type = -1 ; while ( n != 0 ) { if ( type == -1 ) { if ( prev == -1 ) { prev = n % 10 ; n = n / 10 ; continue ; } if ( prev == n % 10 ) { flag = false ; break ; } if ( prev > n % 10 ) { type = 1 ; prev = n % 10 ; n = n / 10 ; continue ; } prev = n % 10 ; n = n / 10 ; } else { if ( prev == n % 10 ) { flag = false ; break ; } if ( prev < n % 10 ) { flag = false ; break ; } prev = n % 10 ; n = n / 10 ; } } return flag ; } int main ( ) { int n = 123454321 ; if ( isCorrectOrder ( n ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Coin game of two corners ( Greedy Approach ) | CPP program to find coins to be picked to make sure that we never loose . ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Find sum of odd positioned coins ; Find sum of even positioned coins ; Print even or odd coins depending upon which sum is greater . ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; void printCoins ( int arr [ ] , int n ) { int oddSum = 0 ; for ( int i = 0 ; i < n ; i += 2 ) oddSum += arr [ i ] ; int evenSum = 0 ; for ( int i = 1 ; i < n ; i += 2 ) evenSum += arr [ i ] ; int start = ( ( oddSum > evenSum ) ? 0 : 1 ) ; for ( int i = start ; i < n ; i += 2 ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr1 [ ] = { 8 , 15 , 3 , 7 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; printCoins ( arr1 , n ) ; cout << endl ; int arr2 [ ] = { 2 , 2 , 2 , 2 } ; n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; printCoins ( arr2 , n ) ; cout << endl ; int arr3 [ ] = { 20 , 30 , 2 , 2 , 2 , 10 } ; n = sizeof ( arr3 ) / sizeof ( arr3 [ 0 ] ) ; printCoins ( arr3 , n ) ; return 0 ; }
Final cell position in the matrix | C ++ implementation to find the final cell position in the given matrix ; function to find the final cell position in the given matrix ; to count up , down , left and cright movements ; to store the final coordinate position ; traverse the command array ; calculate final values ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; void finalPos ( char command [ ] , int n , int x , int y ) { int cup , cdown , cleft , cright ; int final_x , final_y ; cup = cdown = cleft = cright = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( command [ i ] == ' U ' ) cup ++ ; else if ( command [ i ] == ' D ' ) cdown ++ ; else if ( command [ i ] == ' L ' ) cleft ++ ; else if ( command [ i ] == ' R ' ) cright ++ ; } final_x = x + ( cright - cleft ) ; final_y = y + ( cdown - cup ) ; cout << " Final ▁ Position : ▁ " << " ( " << final_x << " , ▁ " << final_y << " ) " ; } int main ( ) { char command [ ] = " DDLRULL " ; int n = ( sizeof ( command ) / sizeof ( char ) ) - 1 ; int x = 3 , y = 4 ; finalPos ( command , n , x , y ) ; return 0 ; }
Prim 's Algorithm (Simple Implementation for Adjacency Matrix Representation) | A simple C ++ implementation to find minimum spanning tree for adjacency representation . ; Returns true if edge u - v is a valid edge to be include in MST . An edge is valid if one end is already included in MST and other is not in MST . ; Include first vertex in MST ; Keep adding edges while number of included edges does not become V - 1. ; Find minimum weight valid edge . ; 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 bool isValidEdge ( int u , int v , vector < bool > inMST ) { if ( u == v ) return false ; if ( inMST [ u ] == false && inMST [ v ] == false ) return false ; else if ( inMST [ u ] == true && inMST [ v ] == true ) return false ; return true ; } void primMST ( int cost [ ] [ V ] ) { vector < bool > inMST ( V , false ) ; inMST [ 0 ] = true ; int edge_count = 0 , mincost = 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 ( cost [ i ] [ j ] < min ) { if ( isValidEdge ( i , j , inMST ) ) { min = cost [ i ] [ j ] ; a = i ; b = j ; } } } } if ( a != -1 && b != -1 ) { printf ( " Edge ▁ % d : ( % d , ▁ % d ) ▁ cost : ▁ % d ▁ STRNEWLINE " , edge_count ++ , a , b , min ) ; mincost = mincost + min ; inMST [ b ] = inMST [ a ] = true ; } } 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 } , } ; primMST ( cost ) ; return 0 ; }
Subarray whose absolute sum is closest to K | C ++ code to find non - negative sub - array whose sum shows minimum deviation . This works only if all elements in array are non - negative ; Function to return the index ; Add Last element tp currSum ; Save Difference of previous Iteration ; Calculate new Difference ; When the Sum exceeds K ; Current Difference greater in magnitude . Store Temporary Result ; Difference in Previous was lesser In previous , Right index = j - 1 ; In next iteration , Left Index Increases but Right Index remains the Same Update currSum and i Accordingly ; Case to simply increase Right Index ; Check if lesser deviation found ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Pair { int f , s , t ; Pair ( int f , int s , int t ) { this -> f = f ; this -> s = s ; this -> t = t ; } } ; Pair * getSubArray ( int * arr , int n , int K ) { int currSum = 0 ; int prevDif = 0 ; int currDif = 0 ; Pair * result = new Pair ( -1 , -1 , abs ( K - abs ( currSum ) ) ) ; Pair * resultTmp = result ; int i = 0 ; int j = 0 ; while ( i <= j && j < n ) { currSum += arr [ j ] ; prevDif = currDif ; currDif = K - abs ( currSum ) ; if ( currDif <= 0 ) { if ( abs ( currDif ) < abs ( prevDif ) ) { resultTmp = new Pair ( i , j , currDif ) ; } else { resultTmp = new Pair ( i , j - 1 , prevDif ) ; currSum -= ( arr [ i ] + arr [ j ] ) ; i += 1 ; } } else { resultTmp = new Pair ( i , j , currDif ) ; j += 1 ; } if ( abs ( resultTmp -> t ) < abs ( result -> t ) ) { result = resultTmp ; } } return result ; } int main ( ) { int arr [ ] = { 15 , -3 , 5 , 2 , 7 , 6 , 34 , -6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 50 ; Pair * tmp = getSubArray ( arr , n , K ) ; int i = tmp -> f ; int j = tmp -> s ; int minDev = tmp -> t ; if ( i == -1 ) { cout << " The ▁ empty ▁ array ▁ shows ▁ minimum ▁ Deviation " << endl ; return 0 ; } for ( int k = i + 1 ; k < j + 1 ; k ++ ) { cout << arr [ k ] << " ▁ " ; } return 0 ; }
Length and Breadth of rectangle such that ratio of Area to diagonal ^ 2 is maximum | CPP for finding maximum p ^ 2 / A ratio of rectangle ; function to print length and breadth ; sort the input array ; create array vector of integers occurring in pairs ; push the same pairs ; calculate length and breadth as per requirement ; check for given condition ; print the required answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findLandB ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; vector < double > arr_pairs ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i + 1 ] ) { arr_pairs . push_back ( arr [ i ] ) ; i ++ ; } } double length = arr_pairs [ 0 ] ; double breadth = arr_pairs [ 1 ] ; double size = arr_pairs . size ( ) ; for ( int i = 2 ; i < size ; i ++ ) { if ( ( length / breadth + breadth / length ) > ( arr_pairs [ i ] / arr_pairs [ i - 1 ] + arr_pairs [ i - 1 ] / arr_pairs [ i ] ) ) { length = arr_pairs [ i ] ; breadth = arr_pairs [ i - 1 ] ; } } cout << length << " , ▁ " << breadth << endl ; } int main ( ) { int arr [ ] = { 4 , 2 , 2 , 2 , 5 , 6 , 5 , 6 , 7 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findLandB ( arr , n ) ; return 0 ; }
Smallest sum contiguous subarray | Set | C ++ program for Smallest sum contiguous subarray | Set 2 ; function to find the smallest sum contiguous subarray ; First invert the sign of the elements ; Apply the normal Kadane algorithm But on the elements Of the array having inverted sign ; Invert the answer to get minimum val ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestSumSubarr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = - arr [ i ] ; int sum_here = arr [ 0 ] , max_sum = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { sum_here = max ( sum_here + arr [ i ] , arr [ i ] ) ; max_sum = max ( max_sum , sum_here ) ; } return ( -1 ) * max_sum ; } int main ( ) { int arr [ ] = { 3 , -4 , 2 , -3 , -1 , 7 , -5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Smallest ▁ sum : ▁ " << smallestSumSubarr ( arr , n ) ; return 0 ; }
Find k pairs with smallest sums in two arrays | Set 2 | C ++ program to print the k smallest pairs | Set 2 ; Function to print the K smallest pairs ; if k is greater than total pairs ; _pair _one keeps track of ' first ' in a1 and ' second ' in a2 in _two , _two . first keeps track of element in the a2 [ ] and _two . second in a1 [ ] ; Repeat the above process till all K pairs are printed ; when both the pointers are pointing to the same elements ( point 3 ) ; updates according to step 1 ; if ( _one . second == 0 ) see point 2 ; updates opposite to step 1 ; updates according to rule 1 ; if ( _one . first == 0 ) see point 2 ; updates opposite to rule 1 ; if ( _two . first == 0 ) see point 2 ; else update as necessary ( point 1 ) ; updating according to rule 1 ; if ( _one . second == 0 ) see point 2 ; updating according to rule 1 ; if ( _one . first == 0 ) see point 2 ; updating according to rule 1 ; if ( _two . first == 0 ) see point 2 ; updating according to rule 1 ; if ( _two . second == 0 ) see point 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef struct _pair { int first , second ; } _pair ; void printKPairs ( int a1 [ ] , int a2 [ ] , int size1 , int size2 , int k ) { if ( k > ( size2 * size1 ) ) { cout << " k ▁ pairs ▁ don ' t ▁ exist STRNEWLINE " ; return ; } _pair _one , _two ; _one . first = _one . second = _two . first = _two . second = 0 ; int cnt = 0 ; while ( cnt < k ) { if ( _one . first == _two . second && _two . first == _one . second ) { if ( a1 [ _one . first ] < a2 [ _one . second ] ) { cout << " [ " << a1 [ _one . first ] << " , ▁ " << a2 [ _one . second ] << " ] ▁ " ; _one . second = ( _one . second + 1 ) % size2 ; _one . first = ( _one . first + 1 ) % size1 ; _two . second = ( _two . second + 1 ) % size2 ; if ( _two . second == 0 ) _two . first = ( _two . first + 1 ) % size2 ; } else { cout << " [ " << a2 [ _one . second ] << " , ▁ " << a1 [ _one . first ] << " ] ▁ " ; _one . first = ( _one . first + 1 ) % size1 ; _one . second = ( _one . second + 1 ) % size2 ; _two . first = ( _two . first + 1 ) % size2 ; _two . second = ( _two . second + 1 ) % size1 ; } } else if ( a1 [ _one . first ] + a2 [ _one . second ] <= a2 [ _two . first ] + a1 [ _two . second ] ) { if ( a1 [ _one . first ] < a2 [ _one . second ] ) { cout << " [ " << a1 [ _one . first ] << " , ▁ " << a2 [ _one . second ] << " ] ▁ " ; _one . second = ( ( _one . second + 1 ) % size2 ) ; _one . first = ( _one . first + 1 ) % size1 ; } else { cout << " [ " << a2 [ _one . second ] << " , ▁ " << a1 [ _one . first ] << " ] ▁ " ; _one . first = ( ( _one . first + 1 ) % size1 ) ; _one . second = ( _one . second + 1 ) % size2 ; } } else if ( a1 [ _one . first ] + a2 [ _one . second ] > a2 [ _two . first ] + a1 [ _two . second ] ) { if ( a2 [ _two . first ] < a1 [ _two . second ] ) { cout << " [ " << a2 [ _two . first ] << " , ▁ " << a1 [ _two . second ] << " ] ▁ " ; _two . first = ( ( _two . first + 1 ) % size2 ) ; _two . second = ( _two . second + 1 ) % size1 ; } else { cout << " [ " << a1 [ _two . second ] << " , ▁ " << a2 [ _two . first ] << " ] ▁ " ; _two . second = ( ( _two . second + 1 ) % size1 ) ; _two . first = ( _two . first + 1 ) % size1 ; } } cnt ++ ; } } int main ( ) { int a1 [ ] = { 2 , 3 , 4 } ; int a2 [ ] = { 1 , 6 , 5 , 8 } ; int size1 = sizeof ( a1 ) / sizeof ( a1 [ 0 ] ) ; int size2 = sizeof ( a2 ) / sizeof ( a2 [ 0 ] ) ; int k = 4 ; printKPairs ( a1 , a2 , size1 , size2 , k ) ; return 0 ; }
Maximum number by concatenating every element in a rotation of an array | C ++ program to print the Maximum number by concatenating every element in rotation of array ; Function to print the largest number ; store the index of largest left most digit of elements ; Iterate for all numbers ; check for the last digit ; check for the largest left most digit ; print the rotation of array ; print the rotation of array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printLargest ( int a [ ] , int n ) { int max = -1 ; int ind = -1 ; for ( int i = 0 ; i < n ; i ++ ) { int num = a [ i ] ; while ( num ) { int r = num % 10 ; num = num / 10 ; if ( num == 0 ) { if ( max < r ) { max = r ; ind = i ; } } } } for ( int i = ind ; i < n ; i ++ ) cout << a [ i ] ; for ( int i = 0 ; i < ind ; i ++ ) cout << a [ i ] ; } int main ( ) { int a [ ] = { 54 , 546 , 548 , 60 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printLargest ( a , n ) ; return 0 ; }
Minimum number of operations to convert a given sequence into a Geometric Progression | C ++ program to find minimum number of operations to convert a given sequence to an Geometric Progression ; Function to print the GP series ; Check for possibility ; Function for getting the Arithmetic Progression ; The array c describes all the given set of possible operations . ; Size of c ; candidate answer ; loop through all the permutations of the first two elements . ; a1 and a2 are the candidate first two elements of the possible GP . ; temp stores the current answer , including the modification of the first two elements . ; common ratio of the possible GP ; To check if the chosen set is valid , and id yes find the number of operations it takes . ; ai is value of a [ i ] according to the assumed first two elements a1 , a2 ith element of an GP = a1 * ( ( a2 - a1 ) ^ ( i - 1 ) ) ; Check for the " proposed " element to be only differing by one ; set the temporary ans ; to infinity and break ; update answer ; Calling function to print the sequence ; Driver Code ; array is 1 - indexed , with a [ 0 ] = 0 for the sake of simplicity ; Function to print the minimum operations and the sequence of elements
#include <bits/stdc++.h> NEW_LINE using namespace std ; void construct ( int n , pair < double , double > ans_pair ) { if ( ans_pair . first == -1 ) { cout << " Not ▁ possible " ; return ; } double a1 = ans_pair . first ; double a2 = ans_pair . second ; double r = a2 / a1 ; cout << " The ▁ resultant ▁ sequence ▁ is : STRNEWLINE " ; for ( int i = 1 ; i <= n ; i ++ ) { double ai = a1 * pow ( r , i - 1 ) ; cout << ai << " ▁ " ; } } void findMinimumOperations ( double * a , int n ) { int ans = INT_MAX ; int c [ ] = { -1 , 0 , 1 } ; int possibilities = 3 ; int pos1 = -1 , pos2 = -1 ; for ( int i = 0 ; i < possibilities ; i ++ ) { for ( int j = 0 ; j < possibilities ; j ++ ) { double a1 = a [ 1 ] + c [ i ] ; double a2 = a [ 2 ] + c [ j ] ; int temp = abs ( a1 - a [ 1 ] ) + abs ( a2 - a [ 2 ] ) ; if ( a1 == 0 a2 == 0 ) continue ; double r = a2 / a1 ; for ( int pos = 3 ; pos <= n ; pos ++ ) { double ai = a1 * pow ( r , pos - 1 ) ; if ( a [ pos ] == ai ) { continue ; } else if ( a [ pos ] + 1 == ai a [ pos ] - 1 == ai ) { temp ++ ; } else { temp = INT_MAX ; break ; } } if ( temp < ans ) { ans = temp ; pos1 = a1 ; pos2 = a2 ; } } } if ( ans == -1 ) { cout << " - 1" ; return ; } cout << " Minimum ▁ Number ▁ of ▁ Operations ▁ are ▁ " << ans << " STRNEWLINE " ; pair < double , double > ans_pair = { pos1 , pos2 } ; construct ( n , ans_pair ) ; } int main ( ) { double a [ ] = { 0 , 7 , 20 , 49 , 125 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; findMinimumOperations ( a , n - 1 ) ; return 0 ; }
Optimal Storage on Tapes | CPP Program to find the order of programs for which MRT is minimized ; This functions outputs the required order and Minimum Retrieval Time ; Here length of i 'th program is L[i] ; Lengths of programs sorted according to increasing lengths . This is the order in which the programs have to be stored on tape for minimum MRT ; MRT - Minimum Retrieval Time ; Driver Code to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findOrderMRT ( int L [ ] , int n ) { sort ( L , L + n ) ; cout << " Optimal ▁ order ▁ in ▁ which ▁ programs ▁ are ▁ to ▁ be " " stored ▁ is : ▁ " ; for ( int i = 0 ; i < n ; i ++ ) cout << L [ i ] << " ▁ " ; cout << endl ; double MRT = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j <= i ; j ++ ) sum += L [ j ] ; MRT += sum ; } MRT /= n ; cout << " Minimum ▁ Retrieval ▁ Time ▁ of ▁ this " " ▁ order ▁ is ▁ " << MRT ; } int main ( ) { int L [ ] = { 2 , 5 , 4 } ; int n = sizeof ( L ) / sizeof ( L [ 0 ] ) ; findOrderMRT ( L , n ) ; return 0 ; }
Minimum operations to make GCD of array a multiple of k | CPP program to make GCD of array a multiple of k . ; If array value is not 1 and it is greater than k then we can increase the or decrease the remainder obtained by dividing k from the ith value of array so that we get the number which is either closer to k or its multiple ; Else we only have one choice which is to increment the value to make equal to k ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinOperation ( int a [ ] , int n , int k ) { int result = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( a [ i ] != 1 && a [ i ] > k ) { result = result + min ( a [ i ] % k , k - a [ i ] % k ) ; } else { result = result + k - a [ i ] ; } } return result ; } int main ( ) { int arr [ ] = { 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 5 ; cout << MinOperation ( arr , n , k ) ; return 0 ; }
Maximum product subset of an array | CPP program to find maximum product of a subset . ; Find count of negative numbers , count of zeros , negative number with least absolute value and product of non - zero numbers ; If number is 0 , we don 't multiply it with product. ; Count negatives and keep track of negative number with least absolute value ; If there are all zeros ; If there are odd number of negative numbers ; Exceptional case : There is only negative and all other are zeros ; Otherwise result is product of all non - zeros divided by negative number with least absolute value ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProductSubset ( int a [ ] , int n ) { if ( n == 1 ) return a [ 0 ] ; int max_neg = INT_MIN ; int count_neg = 0 , count_zero = 0 ; int prod = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) { count_zero ++ ; continue ; } if ( a [ i ] < 0 ) { count_neg ++ ; max_neg = max ( max_neg , a [ i ] ) ; } prod = prod * a [ i ] ; } if ( count_zero == n ) return 0 ; if ( count_neg & 1 ) { if ( count_neg == 1 && count_zero > 0 && count_zero + count_neg == n ) return 0 ; prod = prod / max_neg ; } return prod ; } int main ( ) { int a [ ] = { -1 , -1 , -2 , 4 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maxProductSubset ( a , n ) ; return 0 ; }
Minimum cost to process m tasks where switching costs | C ++ Program to find out minimum cost to process m tasks ; Function to find out the farthest position where one of the currently ongoing tasks will rehappen . ; Iterate form last to current position and find where the task will happen next . ; Find out maximum of all these positions and it is the farthest position . ; Function to find out minimum cost to process all the tasks ; freqarr [ i ] [ j ] denotes the frequency of type j task after position i like in array { 1 , 2 , 1 , 3 , 2 , 1 } frequency of type 1 task after position 0 is 2. So , for this array freqarr [ 0 ] [ 1 ] = 2. Here , i can range in between 0 to m - 1 and j can range in between 0 to m ( though there is not any type 0 task ) . ; Fill up the freqarr vector from last to first . After m - 1 th position frequency of all type of tasks will be 0. Then at m - 2 th position only frequency of arr [ m - 1 ] type task will be increased by 1. Again , in m - 3 th position only frequency of type arr [ m - 2 ] task will be increased by 1 and so on . ; isRunning [ i ] denotes whether type i task is currently running in one of the cores . At the beginning no tasks are running so all values are false . ; cost denotes total cost to assign tasks ; truecount denotes number of occupied cores ; iterate through each task and find the total cost . ; ele denotes type of task . ; Case 1 : if same type of task is currently running cost for this is 0. ; Case 2 : same type of task is not currently running . ; Subcase 1 : if there is at least one free core then assign this task to that core at a cost of 1 unit . ; Subcase 2 : No core is free ; set minimum frequency to a big number ; set index of minimum frequency task to 0. ; find the minimum frequency task type ( miniind ) and frequency ( mini ) . ; If minimum frequency is zero then just stop the task and start the present task in that core . Cost for this is 1 unit . ; If minimum frequency is nonzero then find the farthest position where one of the ongoing task will rehappen . Stop that task and start present task in that core . ; find out the farthest position using find function ; return total cost ; Driver Program ; Test case 1 ; Test case 2 ; Test case 3
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( vector < int > arr , int pos , int m , vector < bool > isRunning ) { vector < int > d ( m + 1 , 0 ) ; for ( int i = m ; i > pos ; i -- ) { if ( isRunning [ arr [ i ] ] ) d [ arr [ i ] ] = i ; } int maxipos = 0 ; for ( int ele : d ) maxipos = max ( ele , maxipos ) ; return maxipos ; } int mincost ( int n , int m , vector < int > arr ) { vector < vector < int > > freqarr ( m ) ; vector < int > newvec ( m + 1 , 0 ) ; freqarr [ m - 1 ] = newvec ; for ( int i = m - 2 ; i >= 0 ; i -- ) { vector < int > nv ; nv = freqarr [ i + 1 ] ; nv [ arr [ i + 1 ] ] += 1 ; freqarr [ i ] = nv ; } vector < bool > isRunning ( m + 1 , false ) ; int cost = 0 ; int truecount = 0 ; for ( int i = 0 ; i < m ; i ++ ) { int ele = arr [ i ] ; if ( isRunning [ ele ] == true ) continue ; else { if ( truecount < n ) { cost += 1 ; truecount += 1 ; isRunning [ ele ] = true ; } else { int mini = 100000 ; int miniind = 0 ; for ( int j = 1 ; j <= m ; j ++ ) { if ( isRunning [ j ] && mini > freqarr [ i ] [ j ] ) { mini = freqarr [ i ] [ j ] ; miniind = j ; } } if ( mini == 0 ) { isRunning [ miniind ] = false ; isRunning [ ele ] = true ; cost += 1 ; } else { int farpos = find ( arr , i , m , isRunning ) ; isRunning [ arr [ farpos ] ] = false ; isRunning [ ele ] = true ; cost += 1 ; } } } } return cost ; } int main ( ) { int n1 = 3 ; int m1 = 6 ; vector < int > arr1 { 1 , 2 , 1 , 3 , 4 , 1 } ; cout << mincost ( n1 , m1 , arr1 ) << endl ; int n2 = 2 ; int m2 = 6 ; vector < int > arr2 { 1 , 2 , 1 , 3 , 2 , 1 } ; cout << mincost ( n2 , m2 , arr2 ) << endl ; int n3 = 3 ; int m3 = 31 ; vector < int > arr3 { 7 , 11 , 17 , 10 , 7 , 10 , 2 , 9 , 2 , 18 , 8 , 10 , 20 , 10 , 3 , 20 , 17 , 17 , 17 , 1 , 15 , 10 , 8 , 3 , 3 , 18 , 13 , 2 , 10 , 10 , 11 } ; cout << mincost ( n3 , m3 , arr3 ) << endl ; return 0 ; }
Minimum Fibonacci terms with sum equal to K | C ++ code to find minimum number of fibonacci terms that sum to K . ; Function to calculate Fibonacci Terms ; Calculate all Fibonacci terms which are less than or equal to K . ; If next term is greater than K do not push it in vector and return . ; Function to find the minimum number of Fibonacci terms having sum equal to K . ; Vector to store Fibonacci terms . ; Subtract Fibonacci terms from sum K until sum > 0. ; Divide sum K by j - th Fibonacci term to find how many terms it contribute in sum . ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void calcFiboTerms ( vector < int > & fiboTerms , int K ) { int i = 3 , nextTerm ; fiboTerms . push_back ( 0 ) ; fiboTerms . push_back ( 1 ) ; fiboTerms . push_back ( 1 ) ; while ( 1 ) { nextTerm = fiboTerms [ i - 1 ] + fiboTerms [ i - 2 ] ; if ( nextTerm > K ) return ; fiboTerms . push_back ( nextTerm ) ; i ++ ; } } int findMinTerms ( int K ) { vector < int > fiboTerms ; calcFiboTerms ( fiboTerms , K ) ; int count = 0 , j = fiboTerms . size ( ) - 1 ; while ( K > 0 ) { count += ( K / fiboTerms [ j ] ) ; K %= ( fiboTerms [ j ] ) ; j -- ; } return count ; } int main ( ) { int K = 17 ; cout << findMinTerms ( K ) ; return 0 ; }
Smallest number with sum of digits as N and divisible by 10 ^ N | CPP program to find smallest number to find smallest number with N as sum of digits and divisible by 10 ^ N . ; If N = 0 the string will be 0 ; If n is not perfectly divisible by 9 output the remainder ; Print 9 N / 9 times ; Append N zero 's to the number so as to make it divisible by 10^N ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void digitsNum ( int N ) { if ( N == 0 ) cout << "0 STRNEWLINE " ; if ( N % 9 != 0 ) cout << ( N % 9 ) ; for ( int i = 1 ; i <= ( N / 9 ) ; ++ i ) cout << "9" ; for ( int i = 1 ; i <= N ; ++ i ) cout << "0" ; cout << " STRNEWLINE " ; } int main ( ) { int N = 5 ; cout << " The ▁ number ▁ is ▁ : ▁ " ; digitsNum ( N ) ; return 0 ; }
Divide 1 to n into two groups with minimum sum difference | CPP program to divide n integers in two groups such that absolute difference of their sum is minimum ; To print vector along size ; Print vector size ; Print vector elements ; To divide n in two groups such that absolute difference of their sum is minimum ; Find sum of all elements upto n ; Sum of elements of group1 ; If sum is greater then or equal to 0 include i in group 1 otherwise include in group2 ; Decrease sum of group1 ; Print both the groups ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printVector ( vector < int > v ) { cout << v . size ( ) << endl ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) cout << v [ i ] << " ▁ " ; cout << endl ; } void findTwoGroup ( int n ) { int sum = n * ( n + 1 ) / 2 ; int group1Sum = sum / 2 ; vector < int > group1 , group2 ; for ( int i = n ; i > 0 ; i -- ) { if ( group1Sum - i >= 0 ) { group1 . push_back ( i ) ; group1Sum -= i ; } else { group2 . push_back ( i ) ; } } printVector ( group1 ) ; printVector ( group2 ) ; } int main ( ) { int n = 5 ; findTwoGroup ( n ) ; return 0 ; }
Maximum number of customers that can be satisfied with given quantity | CPP program to find maximum number of customers that can be satisfied ; print maximum number of satisfied customers and their indexes ; Creating an vector of pair of total demand and customer number ; Sorting the customers according to their total demand ; Taking the first k customers that can be satisfied by total amount d ; Driver program ; Initializing variables
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < pair < long long , int > > v ; void solve ( int n , int d , int a , int b , int arr [ ] [ 2 ] ) { for ( int i = 0 ; i < n ; i ++ ) { int m = arr [ i ] [ 0 ] , t = arr [ i ] [ 1 ] ; v . push_back ( make_pair ( ( a * m + b * t ) , i + 1 ) ) ; } sort ( v . begin ( ) , v . end ( ) ) ; vector < int > ans ; for ( int i = 0 ; i < n ; i ++ ) { if ( v [ i ] . first <= d ) { ans . push_back ( v [ i ] . second ) ; d -= v [ i ] . first ; } } cout << ans . size ( ) << endl ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { int n = 5 ; long d = 5 ; int a = 1 , b = 1 ; int arr [ ] [ 2 ] = { { 2 , 0 } , { 3 , 2 } , { 4 , 4 } , { 10 , 0 } , { 0 , 1 } } ; solve ( n , d , a , b , arr ) ; return 0 ; }
Partition into two subarrays of lengths k and ( N | C ++ program to calculate max_difference between the sum of two subarrays of length k and N - k ; Function to calculate max_difference ; Sum of the array ; Sort the array in descending order ; Calculating max_difference ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDifference ( int arr [ ] , int N , int k ) { int M , S = 0 , S1 = 0 , max_difference = 0 ; for ( int i = 0 ; i < N ; i ++ ) S += arr [ i ] ; sort ( arr , arr + N , greater < int > ( ) ) ; M = max ( k , N - k ) ; for ( int i = 0 ; i < M ; i ++ ) S1 += arr [ i ] ; max_difference = S1 - ( S - S1 ) ; return max_difference ; } int main ( ) { int arr [ ] = { 8 , 4 , 5 , 2 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; cout << maxDifference ( arr , N , k ) << endl ; return 0 ; }
Minimum sum of product of two arrays | CPP program to find minimum sum of product of two arrays with k operations allowed on first array . ; Function to find the minimum product ; Find product of current elements and update result . ; If both product and b [ i ] are negative , we must increase value of a [ i ] to minimize result . ; If both product and a [ i ] are negative , we must decrease value of a [ i ] to minimize result . ; Similar to above two cases for positive product . ; Check if current difference becomes higher than the maximum difference so far . ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minproduct ( int a [ ] , int b [ ] , int n , int k ) { int diff = 0 , res = 0 ; int temp ; for ( int i = 0 ; i < n ; i ++ ) { int pro = a [ i ] * b [ i ] ; res = res + pro ; if ( pro < 0 && b [ i ] < 0 ) temp = ( a [ i ] + 2 * k ) * b [ i ] ; else if ( pro < 0 && a [ i ] < 0 ) temp = ( a [ i ] - 2 * k ) * b [ i ] ; else if ( pro > 0 && a [ i ] < 0 ) temp = ( a [ i ] + 2 * k ) * b [ i ] ; else if ( pro > 0 && a [ i ] > 0 ) temp = ( a [ i ] - 2 * k ) * b [ i ] ; int d = abs ( pro - temp ) ; if ( d > diff ) diff = d ; } return res - diff ; } int main ( ) { int a [ ] = { 2 , 3 , 4 , 5 , 4 } ; int b [ ] = { 3 , 4 , 2 , 3 , 2 } ; int n = 5 , k = 3 ; cout << minproduct ( a , b , n , k ) << endl ; return 0 ; }
Split n into maximum composite numbers | CPP program to split a number into maximum number of composite numbers . ; function to calculate the maximum number of composite numbers adding upto n ; 4 is the smallest composite number ; stores the remainder when n is divided by 4 ; if remainder is 0 , then it is perfectly divisible by 4. ; if the remainder is 1 ; If the number is less then 9 , that is 5 , then it cannot be expressed as 4 is the only composite number less than 5 ; If the number is greater then 8 , and has a remainder of 1 , then express n as n - 9 a and it is perfectly divisible by 4 and for 9 , count 1. ; When remainder is 2 , just subtract 6 from n , so that n is perfectly divisible by 4 and count 1 for 6 which is subtracted . ; if the number is 7 , 11 which cannot be expressed as sum of any composite numbers ; when the remainder is 3 , then subtract 15 from it and n becomes perfectly divisible by 4 and we add 2 for 9 and 6 , which is getting subtracted to make n perfectly divisible by 4. ; driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int n ) { if ( n < 4 ) return -1 ; int rem = n % 4 ; if ( rem == 0 ) return n / 4 ; if ( rem == 1 ) { if ( n < 9 ) return -1 ; return ( n - 9 ) / 4 + 1 ; } if ( rem == 2 ) return ( n - 6 ) / 4 + 1 ; if ( rem == 3 ) { if ( n < 15 ) return -1 ; return ( n - 15 ) / 4 + 2 ; } } int main ( ) { int n = 90 ; cout << count ( n ) << endl ; n = 143 ; cout << count ( n ) << endl ; return 0 ; }
Policemen catch thieves | C ++ program to find maximum number of thieves caught ; Returns maximum number of thieves that can be caught . ; store indices in the vector ; track lowest current indices of thief : thi [ l ] , police : pol [ r ] ; can be caught ; increment the minimum index ; Driver program
#include <iostream> NEW_LINE #include <vector> NEW_LINE #include <cmath> NEW_LINE using namespace std ; int policeThief ( char arr [ ] , int n , int k ) { int res = 0 ; vector < int > thi ; vector < int > pol ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == ' P ' ) pol . push_back ( i ) ; else if ( arr [ i ] == ' T ' ) thi . push_back ( i ) ; } int l = 0 , r = 0 ; while ( l < thi . size ( ) && r < pol . size ( ) ) { if ( abs ( thi [ l ] - pol [ r ] ) <= k ) { res ++ ; l ++ ; r ++ ; } else if ( thi [ l ] < pol [ r ] ) l ++ ; else r ++ ; } return res ; } int main ( ) { int k , n ; char arr1 [ ] = { ' P ' , ' T ' , ' T ' , ' P ' , ' T ' } ; k = 2 ; n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; cout << " Maximum ▁ thieves ▁ caught : ▁ " << policeThief ( arr1 , n , k ) << endl ; char arr2 [ ] = { ' T ' , ' T ' , ' P ' , ' P ' , ' T ' , ' P ' } ; k = 2 ; n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << " Maximum ▁ thieves ▁ caught : ▁ " << policeThief ( arr2 , n , k ) << endl ; char arr3 [ ] = { ' P ' , ' T ' , ' P ' , ' T ' , ' T ' , ' P ' } ; k = 3 ; n = sizeof ( arr3 ) / sizeof ( arr3 [ 0 ] ) ; cout << " Maximum ▁ thieves ▁ caught : ▁ " << policeThief ( arr3 , n , k ) << endl ; return 0 ; }
Minimum rotations to unlock a circular lock | CPP program for min rotation to unlock ; function for min rotation ; iterate till input and unlock code become 0 ; input and unlock last digit as reminder ; find min rotation ; update code and input ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minRotation ( int input , int unlock_code ) { int rotation = 0 ; int input_digit , code_digit ; while ( input unlock_code ) { input_digit = input % 10 ; code_digit = unlock_code % 10 ; rotation += min ( abs ( input_digit - code_digit ) , 10 - abs ( input_digit - code_digit ) ) ; input /= 10 ; unlock_code /= 10 ; } return rotation ; } int main ( ) { int input = 28756 ; int unlock_code = 98234 ; cout << " Minimum ▁ Rotation ▁ = ▁ " << minRotation ( input , unlock_code ) ; return 0 ; }
Job Scheduling with two jobs allowed at a time | CPP program to check if all jobs can be scheduled if two jobs are allowed at a time . ; making a pair of starting and ending time of job ; sorting according to starting time of job ; starting first and second job simultaneously ; Checking if starting time of next new job is greater than ending time of currently scheduled first job ; Checking if starting time of next new job is greater than ending time of ocurrently scheduled second job ; Driver code ; int startin [ ] = { 1 , 2 , 4 } ; starting time of jobs int endin [ ] = { 2 , 3 , 5 } ; ending times of jobs
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkJobs ( int startin [ ] , int endin [ ] , int n ) { vector < pair < int , int > > a ; for ( int i = 0 ; i < n ; i ++ ) a . push_back ( make_pair ( startin [ i ] , endin [ i ] ) ) ; sort ( a . begin ( ) , a . end ( ) ) ; long long tv1 = a [ 0 ] . second , tv2 = a [ 1 ] . second ; for ( int i = 2 ; i < n ; i ++ ) { if ( a [ i ] . first >= tv1 ) { tv1 = tv2 ; tv2 = a [ i ] . second ; } else if ( a [ i ] . first >= tv2 ) tv2 = a [ i ] . second ; else return false ; } return true ; } int main ( ) { int n = sizeof ( startin ) / sizeof ( startin [ 0 ] ) ; cout << checkJobs ( startin , endin , n ) ; return 0 ; }
Minimum cost for acquiring all coins with k extra coins allowed with every coin | C ++ program to acquire all n coins at minimum cost with multiple values of k . ; Converts coin [ ] to prefix sum array ; sort the coins value ; Maintain prefix sum array ; Function to calculate min cost when we can get k extra coins after paying cost of one . ; calculate no . of coins needed ; return sum of from prefix array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void preprocess ( int coin [ ] , int n ) { sort ( coin , coin + n ) ; for ( int i = 1 ; i <= n - 1 ; i ++ ) coin [ i ] += coin [ i - 1 ] ; } int minCost ( int coin [ ] , int n , int k ) { int coins_needed = ceil ( 1.0 * n / ( k + 1 ) ) ; return coin [ coins_needed - 1 ] ; } int main ( ) { int coin [ ] = { 8 , 5 , 3 , 10 , 2 , 1 , 15 , 25 } ; int n = sizeof ( coin ) / sizeof ( coin [ 0 ] ) ; preprocess ( coin , n ) ; int k = 3 ; cout << minCost ( coin , n , k ) << endl ; k = 7 ; cout << minCost ( coin , n , k ) << endl ; return 0 ; }
Program for Worst Fit algorithm in Memory Management | C ++ implementation of worst - Fit algorithm ; Function to allocate memory to blocks as per worst 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 worstFit ( int blockSize [ ] , int m , int processSize [ ] , int n ) { int allocation [ n ] ; memset ( allocation , -1 , sizeof ( allocation ) ) ; for ( int i = 0 ; i < n ; i ++ ) { int wstIdx = -1 ; for ( int j = 0 ; j < m ; j ++ ) { if ( blockSize [ j ] >= processSize [ i ] ) { if ( wstIdx == -1 ) wstIdx = j ; else if ( blockSize [ wstIdx ] < blockSize [ j ] ) wstIdx = j ; } } if ( wstIdx != -1 ) { allocation [ i ] = wstIdx ; blockSize [ wstIdx ] -= 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 ] ) ; worstFit ( blockSize , m , processSize , n ) ; return 0 ; }
Maximize array sum after K negations | Set 1 | C ++ program to maximize array sum after k operations . ; This function does k operations on array in a way that maximize the array sum . index -- > stores the index of current minimum element for j 'th operation ; Modify array K number of times ; Find minimum element in array for current operation and modify it i . e ; arr [ j ] -- > - arr [ j ] ; this the condition if we find 0 as minimum element , so it will useless to replace 0 by - ( 0 ) for remaining operations ; Modify element of array ; Calculate sum of array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( int arr [ ] , int n , int k ) { for ( int i = 1 ; i <= k ; i ++ ) { int min = INT_MAX ; int index = -1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] < min ) { min = arr [ j ] ; index = j ; } } if ( min == 0 ) break ; arr [ index ] = - arr [ index ] ; } int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; return sum ; } int main ( ) { int arr [ ] = { -2 , 0 , 5 , -1 , 2 } ; int k = 4 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumSum ( arr , n , k ) ; return 0 ; }
Maximize array sum after K negations | Set 1 | C ++ program to find maximum array sum after at most k negations . ; Sorting given array using in - built sort function ; If we find a 0 in our sorted array , we stop ; Calculating sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sol ( int arr [ ] , int n , int k ) { int sum = 0 ; int i = 0 ; sort ( arr , arr + n ) ; while ( k > 0 ) { if ( arr [ i ] >= 0 ) k = 0 ; else { arr [ i ] = ( -1 ) * arr [ i ] ; k = k - 1 ; } i ++ ; } for ( int j = 0 ; j < n ; j ++ ) { sum += arr [ j ] ; } return sum ; } int main ( ) { int arr [ ] = { -2 , 0 , 5 , -1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << sol ( arr , n , 4 ) << endl ; return 0 ; }
Maximize array sum after K negations | Set 1 | C ++ program for the above approach ; Function to calculate sum of the array ; Iterate from 0 to n - 1 ; Function to maximize sum ; Iterate from 0 to n - 1 ; Driver Code ; Function Call
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; long long int sumArray ( long long int * arr , int n ) { long long int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } return sum ; } long long int maximizeSum ( long long int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int i = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( k && arr [ i ] < 0 ) { arr [ i ] *= -1 ; k -- ; continue ; } break ; } if ( i == n ) i -- ; if ( k == 0 k % 2 == 0 ) { return sumArray ( arr , n ) ; } if ( i != 0 && abs ( arr [ i ] ) >= abs ( arr [ i - 1 ] ) ) { i -- ; } arr [ i ] *= -1 ; return sumArray ( arr , n ) ; } int main ( ) { int n = 5 ; int k = 4 ; long long int arr [ 5 ] = { -3 , -2 , -1 , 5 , 6 } ; cout << maximizeSum ( arr , n , k ) << endl ; return 0 ; }
Bin Packing Problem ( Minimize number of used Bins ) | C ++ program to find number of bins required using First Fit algorithm . ; Returns number of bins required using first 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 first bin that can accommodate weight [ i ] ; If no bin could accommodate weight [ i ] ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int firstFit ( int weight [ ] , int n , int c ) { int res = 0 ; int bin_rem [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int j ; for ( j = 0 ; j < res ; j ++ ) { if ( bin_rem [ j ] >= weight [ i ] ) { bin_rem [ j ] = bin_rem [ j ] - weight [ i ] ; break ; } } if ( j == res ) { bin_rem [ res ] = c - weight [ i ] ; res ++ ; } } 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 ▁ First ▁ Fit ▁ : ▁ " << firstFit ( weight , n , c ) ; return 0 ; }
Minimum cost to reduce A and B to 0 using square root or divide by 2 | C ++ program for the above approach ; Function to return the minimum cost of converting A and B to 0 ; If both A and B doesn 't change in this recusrive call, then return INT_MAX to save the code from going into infinite loop ; Base Case ; If the answer of this recursive call is already memoised ; If A is reduced to A / 2 ; If B is reduced to B / 2 ; If both A and B is reduced to sqrt ( A * B ) ; Return the minimum of the value given by the above three subproblems , also memoize the value while returning ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinOperations ( int A , int B , int prevA , int prevB , vector < vector < int > > & dp ) { if ( A == prevA and B == prevB ) { return INT_MAX ; } if ( A == 0 and B == 0 ) { return 0 ; } if ( dp [ A ] [ B ] != -1 ) { return dp [ A ] [ B ] ; } int ans1 = getMinOperations ( A / 2 , B , A , B , dp ) ; if ( ans1 != INT_MAX ) { ans1 += 1 ; } int ans2 = getMinOperations ( A , B / 2 , A , B , dp ) ; if ( ans2 != INT_MAX ) { ans2 += 1 ; } int ans3 = getMinOperations ( sqrt ( A * B ) , sqrt ( A * B ) , A , B , dp ) ; if ( ans3 != INT_MAX ) { ans3 += 2 ; } return dp [ A ] [ B ] = min ( { ans1 , ans2 , ans3 } ) ; } int main ( ) { int A = 53 , B = 16 ; int mx = max ( A , B ) ; vector < vector < int > > dp ( mx + 1 , vector < int > ( mx + 1 , -1 ) ) ; cout << getMinOperations ( A , B , -1 , -1 , dp ) ; }
Find Maximum Shortest Distance in Each Component of a Graph | C ++ program for the above approach ; Below dfs function will be used to get the connected components of a graph and stores all the connected nodes in the vector component ; Mark this vertex as visited ; Put this node in component vector ; For all other vertices in graph ; If there is an edge between src and dest i . e . , the value of graph [ u ] [ v ] != INT_MAX ; If we haven 't visited dest then recursively apply dfs on dest ; Below is the Floyd Warshall Algorithm which is based on Dynamic Programming ; For every vertex of graph find the shortest distance with other vertices ; Taking care of interger overflow ; Update distance between vertex i and j if choosing k as an intermediate vertex make a shorter distance ; Function to find the maximum shortest path distance in a component by checking the shortest distances between all possible pairs of nodes ; If the maxDistance is still INT_MIN then return 0 because this component has a single element ; Below function uses above two method to get the maximum shortest distances in each component of the graph the function returns a vector , where each element denotes maximum shortest path distance for a component ; Find the connected components ; For storing the nodes in a particular component ; Now for each unvisited node run the dfs to get the connected component having this unvisited node ; First of all clear the temp ; Now for all - pair find the shortest path distances using Floyd Warshall ; Now for each component find the maximum shortest distance and store it in result ; Driver Code ; Adjacency Matrix for the first graph in the examples ; Find the maximum shortest distances ; Printing the maximum shortest path distances for each components
#include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( int src , vector < bool > & visited , vector < vector < int > > & graph , vector < int > & component , int N ) { visited [ src ] = true ; component . push_back ( src ) ; for ( int dest = 0 ; dest < N ; dest ++ ) { if ( graph [ src ] [ dest ] != INT_MAX ) { if ( ! visited [ dest ] ) dfs ( dest , visited , graph , component , N ) ; } } } void floydWarshall ( vector < vector < int > > & graph , int N ) { for ( int k = 0 ; k < N ; k ++ ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( graph [ i ] [ k ] != INT_MAX && graph [ k ] [ j ] != INT_MAX ) { if ( graph [ i ] [ k ] + graph [ k ] [ j ] < graph [ i ] [ j ] ) graph [ i ] [ j ] = graph [ i ] [ k ] + graph [ k ] [ j ] ; } } } } } int maxInThisComponent ( vector < int > & component , vector < vector < int > > & graph ) { int maxDistance = INT_MIN ; int n = component . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { maxDistance = max ( maxDistance , graph [ component [ i ] ] [ component [ j ] ] ) ; } } return ( maxDistance == INT_MIN ? 0 : maxDistance ) ; } vector < int > maximumShortesDistances ( vector < vector < int > > & graph , int N ) { vector < bool > visited ( N , false ) ; vector < vector < int > > components ; vector < int > temp ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! visited [ i ] ) { temp . clear ( ) ; dfs ( i , visited , graph , temp , N ) ; components . push_back ( temp ) ; } } floydWarshall ( graph , N ) ; vector < int > result ; int numOfComp = components . size ( ) ; int maxDistance ; for ( int i = 0 ; i < numOfComp ; i ++ ) { maxDistance = maxInThisComponent ( components [ i ] , graph ) ; result . push_back ( maxDistance ) ; } return result ; } int main ( ) { int N = 8 ; const int inf = INT_MAX ; vector < vector < int > > graph1 = { { 0 , inf , 9 , inf , inf , inf , 3 , inf } , { inf , 0 , inf , 10 , 1 , 8 , inf , inf } , { 9 , inf , 0 , inf , inf , inf , 11 , inf } , { inf , 10 , inf , 0 , 5 , 13 , inf , inf } , { inf , 1 , inf , 5 , 0 , 3 , inf , inf } , { 8 , inf , inf , 13 , 3 , 0 , inf , inf } , { 3 , inf , 11 , inf , inf , inf , 0 , inf } , { inf , inf , inf , inf , inf , inf , inf , 0 } , } ; vector < int > result1 = maximumShortesDistances ( graph1 , N ) ; for ( int mx1 : result1 ) cout << mx1 << ' ▁ ' ; return 0 ; }
Maximize count of indices with same element by pairing rows from given Matrices | C ++ program for the above approach ; Function to find the maximum score ; Stores the maximum sum of scores ; For each permutation of pos vector calculate the score ; If values at current indexes are same then increment the current score ; Print the maximum score ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxScoreSum ( vector < vector < int > > & a , vector < vector < int > > & b ) { int maxSum = 0 ; vector < int > pos ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { pos . push_back ( i ) ; } do { int curSum = 0 ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { for ( int j = 0 ; j < a [ pos [ i ] ] . size ( ) ; j ++ ) { curSum += ( a [ pos [ i ] ] [ j ] == b [ i ] [ j ] ) ; maxSum = max ( maxSum , curSum ) ; } } } while ( next_permutation ( pos . begin ( ) , pos . end ( ) ) ) ; cout << maxSum ; } int main ( ) { int N = 3 , M = 3 ; vector < vector < int > > a = { { 1 , 1 , 0 } , { 1 , 0 , 1 } , { 0 , 0 , 1 } } ; vector < vector < int > > b = { { 1 , 0 , 0 } , { 0 , 0 , 1 } , { 1 , 1 , 0 } } ; maxScoreSum ( a , b ) ; return 0 ; }
Maximize count of indices with same element by pairing rows from given Matrices | C ++ program for the above approach ; Function to find the maximum defined score ; If all students are assigned ; Check if row is not paired yet ; Check for all indexes ; If values at current indexes are same increase curSum ; Further recursive call ; Store the ans for current mask and return ; Utility function to find the maximum defined score ; Create a mask with all set bits 1 -> row is not paired yet 0 -> row is already paired ; Initialise dp array with - 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxScoreSum ( vector < vector < int > > & a , vector < vector < int > > & b , int row , int mask , vector < int > & dp ) { if ( row >= a . size ( ) ) { return 0 ; } if ( dp [ mask ] != -1 ) { return dp [ mask ] ; } int ans = 0 ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { if ( mask & ( 1 << i ) ) { int newMask = mask ^ ( 1 << i ) ; int curSum = 0 ; for ( int j = 0 ; j < a [ i ] . size ( ) ; j ++ ) { if ( a [ row ] [ j ] == b [ i ] [ j ] ) { curSum ++ ; } } ans = max ( ans , curSum + maxScoreSum ( a , b , row + 1 , newMask , dp ) ) ; } } return dp [ mask ] = ans ; } int maxScoreSumUtil ( vector < vector < int > > & a , vector < vector < int > > & b , int N , int M ) { int row = 0 ; int mask = pow ( 2 , M ) - 1 ; vector < int > dp ( mask + 1 , -1 ) ; return maxScoreSum ( a , b , row , mask , dp ) ; } int main ( ) { int N = 3 , M = 3 ; vector < vector < int > > a = { { 1 , 1 , 0 } , { 1 , 0 , 1 } , { 0 , 0 , 1 } } ; vector < vector < int > > b = { { 1 , 0 , 0 } , { 0 , 0 , 1 } , { 1 , 1 , 0 } } ; cout << maxScoreSumUtil ( a , b , N , M ) ; return 0 ; }
Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays | C ++ program for the above approach ; Function to find the maximum sum of differences of subarrays by splitting array into non - overlapping subarrays ; Stores the answer for prefix and initialize with zero ; Assume i - th index as right endpoint ; Choose the current value as the maximum and minimum ; Find the left endpoint and update the array dp [ ] ; Return answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDiffSum ( int arr [ ] , int n ) { int dp [ n ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 0 ; i < n ; i ++ ) { int maxVal = arr [ i ] , minVal = arr [ i ] ; for ( int j = i ; j >= 0 ; j -- ) { minVal = min ( minVal , arr [ j ] ) ; maxVal = max ( maxVal , arr [ j ] ) ; if ( j - 1 >= 0 ) dp [ i ] = max ( dp [ i ] , maxVal - minVal + dp [ j - 1 ] ) ; else dp [ i ] = max ( dp [ i ] , maxVal - minVal ) ; } } return dp [ n - 1 ] ; } int main ( ) { int arr [ ] = { 8 , 1 , 7 , 9 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxDiffSum ( arr , N ) ; return 0 ; }
Count of N | C ++ program for the above approach ; Find the value of x raised to the yth power modulo MOD ; Stores the value of x ^ y ; Iterate until y is positive ; Function to perform the Modular Multiplicative Inverse using the Fermat 's little theorem ; Modular division x / y , find modular multiplicative inverse of y and multiply by x ; Function to find Binomial Coefficient C ( n , k ) in O ( k ) time ; Base Case ; Update the value of p and q ; Function to find the count of arrays having K as the first element satisfying the given criteria ; Stores the resultant count of arrays ; Find the factorization of K ; Stores the count of the exponent of the currentprime factor ; N is one last prime factor , for c = 1 -> C ( N - 1 + 1 , 1 ) = N ; Return the totol count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MOD = 1000000007 ; long modPow ( long x , long y ) { long r = 1 , a = x ; while ( y > 0 ) { if ( ( y & 1 ) == 1 ) { r = ( r * a ) % MOD ; } a = ( a * a ) % MOD ; y /= 2 ; } return r ; } long modInverse ( long x ) { return modPow ( x , MOD - 2 ) ; } long modDivision ( long p , long q ) { return ( p * modInverse ( q ) ) % MOD ; } long C ( long n , int k ) { if ( k > n ) { return 0 ; } long p = 1 , q = 1 ; for ( int i = 1 ; i <= k ; i ++ ) { q = ( q * i ) % MOD ; p = ( p * ( n - i + 1 ) ) % MOD ; } return modDivision ( p , q ) ; } int countArrays ( int N , int K ) { long res = 1 ; for ( int p = 2 ; p <= K / p ; p ++ ) { int c = 0 ; while ( K % p == 0 ) { K /= p ; c ++ ; } res = ( res * C ( N - 1 + c , c ) ) % MOD ; } if ( N > 1 ) { res = ( res * N ) % MOD ; } return res ; } int main ( ) { int N = 3 , K = 5 ; cout << countArrays ( N , K ) ; return 0 ; }
Minimum number of days to debug all programs | C ++ program for the above approach ; Function to calculate the minimum work sessions ; Break condition ; All bits are set ; Check if already calculated ; Store the answer ; Check if ith bit is set or unset ; Including in current work session ; Including in next work session ; Resultant answer will be minimum of both ; Function to initialize DP array and solve the problem ; Initialize dp table with - 1 ; Resultant mask ; no . of minimum work sessions is even ; no . of minimum work sessions is odd ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSessions ( vector < int > & codeTime , vector < vector < int > > & dp , int ones , int n , int mask , int currTime , int WorkingSessionTime ) { if ( currTime > WorkingSessionTime ) return INT_MAX ; if ( mask == ones ) return 1 ; if ( dp [ mask ] [ currTime ] != -1 ) return dp [ mask ] [ currTime ] ; int ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( mask & ( 1 << i ) ) == 0 ) { int inc = minSessions ( codeTime , dp , ones , n , mask | ( 1 << i ) , currTime + codeTime [ i ] , WorkingSessionTime ) ; int inc_next = 1 + minSessions ( codeTime , dp , ones , n , mask | ( 1 << i ) , codeTime [ i ] , WorkingSessionTime ) ; ans = min ( { ans , inc , inc_next } ) ; } } return dp [ mask ] [ currTime ] = ans ; } int solve ( vector < int > codeTime , int n , int WorkingSessionTime ) { vector < vector < int > > dp ( ( 1 << 14 ) , vector < int > ( 15 , -1 ) ) ; int ones = ( 1 << n ) - 1 ; int ans = minSessions ( codeTime , dp , ones , n , 0 , 0 , WorkingSessionTime ) ; if ( WorkingSessionTime < 6 ) { if ( ans % 2 == 0 ) ans = ans / 2 ; else ans = ( ans / 2 ) + 1 ; } return ans ; } int main ( ) { vector < int > codeTime = { 1 , 2 , 3 , 1 , 1 , 3 } ; int n = codeTime . size ( ) ; int WorkingSessionTime = 4 ; cout << solve ( codeTime , n , WorkingSessionTime ) << endl ; return 0 ; }
Count of non | C ++ program for the above approach ; Define the dp table globally ; Recursive function to calculate total number of valid non - decreasing strings ; If already calculated state ; Base Case ; Stores the total count of strings formed ; Fill the value in dp matrix ; Function to find the total number of non - decreasing string formed by replacing the ' ? ' ; Initialize all value of dp table with - 1 ; Left and Right limits ; Iterate through all the characters of the string S ; Change R to the current character ; Call the recursive function ; Change L to R and R to 9 ; Reinitialize the length of ? to 0 ; Increment the length of the segment ; Update the ans ; Return the total count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 100005 NEW_LINE int dp [ MAXN ] [ 10 ] ; int solve ( int len , int gap ) { if ( dp [ len ] [ gap ] != -1 ) { return dp [ len ] [ gap ] ; } if ( len == 0 gap == 0 ) { return 1 ; } if ( gap < 0 ) { return 0 ; } int ans = 0 ; for ( int i = 0 ; i <= gap ; i ++ ) { ans += solve ( len - 1 , gap - i ) ; } return dp [ len ] [ gap ] = ans ; } int countValidStrings ( string S ) { memset ( dp , -1 , sizeof ( dp ) ) ; int N = S . length ( ) ; int L = 1 , R = 9 ; int cnt = 0 ; int ans = 1 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] != ' ? ' ) { R = S [ i ] - '0' ; ans *= solve ( cnt , R - L ) ; L = R ; R = 9 ; cnt = 0 ; } else { cnt ++ ; } } ans *= solve ( cnt , R - L ) ; return ans ; } int main ( ) { string S = "1 ? ? ?2" ; cout << countValidStrings ( S ) ; return 0 ; }
K | C ++ program for the above approach ; Recursive function to find the Kth smallest binary string ; Base Case ; Return string of all 1 's of length B ; Return string of all 0 's of length A ; Function to find the Kth lexicographically smallest binary string with exactly A zeroes and B ones ; Stores the recurring states ; Calculate the dp values iteratively ; The last character was '0' ; The last character was '1' ; Print the binary string obtained ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string KthString ( int A , int B , long long K , vector < vector < int > > & dp ) { if ( A == 0 ) { return string ( B , '1' ) ; } if ( B == 0 ) { return string ( A , '0' ) ; } if ( K <= dp [ A - 1 ] [ B ] ) { return "0" + KthString ( A - 1 , B , K , dp ) ; } else { return "1" + KthString ( A , B - 1 , K - dp [ A - 1 ] [ B ] , dp ) ; } } int KthStringUtil ( int A , int B , int K ) { vector < vector < int > > dp ( A + 1 , vector < int > ( B + 1 ) ) ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 0 ; i <= A ; ++ i ) { for ( int j = 0 ; j <= B ; ++ j ) { if ( i > 0 ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j ] ; } if ( j > 0 ) { dp [ i ] [ j ] += dp [ i ] [ j - 1 ] ; } } } cout << KthString ( A , B , K , dp ) ; return 0 ; } int main ( ) { int A = 3 , B = 3 , K = 7 ; KthStringUtil ( A , B , K ) ; return 0 ; }
Count of binary arrays of size N with sum of product of adjacent pairs equal to K | C ++ program for the above approach ; Function to return the number of total possible combinations of 0 and 1 to form an array of size N having sum of product of consecutive elements K ; If value is greater than K , then return 0 as no combination is possible to have sum K ; Check if the result of this recursive call is memoised already , if it is then just return the previously calculated result ; Check if the value is equal to K at N , if it is then return 1 as this combination is possible . Otherwise return 0. ; If previous element is 1 ; If current element is 1 as well , then add 1 to value ; If current element is 0 , then value will remain same ; If previous element is 0 , then value will remain same irrespective of the current element ; Memoise and return the ans ; Driver Code ; As the array can be started by 0 or 1 , so take both cases while calculating the total possible combinations
#include <bits/stdc++.h> NEW_LINE using namespace std ; int combinationsPossible ( int N , int idx , int prev , int val , int K , vector < vector < vector < int > > > & dp ) { if ( val > K ) { return 0 ; } if ( dp [ val ] [ idx ] [ prev ] != -1 ) { return dp [ val ] [ idx ] [ prev ] ; } if ( idx == N - 1 ) { if ( val == K ) { return 1 ; } return 0 ; } int ans = 0 ; if ( prev == 1 ) { ans += combinationsPossible ( N , idx + 1 , 1 , val + 1 , K , dp ) ; ans += combinationsPossible ( N , idx + 1 , 0 , val , K , dp ) ; } else { ans += combinationsPossible ( N , idx + 1 , 1 , val , K , dp ) ; ans += combinationsPossible ( N , idx + 1 , 0 , val , K , dp ) ; } return dp [ val ] [ idx ] [ prev ] = ans ; } int main ( ) { int N = 5 ; int K = 3 ; vector < vector < vector < int > > > dp ( K + 1 , vector < vector < int > > ( N + 1 , vector < int > ( 2 , -1 ) ) ) ; cout << ( combinationsPossible ( N , 0 , 0 , 0 , K , dp ) + combinationsPossible ( N , 0 , 1 , 0 , K , dp ) ) ; }
Count ways to split an array into subarrays such that sum of the i | C ++ program for the above approach ; Function to count ways to split an array into subarrays such that sum of the i - th subarray is divisible by i ; Stores the prefix sum of array ; Find the prefix sum ; Initialize dp [ ] [ ] array ; Stores the count of splitting ; Iterate over the range [ 0 , N ] ; Update the dp table ; If the last index is reached , then add it to the variable ans ; Return the possible count of splitting of array into subarrays ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOfWays ( int arr [ ] , int N ) { int pre [ N + 1 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { pre [ i + 1 ] = pre [ i ] + arr [ i ] ; } int dp [ N + 1 ] [ N + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 1 ] [ 0 ] ++ ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = N ; j >= 1 ; j -- ) { dp [ j + 1 ] [ pre [ i + 1 ] % ( j + 1 ) ] += dp [ j ] [ pre [ i + 1 ] % j ] ; if ( i == N - 1 ) { ans += dp [ j ] [ pre [ i + 1 ] % j ] ; } } } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countOfWays ( arr , N ) ; return 0 ; }
Queries to find minimum absolute difference between adjacent array elements in given ranges | C ++ program for the above approach ; Stores the index for the minimum value in the subarray arr [ i , j ] ; Structure for query range ; Function to fill the lookup array lookup [ ] [ ] in the bottom up manner ; Initialize M for the intervals with length 1 ; Find the values from smaller to bigger intervals ; Compute minimum value for all intervals with size 2 ^ j ; For arr [ 2 ] [ 10 ] , compare arr [ lookup [ 0 ] [ 3 ] ] and arr [ lookup [ 3 ] [ 3 ] ] ; Otherwise ; Function find minimum of absolute difference of all adjacent element in subarray arr [ L . . R ] ; For [ 2 , 10 ] , j = 3 ; For [ 2 , 10 ] , compare arr [ lookup [ 0 ] [ 3 ] ] and arr [ lookup [ 3 ] [ 3 ] ] , ; Function to find the minimum of the ranges for M queries ; Fills table lookup [ n ] [ Log n ] ; Compute sum of all queries ; Left and right boundaries of current range ; Print sum of current query range ; Function to find the minimum absolute difference in a range ; diff [ ] is to stores the absolute difference of adjacent elements ; Call Min_difference to get minimum difference of adjacent elements ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 500 NEW_LINE int lookup [ MAX ] [ MAX ] ; struct Query { int L , R ; } ; void preprocess ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) lookup [ i ] [ 0 ] = i ; for ( int j = 1 ; ( 1 << j ) <= n ; j ++ ) { for ( int i = 0 ; ( i + ( 1 << j ) - 1 ) < n ; i ++ ) { if ( arr [ lookup [ i ] [ j - 1 ] ] < arr [ lookup [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] ] ) lookup [ i ] [ j ] = lookup [ i ] [ j - 1 ] ; else lookup [ i ] [ j ] = lookup [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] ; } } } int query ( int arr [ ] , int L , int R ) { int j = ( int ) log2 ( R - L + 1 ) ; if ( arr [ lookup [ L ] [ j ] ] <= arr [ lookup [ R - ( 1 << j ) + 1 ] [ j ] ] ) return arr [ lookup [ L ] [ j ] ] ; else return arr [ lookup [ R - ( 1 << j ) + 1 ] [ j ] ] ; } void Min_difference ( int arr [ ] , int n , Query q [ ] , int m ) { preprocess ( arr , n ) ; for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] . L , R = q [ i ] . R ; cout << query ( arr , L , R - 1 ) << ' ' ; } } void minimumDifference ( int arr [ ] , Query q [ ] , int N , int m ) { int diff [ N ] ; for ( int i = 0 ; i < N - 1 ; i ++ ) diff [ i ] = abs ( arr [ i ] - arr [ i + 1 ] ) ; Min_difference ( diff , N - 1 , q , m ) ; } int main ( ) { int arr [ ] = { 2 , 6 , 1 , 8 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Query Q [ ] = { { 0 , 3 } , { 1 , 5 } , { 4 , 5 } } ; int M = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; minimumDifference ( arr , Q , N , M ) ; return 0 ; }
Domino and Tromino tiling problem | C ++ program for the above approach ; Function to find the total number of ways to tile a 2 * N board using the given types of tile ; If N is less than 3 ; Store all dp - states ; Base Case ; Traverse the range [ 2 , N ] ; Update the value of dp [ i ] [ 0 ] ; Update the value of dp [ i ] [ 1 ] ; Update the value of dp [ i ] [ 2 ] ; Return the number of ways as the value of dp [ N ] [ 0 ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const long long MOD = 1e9 + 7 ; int numTilings ( int N ) { if ( N < 3 ) { return N ; } vector < vector < long long > > dp ( N + 1 , vector < long long > ( 3 , 0 ) ) ; dp [ 0 ] [ 0 ] = dp [ 1 ] [ 0 ] = 1 ; dp [ 1 ] [ 1 ] = dp [ 1 ] [ 2 ] = 1 ; for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 2 ] [ 0 ] + dp [ i - 2 ] [ 1 ] + dp [ i - 2 ] [ 2 ] ) % MOD ; dp [ i ] [ 1 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 2 ] ) % MOD ; dp [ i ] [ 2 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] ) % MOD ; } return dp [ N ] [ 0 ] ; } int main ( ) { int N = 3 ; cout << numTilings ( N ) ; return 0 ; }
Count of N | C ++ program for the above approach ; Store the recurring recursive states ; Function to find the number of strings of length N such that it is a concatenation it substrings ; Single character cant be repeated ; Check if this state has been already calculated ; Stores the resultant count for the current recursive calls ; Iterate over all divisors ; Non - Repeated = Total - Repeated ; Non - Repeated = Total - Repeated ; Store the result for the further calculation ; Return resultant count ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; map < int , int > dp ; int countStrings ( int N ) { if ( N == 1 ) return 0 ; if ( dp . find ( N ) != dp . end ( ) ) return dp [ N ] ; int ret = 0 ; for ( int div = 1 ; div <= sqrt ( N ) ; div ++ ) { if ( N % div == 0 ) { ret += ( 1 << div ) - countStrings ( div ) ; int div2 = N / div ; if ( div2 != div and div != 1 ) ret += ( 1 << div2 ) - countStrings ( div2 ) ; } } dp [ N ] = ret ; return ret ; } int main ( ) { int N = 6 ; cout << countStrings ( N ) << endl ; }
Count N | C ++ program for the above approach ; Function to count N - digit numbers such that each position is divisible by the digit occurring at that position ; Stores the answer . ; Iterate from indices 1 to N ; Stores count of digits that can be placed at the current index ; Iterate from digit 1 to 9 ; If index is divisible by digit ; Multiply answer with possible choices ; Driver Code ; Given Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1e9 + 7 ; void countOfNumbers ( int N ) { int ans = 1 ; for ( int index = 1 ; index <= N ; ++ index ) { int choices = 0 ; for ( int digit = 1 ; digit <= 9 ; ++ digit ) { if ( index % digit == 0 ) { ++ choices ; } } ans = ( ans * 1LL * choices ) % mod ; } cout << ans << endl ; } int main ( ) { int N = 5 ; countOfNumbers ( N ) ; return 0 ; }
Maximum number of groups that can receive fresh donuts distributed in batches of size K | C ++ program for the above approach ; Recursive function to find the maximum number of groups that will receive fresh donuts ; Store the result for the current state ; Check if the leftover donuts from the previous batch is 0 ; If true , then one by one give the fresh donuts to each group ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] ; Otherwise , traverse the given array , arr [ ] ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] ; Return the value of q ; Function to find the maximum number of groups that will receive fresh donuts ; Stores count of remainder by K ; Traverse the array arr [ ] ; Stores maximum number of groups ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dfs ( int arr [ ] , int left , int K ) { int q = 0 ; if ( left == 0 ) { for ( int i = 1 ; i < K ; ++ i ) { if ( arr [ i ] > 0 ) { arr [ i ] -- ; q = max ( q , 1 + dfs ( arr , K - i , K ) ) ; arr [ i ] ++ ; } } } else { for ( int i = 1 ; i < K ; ++ i ) { if ( arr [ i ] > 0 ) { arr [ i ] -- ; int nleft = ( i <= left ? left - i : K + left - i ) ; q = max ( q , dfs ( arr , nleft , K ) ) ; arr [ i ] ++ ; } } } return q ; } int maxGroups ( int K , int arr [ ] , int n ) { int V [ K ] = { 0 } ; for ( int x = 0 ; x < n ; x ++ ) V [ arr [ x ] % K ] ++ ; int ans = V [ 0 ] + dfs ( V , 0 , K ) ; return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << maxGroups ( K , arr , n ) ; return 0 ; }
Maximum jumps to reach end of Array with condition that index i can make arr [ i ] jumps | C ++ code for the above approach ; Function to find the maximum jumps to reach end of array ; Stores the jumps needed to reach end from each index ; Traverse the array ; Check if j is less than N ; Add dp [ j ] to the value of dp [ i ] ; Update the value of ans ; Print the value of ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxJumps ( int arr [ ] , int N ) { int dp [ N ] = { 0 } ; int ans = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { dp [ i ] = arr [ i ] ; int j = i + arr [ i ] ; if ( j < N ) { dp [ i ] = dp [ i ] + dp [ j ] ; } ans = max ( ans , dp [ i ] ) ; } cout << ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 7 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMaxJumps ( arr , N ) ; return 0 ; }
Longest subsequence with non negative prefix sum at each position | C ++ program for the above approach ; Function to find the length of the longest subsequence with non negative prefix sum at each position ; Stores the maximum sum possible if we include j elements till the position i ; Initialize dp array with - 1 ; Maximum subsequence sum by including no elements till position ' i ' ; Maximum subsequence sum by including first element at first position ; Iterate over all the remaining positions ; If the current element is excluded ; If current element is included and if total sum is positive or not ; Select the maximum j by which a non negative prefix sum subsequence can be obtained ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void longestSubsequence ( int * arr , int N ) { int dp [ N ] [ N + 1 ] ; memset ( dp , -1 , sizeof dp ) ; for ( int i = 0 ; i < N ; ++ i ) { dp [ i ] [ 0 ] = 0 ; } dp [ 0 ] [ 1 ] = ( arr [ 0 ] >= 0 ? arr [ 0 ] : -1 ) ; for ( int i = 1 ; i < N ; ++ i ) { for ( int j = 1 ; j <= ( i + 1 ) ; ++ j ) { if ( dp [ i - 1 ] [ j ] != -1 ) { dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j ] ) ; } if ( dp [ i - 1 ] [ j - 1 ] >= 0 && dp [ i - 1 ] [ j - 1 ] + arr [ i ] >= 0 ) { dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - 1 ] + arr [ i ] ) ; } } } int ans = 0 ; for ( int j = 0 ; j <= N ; ++ j ) { if ( dp [ N - 1 ] [ j ] >= 0 ) { ans = j ; } } cout << ans << endl ; } int main ( ) { int arr [ ] = { 4 , -4 , 1 , -3 , 1 , -3 } ; int N = sizeof arr / sizeof arr [ 0 ] ; longestSubsequence ( arr , N ) ; return 0 ; }
Count of strictly increasing N | C ++ program for the above approach ; Declaration of dp table ; Function to find the count of all N digit numbers such that all the digit is less than its adjacent digits ; Base Case : If i = n , then return 1 as valid number has been formed ; If the state has already been computed , then return it ; Stores the total count of ways for the current recursive call ; If i = 0 , any digit from [ 1 - 9 ] can be placed and also if N = 1 , then 0 can also be placed ; If i = 1 , any digit from [ 0 - 9 ] can be placed such that digit is not equal to previous digit ; If the current digit is not same as the prev ; Place the current digit such that it is less than the previous digit ; Place current digit such that it is more than the previous digit ; Return the resultant total count ; Function to find all N - digit numbers satisfying the given criteria ; Initialize an array dp [ ] with all elements as - 1 ; Function call to count all possible ways ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100 ] [ 10 ] [ 2 ] ; int solve ( int i , int n , int prev , bool sign ) { if ( i == n ) { return 1 ; } int & val = dp [ i ] [ prev ] [ sign ] ; if ( val != -1 ) return val ; val = 0 ; if ( i == 0 ) { for ( int digit = ( n == 1 ? 0 : 1 ) ; digit <= 9 ; ++ digit ) { val += solve ( i + 1 , n , digit , sign ) ; } } else if ( i == 1 ) { for ( int digit = 0 ; digit <= 9 ; ++ digit ) { if ( digit != prev ) { val += solve ( i + 1 , n , digit , ( digit > prev ) ) ; } } } else { if ( sign == 1 ) { for ( int digit = prev - 1 ; digit >= 0 ; -- digit ) { val += solve ( i + 1 , n , digit , 0 ) ; } } else { for ( int digit = prev + 1 ; digit <= 9 ; ++ digit ) { val += solve ( i + 1 , n , digit , 1 ) ; } } } return val ; } void countNdigitNumber ( int N ) { memset ( dp , -1 , sizeof dp ) ; cout << solve ( 0 , N , 0 , 0 ) ; } int main ( ) { int N = 3 ; countNdigitNumber ( N ) ; return 0 ; }
Total count of sorted numbers upto N digits in range [ L , R ] ( Magnificent necklace combinatorics problem ) | C ++ program for the above approach ; Function to count total number of ways ; Stores all DP - states ; Stores the result ; Traverse the range [ 0 , N ] ; Traverse the range [ 1 , R - L ] ; Update dp [ i ] [ j ] ; Assign dp [ 0 ] [ R - L ] to ans ; Traverse the range [ 1 , N ] ; Traverse the range [ 1 , R - L ] ; Update dp [ i ] [ j ] ; Increment ans by dp [ i - 1 ] [ j ] ; Return ans ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Count ( int N , int L , int R ) { vector < vector < int > > dp ( N , vector < int > ( R - L + 1 , 0 ) ) ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = 1 ; } for ( int i = 1 ; i < dp [ 0 ] . size ( ) ; i ++ ) { dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + 1 ; } ans = dp [ 0 ] [ R - L ] ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j < dp [ 0 ] . size ( ) ; j ++ ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] ; } ans += dp [ i ] [ R - L ] ; } return ans ; } int main ( ) { int N = 3 ; int L = 6 ; int R = 9 ; cout << Count ( N , L , R ) ; return 0 ; }
Length of largest common subarray in all the rows of given Matrix | C ++ program for the above approach ; Function to find longest common subarray in all the rows of the matrix ; Array to store the position of element in every row ; Traverse the matrix ; Store the position of every element in every row ; Variable to store length of largest common Subarray ; Traverse through the matrix column ; Variable to check if every row has arr [ i ] [ j ] next to arr [ i - 1 ] [ j ] or not ; Traverse through the matrix rows ; Check if arr [ i ] [ j ] is next to arr [ i ] [ j - 1 ] in every row or not ; If every row has arr [ 0 ] [ j ] next to arr [ 0 ] [ j - 1 ] increment len by 1 and update the value of ans ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestCommonSubarray ( vector < vector < int > > arr , int n , int m ) { int dp [ n ] [ m + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { dp [ i ] [ arr [ i ] [ j ] ] = j ; } } int ans = 1 ; int len = 1 ; for ( int i = 1 ; i < m ; i ++ ) { bool check = true ; for ( int j = 1 ; j < n ; j ++ ) { if ( dp [ j ] [ arr [ 0 ] [ i - 1 ] ] + 1 != dp [ j ] [ arr [ 0 ] [ i ] ] ) { check = false ; break ; } } if ( check ) { len ++ ; ans = max ( ans , len ) ; } else { len = 1 ; } } return ans ; } int main ( ) { int n = 4 ; int m = 5 ; vector < vector < int > > arr { { 4 , 5 , 1 , 2 , 3 , 6 , 7 } , { 1 , 2 , 4 , 5 , 7 , 6 , 3 } , { 2 , 7 , 3 , 4 , 5 , 1 , 6 } } ; int N = arr . size ( ) ; int M = arr [ 0 ] . size ( ) ; cout << largestCommonSubarray ( arr , N , M ) ; return 0 ; }
Maximize sum that can be obtained from two given arrays based on given conditions | C ++ program for the above approach ; Function to find the maximum sum that can be obtained from two given based on the following conditions ; Stores the maximum sum from 0 to i ; Initialize the value of dp [ 0 ] [ 0 ] and dp [ 0 ] [ 1 ] ; Traverse the array A [ ] and B [ ] ; If A [ i ] is considered ; If B [ i ] is not considered ; If B [ i ] is considered ; If i = 1 , then consider the value of dp [ i ] [ 1 ] as b [ i ] ; Return maximum Sum ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MaximumSum ( int a [ ] , int b [ ] , int n ) { int dp [ n ] [ 2 ] ; dp [ 0 ] [ 0 ] = a [ 0 ] ; dp [ 0 ] [ 1 ] = b [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] [ 0 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) + a [ i ] ; dp [ i ] [ 1 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) ; if ( i - 2 >= 0 ) { dp [ i ] [ 1 ] = max ( dp [ i ] [ 1 ] , max ( dp [ i - 2 ] [ 0 ] , dp [ i - 2 ] [ 1 ] ) + b [ i ] ) ; } else { dp [ i ] [ 1 ] = max ( dp [ i ] [ 1 ] , b [ i ] ) ; } } return max ( dp [ n - 1 ] [ 0 ] , dp [ n - 1 ] [ 1 ] ) ; } int main ( ) { int A [ ] = { 10 , 1 , 10 , 10 } ; int B [ ] = { 5 , 50 , 1 , 5 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << MaximumSum ( A , B , N ) ; return 0 ; }