text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Choose k array elements such that difference of maximum and minimum is minimized | C ++ program to find minimum difference of maximum and minimum of K number . ; Return minimum difference of maximum and minimum of k elements of arr [ 0. . n - 1 ] . ; Sorting the array . ; Find minimum value among all K size subarray . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDiff ( int arr [ ] , int n , int k ) { int result = INT_MAX ; sort ( arr , arr + n ) ; for ( int i = 0 ; i <= n - k ; i ++ ) result = min ( result , arr [ i + k - 1 ] - arr [ i ] ) ; return result ; } int main ( ) { int arr [ ] = { 10 , 100 , 300 , 200 , 1000 , 20 , 30 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << minDiff ( arr , n , k ) << endl ; return 0 ; }
Sort even | Program to separately sort even - placed and odd placed numbers and place them together in sorted array . ; create evenArr [ ] and oddArr [ ] ; Put elements in oddArr [ ] and evenArr [ ] as per their position ; sort evenArr [ ] in ascending order sort oddArr [ ] in descending order ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void bitonicGenerator ( int arr [ ] , int n ) { vector < int > evenArr ; vector < int > oddArr ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! ( i % 2 ) ) evenArr . push_back ( arr [ i ] ) ; else oddArr . push_back ( arr [ i ] ) ; } sort ( evenArr . begin ( ) , evenArr . end ( ) ) ; sort ( oddArr . begin ( ) , oddArr . end ( ) , greater < int > ( ) ) ; int i = 0 ; for ( int j = 0 ; j < evenArr . size ( ) ; j ++ ) arr [ i ++ ] = evenArr [ j ] ; for ( int j = 0 ; j < oddArr . size ( ) ; j ++ ) arr [ i ++ ] = oddArr [ j ] ; } int main ( ) { int arr [ ] = { 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; bitonicGenerator ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Number of swaps to sort when only adjacent swapping allowed | C ++ program to count number of swaps required to sort an array when only swapping of adjacent elements is allowed . ; This function merges two sorted arrays and returns inversion count in the arrays . ; i is index for left subarray ; j is index for right subarray ; k is index for resultant merged subarray ; this is tricky -- see above explanation / diagram for merge ( ) ; Copy the remaining elements of left subarray ( if there are any ) to temp ; Copy the remaining elements of right subarray ( if there are any ) to temp ; Copy back the merged elements to original array ; An auxiliary recursive function that sorts the input array and returns the number of inversions in the array . ; Divide the array into two parts and call _mergeSortAndCountInv ( ) for each of the parts ; Inversion count will be sum of inversions in left - part , right - part and number of inversions in merging ; Merge the two parts ; This function sorts the input array and returns the number of inversions in the array ; Driver progra to test above functions
#include <bits/stdc++.h> NEW_LINE int merge ( int arr [ ] , int temp [ ] , int left , int mid , int right ) { int inv_count = 0 ; int i = left ; int j = mid ; int k = left ; while ( ( i <= mid - 1 ) && ( j <= right ) ) { if ( arr [ i ] <= arr [ j ] ) temp [ k ++ ] = arr [ i ++ ] ; else { temp [ k ++ ] = arr [ j ++ ] ; inv_count = inv_count + ( mid - i ) ; } } while ( i <= mid - 1 ) temp [ k ++ ] = arr [ i ++ ] ; while ( j <= right ) temp [ k ++ ] = arr [ j ++ ] ; for ( i = left ; i <= right ; i ++ ) arr [ i ] = temp [ i ] ; return inv_count ; } int _mergeSort ( int arr [ ] , int temp [ ] , int left , int right ) { int mid , inv_count = 0 ; if ( right > left ) { mid = ( right + left ) / 2 ; inv_count = _mergeSort ( arr , temp , left , mid ) ; inv_count += _mergeSort ( arr , temp , mid + 1 , right ) ; inv_count += merge ( arr , temp , left , mid + 1 , right ) ; } return inv_count ; } int countSwaps ( int arr [ ] , int n ) { int temp [ n ] ; return _mergeSort ( arr , temp , 0 , n - 1 ) ; } int main ( int argv , char * * args ) { int arr [ ] = { 1 , 20 , 6 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Number ▁ of ▁ swaps ▁ is ▁ % d ▁ STRNEWLINE " , countSwaps ( arr , n ) ) ; return 0 ; }
Check whether a given number is even or odd | A simple C ++ program to check for even or odd ; Returns true if n is even , else odd ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool isEven ( int n ) { return ( n % 2 == 0 ) ; } int main ( ) { int n = 101 ; isEven ( n ) ? cout << " Even " : cout << " Odd " ; return 0 ; }
Find Surpasser Count of each element in array | Naive C ++ program to find surpasser count of each element in array ; Function to find surpasser count of each element in array ; stores surpasser count for element arr [ i ] ; Function to print an array ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSurpasser ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ j ] > arr [ i ] ) count ++ ; cout << count << " ▁ " ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 2 , 7 , 5 , 3 , 0 , 8 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Given ▁ array ▁ is ▁ STRNEWLINE " ) ; printArray ( arr , n ) ; printf ( " Surpasser ▁ Count ▁ of ▁ array ▁ is ▁ STRNEWLINE " ) ; findSurpasser ( arr , n ) ; return 0 ; }
Minimum sum of two numbers formed from digits of an array | C ++ program to find minimum sum of two numbers formed from digits of the array . ; Function to find and return minimum sum of two numbers formed from digits of the array . ; sort the array ; let two numbers be a and b ; fill a and b with every alternate digit of input array ; return the sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int a = 0 , b = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i & 1 ) a = a * 10 + arr [ i ] ; else b = b * 10 + arr [ i ] ; } return a + b ; } int main ( ) { int arr [ ] = { 6 , 8 , 4 , 5 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Sum ▁ is ▁ " << solve ( arr , n ) ; return 0 ; }
Maximum product of a triplet ( subsequence of size 3 ) in array | A C ++ program to find a maximum product of a triplet in array of integers ; Function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; will contain max product ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProduct ( int arr [ ] , int n ) { if ( n < 3 ) return -1 ; int max_product = INT_MIN ; for ( int i = 0 ; i < n - 2 ; i ++ ) for ( int j = i + 1 ; j < n - 1 ; j ++ ) for ( int k = j + 1 ; k < n ; k ++ ) max_product = max ( max_product , arr [ i ] * arr [ j ] * arr [ k ] ) ; return max_product ; } int main ( ) { int arr [ ] = { 10 , 3 , 5 , 6 , 20 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int max = maxProduct ( arr , n ) ; if ( max == -1 ) cout << " No ▁ Triplet ▁ Exists " ; else cout << " Maximum ▁ product ▁ is ▁ " << max ; return 0 ; }
Maximum product of a triplet ( subsequence of size 3 ) in array | A C ++ program to find a maximum product of a triplet in array of integers ; Function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; Construct four auxiliary vectors of size n and initialize them by - 1 ; will contain max product ; to store maximum element on left of array ; to store minimum element on left of array ; leftMax [ i ] will contain max element on left of arr [ i ] excluding arr [ i ] . leftMin [ i ] will contain min element on left of arr [ i ] excluding arr [ i ] . ; reset max_sum to store maximum element on right of array ; reset min_sum to store minimum element on right of array ; rightMax [ i ] will contain max element on right of arr [ i ] excluding arr [ i ] . rightMin [ i ] will contain min element on right of arr [ i ] excluding arr [ i ] . ; For all array indexes i except first and last , compute maximum of arr [ i ] * x * y where x can be leftMax [ i ] or leftMin [ i ] and y can be rightMax [ i ] or rightMin [ i ] . ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProduct ( int arr [ ] , int n ) { if ( n < 3 ) return -1 ; vector < int > leftMin ( n , -1 ) ; vector < int > rightMin ( n , -1 ) ; vector < int > leftMax ( n , -1 ) ; vector < int > rightMax ( n , -1 ) ; int max_product = INT_MIN ; int max_sum = arr [ 0 ] ; int min_sum = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { leftMax [ i ] = max_sum ; if ( arr [ i ] > max_sum ) max_sum = arr [ i ] ; leftMin [ i ] = min_sum ; if ( arr [ i ] < min_sum ) min_sum = arr [ i ] ; } max_sum = arr [ n - 1 ] ; min_sum = arr [ n - 1 ] ; for ( int j = n - 2 ; j >= 0 ; j -- ) { rightMax [ j ] = max_sum ; if ( arr [ j ] > max_sum ) max_sum = arr [ j ] ; rightMin [ j ] = min_sum ; if ( arr [ j ] < min_sum ) min_sum = arr [ j ] ; } for ( int i = 1 ; i < n - 1 ; i ++ ) { int max1 = max ( arr [ i ] * leftMax [ i ] * rightMax [ i ] , arr [ i ] * leftMin [ i ] * rightMin [ i ] ) ; int max2 = max ( arr [ i ] * leftMax [ i ] * rightMin [ i ] , arr [ i ] * leftMin [ i ] * rightMax [ i ] ) ; max_product = max ( max_product , max ( max1 , max2 ) ) ; } return max_product ; } int main ( ) { int arr [ ] = { 1 , 4 , 3 , -6 , -7 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int max = maxProduct ( arr , n ) ; if ( max == -1 ) cout << " No ▁ Triplet ▁ Exists " ; else cout << " Maximum ▁ product ▁ is ▁ " << max ; return 0 ; }
Maximum product of a triplet ( subsequence of size 3 ) in array | A C ++ program to find a maximum product of a triplet in array of integers ; Function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; Sort the array in ascending order ; Return the maximum of product of last three elements and product of first two elements and last element ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProduct ( int arr [ ] , int n ) { if ( n < 3 ) return -1 ; sort ( arr , arr + n ) ; return max ( arr [ 0 ] * arr [ 1 ] * arr [ n - 1 ] , arr [ n - 1 ] * arr [ n - 2 ] * arr [ n - 3 ] ) ; } int main ( ) { int arr [ ] = { -10 , -3 , 5 , 6 , -20 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int max = maxProduct ( arr , n ) ; if ( max == -1 ) cout << " No ▁ Triplet ▁ Exists " ; else cout << " Maximum ▁ product ▁ is ▁ " << max ; return 0 ; }
Maximum product of a triplet ( subsequence of size 3 ) in array | A O ( n ) C ++ program to find maximum product pair in an array . ; Function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; Initialize Maximum , second maximum and third maximum element ; Initialize Minimum and second minimum element ; Update Maximum , second maximum and third maximum element ; Update second maximum and third maximum element ; Update third maximum element ; Update Minimum and second minimum element ; Update second minimum element ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProduct ( int arr [ ] , int n ) { if ( n < 3 ) return -1 ; int maxA = INT_MIN , maxB = INT_MIN , maxC = INT_MIN ; int minA = INT_MAX , minB = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > maxA ) { maxC = maxB ; maxB = maxA ; maxA = arr [ i ] ; } else if ( arr [ i ] > maxB ) { maxC = maxB ; maxB = arr [ i ] ; } else if ( arr [ i ] > maxC ) maxC = arr [ i ] ; if ( arr [ i ] < minA ) { minB = minA ; minA = arr [ i ] ; } else if ( arr [ i ] < minB ) minB = arr [ i ] ; } return max ( minA * minB * maxA , maxA * maxB * maxC ) ; } int main ( ) { int arr [ ] = { 1 , -4 , 3 , -6 , 7 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int max = maxProduct ( arr , n ) ; if ( max == -1 ) cout << " No ▁ Triplet ▁ Exists " ; else cout << " Maximum ▁ product ▁ is ▁ " << max ; return 0 ; }
How to efficiently sort a big list dates in 20 's | C ++ program to sort an array of dates using Radix Sort ; Utilitiy function to obtain maximum date or month or year ; A function to do counting sort of arr [ ] according to given q i . e . ( 0 for day , 1 for month , 2 for year ) ; to extract last digit divide by p then % 10 Store count of occurrences in cnt [ ] ; Build the output array ; Copy the output array to arr [ ] , so that arr [ ] now contains sorted numbers according to current digit ; update p to get the next digit ; The main function that sorts array of dates using Radix Sort ; First sort by day ; Then by month ; Finally by year ; A utility function to print an array ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMax ( int arr [ ] [ 3 ] , int n , int q ) { int maxi = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { maxi = max ( maxi , arr [ i ] [ q ] ) ; } return maxi ; } void sortDatesUtil ( int arr [ ] [ 3 ] , int n , int q ) { int maxi = getMax ( arr , n , q ) ; int p = 1 ; while ( maxi > 0 ) { int cnt [ 10 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { cnt [ ( arr [ i ] [ q ] / p ) % 10 ] ++ ; } for ( int i = 1 ; i < 10 ; i ++ ) { cnt [ i ] += cnt [ i - 1 ] ; } int ans [ n ] [ 3 ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { int lastDigit = ( arr [ i ] [ q ] / p ) % 10 ; for ( int j = 0 ; j < 3 ; j ++ ) { ans [ cnt [ lastDigit ] - 1 ] [ j ] = arr [ i ] [ j ] ; } cnt [ lastDigit ] -- ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { arr [ i ] [ j ] = ans [ i ] [ j ] ; } } p *= 10 ; maxi /= 10 ; } } void sortDates ( int dates [ ] [ 3 ] , int n ) { sortDatesUtil ( dates , n , 0 ) ; sortDatesUtil ( dates , n , 1 ) ; sortDatesUtil ( dates , n , 2 ) ; } void printArr ( int arr [ ] [ 3 ] , int n ) { for ( int i = 0 ; i < 6 ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { cout << arr [ i ] [ j ] << " ▁ " ; } cout << endl ; } } int main ( ) { int dates [ ] [ 3 ] = { { 20 , 1 , 2014 } , { 25 , 3 , 2010 } , { 3 , 12 , 2000 } , { 18 , 11 , 2000 } , { 19 , 4 , 2015 } , { 9 , 7 , 2005 } } ; int n = sizeof ( dates ) / sizeof ( dates [ 0 ] ) ; sortDates ( dates , n ) ; cout << " Sorted Dates " printArr ( dates , n ) ; return 0 ; }
Maximize sum of ratios of N given fractions by incrementing numerator and denominators K times by 1 | C ++ program for the above approach ; Function to increment the K fractions from the given array to maximize the sum of ratios of the given fractions ; Size of the array ; Max priority queue ; Iterate through the array ; Insert the incremented value if an operation is performed on the ith index ; Loop to perform K operations ; Increment the numerator and denominator of ith fraction ; Add the incremented value ; Stores the average ratio ; Return the ratio ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double maxAverageRatio ( vector < vector < int > > & arr , int K ) { int N = arr . size ( ) ; priority_queue < pair < double , int > > q ; for ( int i = 0 ; i < N ; i ++ ) { double extra = ( ( ( double ) arr [ i ] [ 0 ] + 1 ) / ( ( double ) arr [ i ] [ 1 ] + 1 ) ) - ( ( double ) arr [ i ] [ 0 ] / ( double ) arr [ i ] [ 1 ] ) ; q . push ( make_pair ( extra , i ) ) ; } while ( K -- ) { int i = q . top ( ) . second ; q . pop ( ) ; arr [ i ] [ 0 ] += 1 ; arr [ i ] [ 1 ] += 1 ; double extra = ( ( ( double ) arr [ i ] [ 0 ] + 1 ) / ( ( double ) arr [ i ] [ 1 ] + 1 ) ) - ( ( double ) arr [ i ] [ 0 ] / ( double ) arr [ i ] [ 1 ] ) ; q . push ( make_pair ( extra , i ) ) ; } double ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { ans += ( ( double ) arr [ i ] [ 0 ] / ( double ) arr [ i ] [ 1 ] ) ; } return ans / N ; } int main ( ) { vector < vector < int > > arr = { { 1 , 2 } , { 3 , 5 } , { 2 , 2 } } ; int K = 2 ; cout << maxAverageRatio ( arr , K ) ; return 0 ; }
Minimum operations to convert Binary Matrix A to B by flipping submatrix of size K | C ++ program for the above approach ; Function to count the operations required to convert matrix A to B ; Store the sizes of matrix ; Stores count of flips required ; Traverse the iven matrix ; Check if the matrix values are not equal ; Increment the count of moves ; Check if the current square sized exists or not ; Flip all the bits in this square sized submatrix ; Count of operations required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minMoves ( vector < vector < char > > a , vector < vector < char > > b , int K ) { int n = a . size ( ) , m = a [ 0 ] . size ( ) ; int cntOperations = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( a [ i ] [ j ] != b [ i ] [ j ] ) { cntOperations ++ ; if ( i + K - 1 >= n j + K - 1 >= m ) { return -1 ; } for ( int p = 0 ; p <= K - 1 ; p ++ ) { for ( int q = 0 ; q <= K - 1 ; q ++ ) { if ( a [ i + p ] [ j + q ] == '0' ) { a [ i + p ] [ j + q ] = '1' ; } else { a [ i + p ] [ j + q ] = '0' ; } } } } } } return cntOperations ; } int main ( ) { vector < vector < char > > A = { { '1' , '0' , '0' } , { '0' , '0' , '0' } , { '0' , '0' , '0' } } ; vector < vector < char > > B = { { '0' , '0' , '0' } , { '0' , '0' , '0' } , { '0' , '0' , '0' } } ; int K = 3 ; cout << minMoves ( A , B , K ) ; return 0 ; }
Lexicographically largest permutation by sequentially inserting Array elements at ends | C ++ program for the above approach ; Function to find the lexicographically largest permutation by sequentially inserting the array elements ; Stores the current state of the new array ; Stores ythe current maximum element of array arr [ ] ; Iterate the array elements ; If the current element is smaller than the current maximum , then insert ; If the current element is at least the current maximum ; Update the value of the current maximum ; Print resultant permutation ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void largestPermutation ( int arr [ ] , int N ) { deque < int > p ; int mx = arr [ 0 ] ; p . push_back ( arr [ 0 ] ) ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] < mx ) p . push_back ( arr [ i ] ) ; else { p . push_front ( arr [ i ] ) ; mx = arr [ i ] ; } } for ( auto i : p ) cout << i << " ▁ " ; } int main ( ) { int arr [ ] = { 3 , 1 , 2 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; largestPermutation ( arr , N ) ; return 0 ; }
Largest value of K that a set of all possible subset | C ++ program for the above approach ; Function to find maximum count of consecutive integers from 0 in set S of all possible subset - sum ; Stores the maximum possible integer ; Sort the given array in non - decrasing order ; Iterate the given array ; If arr [ i ] <= X + 1 , then update X otherwise break the loop ; Return Answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxConsecutiveCnt ( vector < int > arr ) { int X = 0 ; sort ( arr . begin ( ) , arr . end ( ) ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( arr [ i ] <= ( X + 1 ) ) { X = X + arr [ i ] ; } else { break ; } } return X + 1 ; } int main ( ) { vector < int > arr = { 1 , 1 , 1 , 4 } ; cout << maxConsecutiveCnt ( arr ) ; return 0 ; }
Maximum length of subarray with same sum at corresponding indices from two Arrays | C ++ program for the above approach ; Function to find maximum length of subarray of array A and B having equal sum ; Stores the maximum size of valid subarray ; Stores the prefix sum of the difference of the given arrays ; Traverse the given array ; Add the difference of the corresponding array element ; If current difference is not present ; If current difference is present , update the value of maxSize ; Return the maximum length ; Driver Code
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int maxLength ( vector < int > & A , vector < int > & B ) { int n = A . size ( ) ; int maxSize = 0 ; unordered_map < int , int > pre ; int diff = 0 ; pre [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { diff += ( A [ i ] - B [ i ] ) ; if ( pre . find ( diff ) == pre . end ( ) ) { pre = i + 1 ; } else { maxSize = max ( maxSize , i - pre + 1 ) ; } } return maxSize ; } int main ( ) { vector < int > A = { 1 , 2 , 3 , 4 } ; vector < int > B = { 4 , 3 , 2 , 1 } ; cout << maxLength ( A , B ) ; return 0 ; }
Minimum jumps required to reach all array elements using largest element | C ++ program for the above approach ; Function to find next greater element to left and right of current element ; Starting l and r from previous and the next element of the current element ; FInd the next greater element to the left ; Find the next greater element to the right ; Return l and r in the form of array of size 2 ; Function to find the minimum jumps required to reach to all elements from the largest element ; Stores the mapping from index to the element in array A [ ] ; Stores largest array element ; Find the two indices l , r such that A [ l ] > A [ i ] < A [ r ] and l < i < r using expand function ; sorting A in descending order ; Stores the resultant minimum jumps required ; Check if the current element is largest or not ; Find the answer to the current element ; Update the resultant minimum jumps for the current element ; Return the result ; Driver Code ; Print the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ar array NEW_LINE ar < int , 2 > expand ( int idx , vector < int > & A ) { int l = idx - 1 ; int r = idx + 1 ; while ( l >= 0 ) { if ( ( int ) ( A [ idx ] ) > A [ l ] ) { -- l ; } else { break ; } } if ( l < 0 l == idx ) { l = -2 ; } while ( r < ( int ) ( A . size ( ) ) ) { if ( ( int ) A [ idx ] > A [ r ] ) { ++ r ; } else { break ; } } if ( r >= ( int ) ( A . size ( ) ) r == idx ) { r = -2 ; } return { l , r } ; } vector < int > minJumps ( int N , vector < int > & A ) { vector < int > ans ( N , 0 ) ; map < int , ar < int , 2 > > mp ; map < int , int > iToA ; map < int , int > AToi ; int big = A [ 0 ] ; for ( int i = 0 ; i < N ; ++ i ) { big = max ( { big , A [ i ] } ) ; mp [ i ] = expand ( i , A ) ; iToA [ i ] = A [ i ] ; AToi [ A [ i ] ] = i ; } sort ( A . begin ( ) , A . end ( ) , greater < int > ( ) ) ; for ( int i = 0 ; i < A . size ( ) ; ++ i ) { int m ; if ( A [ i ] == big ) { int cur = AToi [ A [ i ] ] ; ans [ cur ] = 0 ; continue ; } int cur = AToi [ A [ i ] ] ; int l = mp [ cur ] [ 0 ] ; int r = mp [ cur ] [ 1 ] ; if ( l >= 0 && r < N ) { m = min ( ans [ l ] , ans [ r ] ) + 1 ; } else if ( l < 0 && r < N ) { m = ans [ r ] + 1 ; } else if ( l >= 0 && r >= N ) { m = ans [ l ] + 1 ; } ans [ cur ] = m ; } return ans ; } int main ( ) { vector < int > arr = { 5 , 1 , 3 , 4 , 7 } ; int N = arr . size ( ) ; vector < int > out = minJumps ( N , arr ) ; for ( auto & it : out ) cout << it << ' ▁ ' ; return 0 ; }
Largest square sub | C ++ program for the above approach ; Define the prefix sum arrays globally ; Diagonal sum ; Check each row ; Check each column ; Check anti - diagonal ; Store the size of the given grid ; Compute the prefix sum for the rows ; Compute the prefix sum for the columns ; Check for all possible square submatrix ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int prefix_sum_row [ 50 ] [ 51 ] ; int prefix_sum_col [ 51 ] [ 50 ] ; bool is_valid ( int r , int c , int size , vector < vector < int > > & grid ) { int r_end = r + size , c_end = c + size ; int sum = 0 ; for ( int i = r , j = c ; i < r_end ; i ++ , j ++ ) { sum += grid [ i ] [ j ] ; } for ( int i = r ; i < r_end ; i ++ ) { if ( prefix_sum_row [ i ] [ c_end ] - prefix_sum_row [ i ] != sum ) { return false ; } } for ( int i = c ; i < c_end ; i ++ ) { if ( prefix_sum_col [ r_end ] [ i ] - prefix_sum_col [ r ] [ i ] != sum ) { return false ; } } int ad_sum = 0 ; for ( int i = r , j = c_end - 1 ; i < r_end ; i ++ , j -- ) { ad_sum += grid [ i ] [ j ] ; } return ad_sum == sum ; } int largestSquareValidMatrix ( vector < vector < int > > & grid ) { int m = grid . size ( ) , n = grid [ 0 ] . size ( ) ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { prefix_sum_row [ i ] [ j ] = prefix_sum_row [ i ] [ j - 1 ] + grid [ i ] [ j - 1 ] ; } } for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { prefix_sum_col [ i ] [ j ] = prefix_sum_col [ i - 1 ] [ j ] + grid [ i - 1 ] [ j ] ; } } for ( int size = min ( m , n ) ; size > 1 ; size -- ) { for ( int i = 0 ; i <= m - size ; i ++ ) { for ( int j = 0 ; j <= n - size ; j ++ ) { if ( is_valid ( i , j , size , grid ) ) { return size ; } } } } return 1 ; } int main ( ) { vector < vector < int > > grid = { { 7 , 1 , 4 , 5 , 6 } , { 2 , 5 , 1 , 6 , 4 } , { 1 , 5 , 4 , 3 , 2 } , { 1 , 2 , 7 , 3 , 4 } } ; cout << largestSquareValidMatrix ( grid ) ; return 0 ; }
Minimize product of first 2 ^ KΓ’ β‚¬β€œ 1 Natural Numbers by swapping bits for any pair any number of times | C ++ program for the above approach ; Function to find the minimum positive product after swapping bits at the similar position for any two numbers ; Stores the resultant number ; range / 2 numbers will be 1 and range / 2 numbers will be range - 1 ; Multiply with the final number ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumPossibleProduct ( int K ) { int res = 1 ; int range = ( 1 << K ) - 1 ; for ( int i = 0 ; i < K ; i ++ ) { res *= ( range - 1 ) ; } res *= range ; return res ; } int main ( ) { int K = 3 ; cout << minimumPossibleProduct ( K ) ; return 0 ; }
Maximum size of subset of given array such that a triangle can be formed by any three integers as the sides of the triangle | C ++ program for the above approach ; Function to find the maximum size of the subset of the given array such that a triangle can be formed from any three integers of the subset as sides ; Sort arr [ ] in increasing order ; Stores the maximum size of a valid subset of the given array ; Stores the starting index of the current window ; Stores the last index of the current window ; Iterate over the array arr [ ] ; Increment j till the value of arr [ i ] + arr [ i + 1 ] > arr [ j ] holds true ; Update the value of maxSize ; Return Answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximizeSubset ( int arr [ ] , int N ) { sort ( arr , arr + N ) ; int maxSize = 0 ; int i = 0 ; int j = i + 2 ; while ( i < N - 2 ) { while ( arr [ i ] + arr [ i + 1 ] > arr [ j ] ) { j ++ ; } maxSize = max ( maxSize , j - i ) ; i ++ ; j = max ( j , i + 2 ) ; } return maxSize ; } int main ( ) { int arr [ ] = { 2 , 7 , 4 , 1 , 6 , 9 , 5 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximizeSubset ( arr , N ) << endl ; return 0 ; }
Maximum possible value of array elements that can be made based on given capacity conditions | C ++ program for the above approach ; Function to find the maximum element after shifting operations in arr [ ] ; Stores the sum of array element ; Stores the maximum element in cap [ ] ; Iterate to find maximum element ; Return the resultant maximum value ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxShiftArrayValue ( int arr [ ] , int cap [ ] , int N ) { int sumVals = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sumVals += arr [ i ] ; } int maxCapacity = 0 ; for ( int i = 0 ; i < N ; i ++ ) { maxCapacity = max ( cap [ i ] , maxCapacity ) ; } return min ( maxCapacity , sumVals ) ; } int main ( ) { int arr [ ] = { 2 , 3 } ; int cap [ ] = { 5 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxShiftArrayValue ( arr , cap , N ) ; return 0 ; }
Minimize cost to connect the graph by connecting any pairs of vertices having cost at least 0 | C ++ program for the above approach ; Function to perform the find operation to find the parent of a disjoint set ; FUnction to perform union operation of disjoint set union ; Update the minimum value such than it should be greater than 0 ; Update the minimum value such than it should be greater than 0 ; Function to minimize the cost to make the graph connected as per the given condition ; Stores the parent elements of sets ; Stores the rank of the sets ; Stores the minValue of the sets ; Update parent [ i ] to i ; Update minValue [ i ] to cost [ i - 1 ] ; Add i . first and i . second elements to the same set ; Stores the parent elements of the different components ; Insert parent of i to s ; Stores the minimum value from s ; Flag to mark if any minimum value is negative ; If minVal [ i ] is negative ; Mark flag as true ; Update the minimum value ; Stores minimum cost to add the edges ; If the given graph is connected or components minimum values not having any negative edge ; Update the minCost ; Print the value of minCost ; Print - 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Find ( vector < int > & parent , int a ) { return parent [ a ] = ( parent [ a ] == a ? a : Find ( parent , parent [ a ] ) ) ; } void Union ( vector < int > & parent , vector < int > & rank , vector < int > & minVal , int a , int b ) { a = Find ( parent , a ) ; b = Find ( parent , b ) ; if ( rank [ a ] == rank [ b ] ) rank [ a ] ++ ; if ( rank [ a ] > rank [ b ] ) { parent [ b ] = a ; if ( minVal [ a ] >= 0 && minVal [ b ] >= 0 ) { minVal [ a ] = min ( minVal [ a ] , minVal [ b ] ) ; } else if ( minVal [ a ] >= 0 && minVal [ b ] < 0 ) { minVal [ a ] = minVal [ a ] ; } else if ( minVal [ a ] < 0 && minVal [ b ] >= 0 ) { minVal [ a ] = minVal [ b ] ; } else { minVal [ a ] = max ( minVal [ a ] , minVal [ b ] ) ; } } else { parent [ a ] = b ; if ( minVal [ a ] >= 0 && minVal [ b ] >= 0 ) { minVal [ b ] = min ( minVal [ a ] , minVal [ b ] ) ; } else if ( minVal [ a ] >= 0 && minVal [ b ] < 0 ) { minVal [ b ] = minVal [ a ] ; } else if ( minVal [ a ] < 0 && minVal [ b ] >= 0 ) { minVal [ b ] = minVal [ b ] ; } else { minVal [ b ] = max ( minVal [ a ] , minVal [ b ] ) ; } } } void findMinCost ( vector < pair < int , int > > & G , vector < int > & cost , int N , int M ) { vector < int > parent ( N + 1 ) ; vector < int > rank ( N + 1 , 0 ) ; vector < int > minVal ( N + 1 ) ; for ( int i = 1 ; i < N + 1 ; i ++ ) { parent [ i ] = i ; minVal [ i ] = cost [ i - 1 ] ; } for ( auto i : G ) { Union ( parent , rank , minVal , i . first , i . second ) ; } set < int > s ; for ( int i = 1 ; i < N + 1 ; i ++ ) { s . insert ( Find ( parent , i ) ) ; } pair < int , int > min = { 0 , INT_MAX } ; bool flag = false ; for ( auto i : s ) { if ( minVal [ i ] < 0 ) { flag = true ; } if ( min . second > minVal [ i ] ) { min = { i , minVal [ i ] } ; } } int minCost = 0 ; if ( ! flag || ( flag && s . size ( ) == 1 ) ) { for ( auto i : s ) { if ( i != min . first ) { minCost += ( minVal [ i ] + min . second ) ; } } cout << minCost << endl ; } else { cout << -1 << endl ; } } int main ( ) { int N = 6 ; vector < pair < int , int > > G = { { 3 , 1 } , { 2 , 3 } , { 2 , 1 } , { 4 , 5 } , { 5 , 6 } , { 6 , 4 } } ; vector < int > cost { 2 , 1 , 5 , 3 , 2 , 9 } ; int M = G . size ( ) ; findMinCost ( G , cost , N , M ) ; return 0 ; }
Minimum size of Array possible with given sum and product values | C ++ program for the above approach ; Function to find the minimum size of array with sum S and product P ; Base Case ; Iterate through all values of S and check the mentioned condition ; Otherwise , print " - 1" ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumSizeArray ( int S , int P ) { if ( S == P ) { return 1 ; } for ( int i = 2 ; i <= S ; i ++ ) { double d = i ; if ( ( S / d ) >= pow ( P , 1.0 / d ) ) { return i ; } } return -1 ; } int main ( ) { int S = 5 , P = 6 ; cout << minimumSizeArray ( S , P ) ; return 0 ; }
Smallest possible integer to be added to N | C ++ program for the above approach ; Function to find the smallest positive integer X such that X is added to every element of A except one element to give array B ; Stores the unique elements of array A ; Insert A [ i ] into the set s ; Sort array A [ ] ; Sort array B [ ] ; Assume X value as B [ 0 ] - A [ 1 ] ; Check if X value assumed is negative or 0 ; Update the X value to B [ 0 ] - A [ 0 ] ; If assumed value is wrong ; Update X value ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findVal ( int A [ ] , int B [ ] , int N ) { unordered_set < int > s ; for ( int i = 0 ; i < N ; i ++ ) { s . insert ( A [ i ] ) ; } sort ( A , A + N ) ; sort ( B , B + N - 1 ) ; int X = B [ 0 ] - A [ 1 ] ; if ( X <= 0 ) X = B [ 0 ] - A [ 0 ] ; else { for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( s . count ( B [ i ] - X ) == 0 ) { X = B [ 0 ] - A [ 0 ] ; break ; } } } cout << X << endl ; } int main ( ) { int A [ ] = { 1 , 4 , 3 , 8 } ; int B [ ] = { 15 , 8 , 11 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; findVal ( A , B , N ) ; return 0 ; }
Count of integral points that lie at a distance D from origin | C ++ program for the above approach ; Function to find the total valid integer coordinates at a distance D from origin ; Stores the count of valid points ; Iterate over possibel x coordinates ; Find the respective y coordinate with the pythagoras theorem ; Adding 4 to compensate the coordinates present on x and y axes . ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPoints ( int D ) { int count = 0 ; for ( int x = 1 ; x * x < D * D ; x ++ ) { int y = ( int ) sqrt ( double ( D * D - x * x ) ) ; if ( x * x + y * y == D * D ) { count += 4 ; } } count += 4 ; return count ; } int main ( ) { int D = 5 ; cout << countPoints ( D ) ; return 0 ; }
Sum of the shortest distance between all 0 s to 1 in given binary string | C ++ program for the above approach ; Function to find the total sum of the shortest distance between every 0 to 1 in a given binary string ; Stores the prefix distance and suffix distance from 0 to 1 ; Stores the current distance from 1 to 0 ; Marks the 1 ; If current character is 1 ; Mark haveOne to true ; Assign the cnt to 0 ; Assign prefixDistance [ i ] as 0 ; If haveOne is true ; Update the cnt ; Update prefixDistance [ i ] ; Assign prefixDistance [ i ] as INT_MAX ; Assign haveOne as false ; If current character is 1 ; Mark haveOne to true ; Assign the cnt to 0 ; Assign the suffixDistance [ i ] as 0 ; If haveOne is true ; Update the cnt ; Update suffixDistance [ i ] as cnt ; Assign suffixDistance [ i ] as INT_MAX ; Stores the total sum of distances between 0 to nearest 1 ; If current character is 0 ; Update the value of sum ; Print the value of the sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findTotalDistance ( string S , int N ) { vector < int > prefixDistance ( N ) ; vector < int > suffixDistance ( N ) ; int cnt = 0 ; bool haveOne = false ; for ( int i = 0 ; i < N ; ++ i ) { if ( S [ i ] == '1' ) { haveOne = true ; cnt = 0 ; prefixDistance [ i ] = 0 ; } else if ( haveOne ) { cnt ++ ; prefixDistance [ i ] = cnt ; } else prefixDistance [ i ] = INT_MAX ; } haveOne = false ; for ( int i = N - 1 ; i >= 0 ; -- i ) { if ( S [ i ] == '1' ) { haveOne = true ; cnt = 0 ; suffixDistance [ i ] = 0 ; } else if ( haveOne ) { cnt ++ ; suffixDistance [ i ] = cnt ; } else suffixDistance [ i ] = INT_MAX ; } int sum = 0 ; for ( int i = 0 ; i < N ; ++ i ) { if ( S [ i ] == '0' ) { sum += min ( prefixDistance [ i ] , suffixDistance [ i ] ) ; } } cout << sum << endl ; } int main ( ) { string S = "100100" ; int N = S . length ( ) ; findTotalDistance ( S , N ) ; return 0 ; }
Minimize value of | A | C ++ program for the above approach ; Function to find the minimum possible value of | A - X | + | B - Y | + | C - Z | such that X * Y = Z for given A , B and C ; Stores the minimum value of | A - X | + | B - Y | + | C - Z | such that X * Y = Z ; Iterate over all values of i in the range [ 1 , 2 * C ] ; Iterate over all values of j such that i * j <= 2 * c ; Update the value of ans ; Return answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimizeCost ( int A , int B , int C ) { int ans = A + B + C ; for ( int i = 1 ; i <= 2 * C ; i ++ ) { int j = 0 ; while ( i * j <= 2 * C ) { ans = min ( ans , abs ( A - i ) + abs ( B - j ) + abs ( i * j - C ) ) ; j ++ ; } } return ans ; } int main ( ) { int A = 19 , B = 28 , C = 522 ; cout << minimizeCost ( A , B , C ) ; return 0 ; }
Average value of set bit count in given Binary string after performing all possible choices of K operations | C ++ program for the above approach ; Function to calculate the average number of Set bits after after given operations ; Stores the average number of set bits after current operation ; Stores the average number of set bits after current operation ; Iterate through the array arr [ ] and update the values of p and q ; Store the value of p and q of the previous state before their updation ; Update average number of set bits after performing the ith operation ; Update average number of off bits after performing the ith operation ; Return Answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double averageSetBits ( int N , int K , int arr [ ] ) { double p = N ; double q = 0 ; for ( int i = 0 ; i < K ; i ++ ) { double _p = p , _q = q ; p = _p - _p * arr [ i ] / N + _q * arr [ i ] / N ; q = _q - _q * arr [ i ] / N + _p * arr [ i ] / N ; } return p ; } int main ( ) { int N = 5 ; int arr [ ] = { 1 , 2 , 3 } ; int K = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << setprecision ( 10 ) << averageSetBits ( N , K , arr ) ; return 0 ; }
Find maximum sum of subsequence after flipping signs of at most K elements in given Array | C ++ implementation for the above approach ; Function to calculate the max sum of subsequence ; Variable to store the max sum ; Sort the array ; Iterate over the array ; Flip sign ; Decrement k ; Traverse over the array ; Add only positive elements ; Return the max sum ; Driver Code ; Given array ; Variable to store number of flips are allowed ; Function call to find the maximum sum of subsequence
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubseq ( int arr [ ] , int N , int K ) { int sum = 0 ; sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( K == 0 ) break ; if ( arr [ i ] < 0 ) { arr [ i ] = - arr [ i ] ; K -- ; } } for ( int i = 0 ; i < N ; i ++ ) if ( arr [ i ] > 0 ) sum += arr [ i ] ; return sum ; } int main ( ) { int arr [ ] = { 6 , -10 , -1 , 0 , -4 , 2 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSubseq ( arr , N , K ) ; return 0 ; }
Minimum number of intervals to cover the target interval | C ++ program for the above approach ; Function to find the minimum number of intervals in the array A [ ] to cover the entire target interval ; Sort the array A [ ] in increasing order of starting point ; Insert a pair of INT_MAX to prevent going out of bounds ; Stores start of current interval ; Stores end of current interval ; Stores the count of intervals ; Iterate over all the intervals ; If starting point of current index <= start ; Update the value of start ; Increment the value of count ; If the target interval is already covered or it is not possible to move then break the loop ; If the entire target interval is not covered ; Return Answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimizeSegment ( vector < pair < int , int > > A , pair < int , int > X ) { sort ( A . begin ( ) , A . end ( ) ) ; A . push_back ( { INT_MAX , INT_MAX } ) ; int start = X . first ; int end = X . first - 1 ; int cnt = 0 ; for ( int i = 0 ; i < A . size ( ) ; ) { if ( A [ i ] . first <= start ) { end = max ( A [ i ++ ] . second , end ) ; } else { start = end ; ++ cnt ; if ( A [ i ] . first > end end >= X . second ) { break ; } } } if ( end < X . second ) { return -1 ; } return cnt ; } int main ( ) { vector < pair < int , int > > A = { { 1 , 3 } , { 2 , 4 } , { 2 , 10 } , { 2 , 3 } , { 1 , 1 } } ; pair < int , int > X = { 1 , 10 } ; cout << minimizeSegment ( A , X ) ; return 0 ; }
K | C ++ implementation for the above approach ; Function to calculate K - th smallest solution ( Y ) of equation X + Y = X | Y ; Initialize the variable to store the answer ; The i - th bit of X is off ; The i - bit of K is on ; Divide K by 2 ; If K becomes 0 then break ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long KthSolution ( long long X , long long K ) { long long ans = 0 ; for ( int i = 0 ; i < 64 ; i ++ ) { if ( ! ( X & ( 1LL << i ) ) ) { if ( K & 1 ) { ans |= ( 1LL << i ) ; } K >>= 1 ; if ( ! K ) { break ; } } } return ans ; } int main ( ) { long long X = 5 , K = 5 ; cout << KthSolution ( X , K ) ; return 0 ; }
Rearrange sorted array such that all odd indices elements comes before all even indices element | C ++ program for the above approach ; Function to print the array ; Function to rearrange the array such that odd indexed elements come before even indexed elements ; Reduces the size of array by one because last element does not need to be changed in case N = odd ; Initialize the variables ; Iterate over the range ; Add the modified element at the odd position ; Iterate over the range ; Add the modified element at the even position ; Iterate over the range ; Divide by thr maximum element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printTheArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) cout << arr [ i ] << " ▁ " ; } void rearrange ( int arr [ ] , int N ) { if ( N & 1 ) N -- ; int odd_idx = 1 , even_idx = 0 ; int i , max_elem = arr [ N - 1 ] + 1 ; for ( i = 0 ; i < N / 2 ; i ++ ) { arr [ i ] += ( arr [ odd_idx ] % max_elem ) * max_elem ; odd_idx += 2 ; } for ( ; i < N ; i ++ ) { arr [ i ] += ( arr [ even_idx ] % max_elem ) * max_elem ; even_idx += 2 ; } for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = arr [ i ] / max_elem ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 16 , 18 , 19 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrange ( arr , N ) ; printTheArray ( arr , N ) ; return 0 ; }
Find range of values for S in given Array with values satisfying [ arr [ i ] = floor ( ( i * S ) / K ) ] | C ++ program for the above approach ; Function to find the range of values for S in a given array that satisfies the given condition ; Stores the left range value ; Stores the right range value ; Find the current left range value for S ; Find the current right range value for S ; Updating L value ; Updating R value ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findRange ( int arr [ ] , int N , int K ) { int L = INT_MIN ; int R = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { int l = ( int ) ceil ( 1.0 * arr [ i ] * K / ( i + 1 ) ) ; int r = ( int ) ceil ( ( 1.0 + arr [ i ] ) * K / ( i + 1 ) ) - 1 ; L = max ( L , l ) ; R = min ( R , r ) ; } cout << L << " ▁ " << R ; } int main ( ) { int arr [ ] = { 2 , 4 , 6 , 9 , 11 } ; int K = 10 ; int N = sizeof ( arr ) / sizeof ( int ) ; findRange ( arr , N , K ) ; return 0 ; }
Find an anagram of given String having different characters at corresponding indices | C ++ program for the above approach ; Function to find anagram of string such that characters at the same indices are different ; Copying our original string for comparison ; Declaring the two pointers ; Checking the given condition ; When string length is odd ; The mid element ; If the characters are the same , then perform the swap operation as illustrated ; Check if the corresponding indices has the same character or not ; If string follows required condition ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findAnagram ( string s ) { string check = s ; int i = 0 , j = s . length ( ) - 1 ; while ( i < s . length ( ) && j >= 0 ) { if ( s [ i ] != s [ j ] && check [ i ] != s [ j ] && check [ j ] != s [ i ] ) { swap ( s [ i ] , s [ j ] ) ; i ++ ; j = s . length ( ) - 1 ; } else { j -- ; } } if ( s . length ( ) % 2 != 0 ) { int mid = s . length ( ) / 2 ; if ( check [ mid ] == s [ mid ] ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( check [ i ] != s [ mid ] && s [ i ] != s [ mid ] ) { swap ( s [ i ] , s [ mid ] ) ; break ; } } } } bool ok = true ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( check [ i ] == s [ i ] ) { ok = false ; break ; } } if ( ok ) cout << s ; else cout << -1 ; } int main ( ) { string S = " geek " ; findAnagram ( S ) ; return 0 ; }
Lexicographically smallest permutation of [ 1 , N ] based on given Binary string | C ++ program for the above approach ; Function to generate the lexicographically smallest permutation according to the given criteria ; Stores the resultant permutation ; Initialize the first elements to 1 ; Traverse the given string S ; Number greater than last number ; Number equal to the last number ; Correct all numbers to the left of the current index ; Printing the permutation ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void constructPermutation ( string S , int N ) { int ans [ N ] ; ans [ 0 ] = 1 ; for ( int i = 1 ; i < N ; ++ i ) { if ( S [ i - 1 ] == '0' ) { ans [ i ] = i + 1 ; } else { ans [ i ] = ans [ i - 1 ] ; } for ( int j = 0 ; j < i ; ++ j ) { if ( ans [ j ] >= ans [ i ] ) { ans [ j ] ++ ; } } } for ( int i = 0 ; i < N ; i ++ ) { cout << ans [ i ] ; if ( i != N - 1 ) { cout << " ▁ " ; } } } int main ( ) { string S = "100101" ; constructPermutation ( S , S . length ( ) + 1 ) ; return 0 ; }
Kth smallest positive integer Y such that its sum with X is same as its bitwise OR with X | C ++ implementation for the above approach ; Function to calculate K - th smallest solution ( Y ) of equation X + Y = X | Y ; Initialize the variable to store the answer ; The i - th bit of X is off ; The i - bit of K is on ; Divide K by 2 ; If K becomes 0 then break ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long KthSolution ( long long X , long long K ) { long long ans = 0 ; for ( int i = 0 ; i < 64 ; i ++ ) { if ( ! ( X & ( 1LL << i ) ) ) { if ( K & 1 ) { ans |= ( 1LL << i ) ; } K >>= 1 ; if ( ! K ) { break ; } } } return ans ; } int main ( ) { long long X = 10 , K = 5 ; cout << KthSolution ( X , K ) ; return 0 ; }
Count of distinct N | C ++ program of the above approach ; Function to find the count of distinct arrays of size n having elements in range [ 1 , k ] and all adjacent elements ( P , Q ) follows ( P <= Q ) or ( P % Q > 0 ) ; Stores the divisors of all integers in the range [ 1 , k ] ; Calculate the divisors of all integers using the Sieve ; Stores the dp states such that dp [ i ] [ j ] with i elements having j as the last element of array ; Initialize the dp array ; Calculate the dp states using the derived relation ; Calculate the sum for len - 1 ; Subtract dp [ len - 1 ] [ j ] for each factor of j from [ 1 , K ] ; Calculate the final result ; Return the resultant sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countArrays ( int n , int k ) { vector < vector < int > > divisors ( k + 1 ) ; for ( int i = 1 ; i <= k ; i ++ ) { for ( int j = 2 * i ; j <= k ; j += i ) { divisors [ j ] . push_back ( i ) ; } } vector < vector < int > > dp ( n + 1 , vector < int > ( k + 1 ) ) ; for ( int j = 1 ; j <= k ; j ++ ) { dp [ 1 ] [ j ] = 1 ; } for ( int x = 2 ; x <= n ; x ++ ) { int sum = 0 ; for ( int j = 1 ; j <= k ; j ++ ) { sum += dp [ x - 1 ] [ j ] ; } for ( int y = 1 ; y <= k ; y ++ ) { dp [ x ] [ y ] = sum ; for ( int d : divisors [ y ] ) { dp [ x ] [ y ] = ( dp [ x ] [ y ] - dp [ x - 1 ] [ d ] ) ; } } } int sum = 0 ; for ( int j = 1 ; j <= k ; j ++ ) { sum += dp [ n ] [ j ] ; } return sum ; } int main ( ) { int N = 2 , K = 3 ; cout << countArrays ( N , K ) ; return 0 ; }
Minimize increment | C ++ Program of the above approach ; Function to calculate the minimum number of operations to convert array A to array B by incrementing and decrementing adjacent elements ; Stores the final count ; Stores the sum of array A and B respectivelly ; Check of the sums are unequall ; Pointer to iterate through array ; Case 1 where A [ i ] > B [ i ] ; Stores the extra values for the current index ; Iterate the array from [ i - 1 , 0 ] ; Stores the count of values being transfered from A [ i ] to A [ j ] ; Add operation count ; Iterate the array in right direction id A [ i ] - B [ i ] > 0 ; Iterate the array from [ i + 1 , n - 1 ] ; Stores the count of values being transfered from A [ i ] to A [ j ] ; Add operation count ; Return Answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumMoves ( int A [ ] , int B [ ] , int N ) { int ans = 0 ; int sum_A = 0 , sum_B = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum_A += A [ i ] ; } for ( int i = 0 ; i < N ; i ++ ) { sum_B += B [ i ] ; } if ( sum_A != sum_B ) { return -1 ; } int i = 0 ; while ( i < N ) { if ( A [ i ] > B [ i ] ) { int temp = A [ i ] - B [ i ] ; int j = i - 1 ; while ( j >= 0 && temp > 0 ) { if ( B [ j ] > A [ j ] ) { int cnt = min ( temp , ( B [ j ] - A [ j ] ) ) ; A [ j ] += cnt ; temp -= cnt ; ans += ( cnt * abs ( j - i ) ) ; } j -- ; } if ( temp > 0 ) { int j = i + 1 ; while ( j < N && temp > 0 ) { if ( B [ j ] > A [ j ] ) { int cnt = min ( temp , ( B [ j ] - A [ j ] ) ) ; A [ j ] += cnt ; temp -= cnt ; ans += ( cnt * abs ( j - i ) ) ; } j ++ ; } } } i ++ ; } return ans ; } int main ( ) { int A [ ] = { 1 , 5 , 7 } ; int B [ ] = { 13 , 0 , 0 } ; int N = sizeof ( A ) / sizeof ( int ) ; cout << minimumMoves ( A , B , N ) ; return 0 ; }
Check if X can be reduced to 0 in exactly T moves by substracting D or 1 from it | C ++ Program to implement the above approach ; Function to check the above problem condition ; Check for base cases ; Check if D - 1 is a divisor of X - T ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int possibleReachingSequence ( int X , int D , int T ) { if ( X < T ) { cout << " NO " ; return 0 ; } if ( T * D < X ) { cout << " NO " ; return 0 ; } if ( ( X - T ) % ( D - 1 ) == 0 ) { cout << " YES " ; } else { cout << " NO " ; } return 0 ; } int main ( ) { int X = 10 , D = 3 , T = 6 ; possibleReachingSequence ( X , D , T ) ; }
Maximum number of times Array can be reduced in half when its all elements are even | C ++ code implementation for the above approach ; Function to return the number of operations possible ; counter to store the number of times the current element is divisible by 2 ; variable to store the final answer ; Initialize the counter to zero for each element ; update the counter till the number is divisible by 2 ; update the answer as the minimum of all the counts ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int arrayDivisionByTwo ( int arr [ ] , int n ) { int cnt = 0 ; int ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { cnt = 0 ; while ( arr [ i ] % 2 == 0 ) { arr [ i ] = arr [ i ] / 2 ; cnt ++ ; } ans = min ( ans , cnt ) ; } return ans ; } int main ( ) { int arr [ ] = { 8 , 12 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << arrayDivisionByTwo ( arr , n ) ; return 0 ; }
Find smallest number with given digits and sum of digits | C ++ Program of the above approach ; Function to print the minimum integer having only digits P and Q and the sum of digits as N ; If Q is greater that P then swap the values of P and Q ; If P and Q are both zero or if Q is zero and N is not divisible by P then there is no possible integer which satisfies the given conditions ; Loop to find the maximum value of count_P that also satisfy P * count_P + Q * count_Q = N ; If N is 0 , their is a valid integer possible that satisfies all the requires conditions ; Print Answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMinInteger ( int P , int Q , int N ) { if ( Q > P ) { swap ( P , Q ) ; } if ( Q == 0 && ( P == 0 N % P != 0 ) ) { cout << " Not ▁ Possible " ; return ; } int count_P = 0 , count_Q = 0 ; while ( N > 0 ) { if ( N % P == 0 ) { count_P += N / P ; N = 0 ; } else { N = N - Q ; count_Q ++ ; } } if ( N == 0 ) { for ( int i = 0 ; i < count_Q ; i ++ ) cout << Q ; for ( int i = 0 ; i < count_P ; i ++ ) cout << P ; } else { cout << " Not ▁ Possible " ; } } int main ( ) { int N = 32 ; int P = 7 ; int Q = 4 ; printMinInteger ( P , Q , N ) ; return 0 ; }
Minimum number of sum and modulo operations using given numbers to reach target | C ++ implementation of the above approach ; Function to find the minimum moves to reach K from N ; Initialization of dp vector ; dp [ i ] = minimum pushes required to reach i ; Traversing through the buttons ; Iterating through all the positions ; If not visited ; Next status of lock ; Advance to next state ; Return the final dp [ target ] ; Driver function ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minPushes ( int N , int K , vector < int > arr ) { vector < int > dp ( 100000 , -1 ) ; dp [ N ] = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { for ( int xx = 0 ; xx < 100000 ; xx ++ ) { int x = xx ; if ( dp [ x ] == -1 ) continue ; int next = ( x + arr [ i ] ) % 100000 ; while ( dp [ next ] == -1 dp [ next ] > dp [ x ] + 1 ) { dp [ next ] = dp [ x ] + 1 ; x = next ; next = ( next + arr [ i ] ) % 100000 ; } } } return dp [ K ] ; } int main ( ) { int N = 99880 , K = 89 ; vector < int > arr { 100 , 3 } ; cout << minPushes ( N , K , arr ) ; return 0 ; }
Minimum number of Apples to be collected from trees to guarantee M red apples | C ++ program for the above approach ; Function to minimum no . of apples ; If we get all required apple from South ; If we required trees at East and West ; If we doesn 't have enough red apples ; Driver Code ; No . of red apple for gift ; No . of red apple in each tree ; No . of tree in North ; No . of tree in South ; No . of tree in West ; No . of tree in East ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minApples ( int M , int K , int N , int S , int W , int E ) { if ( M <= S * K ) return M ; else if ( M <= S * K + E + W ) return S * K + ( M - S * K ) * K ; else return -1 ; } int main ( ) { int M = 10 ; int K = 15 ; int N = 0 ; int S = 1 ; int W = 0 ; int E = 0 ; int ans = minApples ( M , K , N , S , W , E ) ; cout << ans << endl ; }
Minimum increments or decrements required to signs of prefix sum array elements alternating | C ++ program for the above approach ; Function to find the minimum number of increments / decrements of array elements by 1 to make signs of prefix sum array elements alternating ; Case 1. neg - pos - neg ; Stores the current sign of the prefix sum of array ; Stores minimum number of operations for Case 1 ; Traverse the array ; Checking both conditions ; Update the current prefix1 to currentPrefixSum ; Case 2. pos - neg - pos ; Stores the prefix sum of array ; Stores minimum number of operations for Case 1 ; Checking both conditions ; Update the current prefix2 to currentPrefixSum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumOperations ( int A [ ] , int N ) { int cur_prefix_1 = 0 ; int parity = -1 ; int minOperationsCase1 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { cur_prefix_1 += A [ i ] ; if ( cur_prefix_1 == 0 parity * cur_prefix_1 < 0 ) { minOperationsCase1 += abs ( parity - cur_prefix_1 ) ; cur_prefix_1 = parity ; } parity *= -1 ; } int cur_prefix_2 = 0 ; parity = 1 ; int minOperationsCase2 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { cur_prefix_2 += A [ i ] ; if ( cur_prefix_2 == 0 parity * cur_prefix_2 < 0 ) { minOperationsCase2 += abs ( parity - cur_prefix_2 ) ; cur_prefix_2 = parity ; } parity *= -1 ; } return min ( minOperationsCase1 , minOperationsCase2 ) ; } int main ( ) { int A [ ] = { 1 , -3 , 1 , 0 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minimumOperations ( A , N ) ; return 0 ; }
Generate an array of maximum sum such that each element exceeds all elements present either on its left or right | C ++ code for the above approach ; Function to construct the array having maximum sum satisfying the given criteria ; Declaration of the array arrA [ ] and ans [ ] ; Stores the maximum sum of the resultant array ; Initialize the array arrA [ ] ; Traversing the array arrA [ ] ; Initialize the array arrB [ ] ; Assign the maximum element to the current element ; Form the first increasing till every index i ; Make the current element as the maximum element ; Forming decreasing from the index i + 1 to the index N ; Initialize the sum ; Find the total sum ; Check if the total sum is at least the sum found then make ans as ansB ; Print the final array formed ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumSumArray ( int arr [ ] , int N ) { vector < int > arrA ( N ) , ans ( N ) ; int maxSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) arrA [ i ] = arr [ i ] ; for ( int i = 0 ; i < N ; i ++ ) { vector < int > arrB ( N ) ; int maximum = arrA [ i ] ; arrB [ i ] = maximum ; for ( int j = i - 1 ; j >= 0 ; j -- ) { arrB [ j ] = min ( maximum , arrA [ j ] ) ; maximum = arrB [ j ] ; } maximum = arrA [ i ] ; for ( int j = i + 1 ; j < N ; j ++ ) { arrB [ j ] = min ( maximum , arrA [ j ] ) ; maximum = arrB [ j ] ; } int sum = 0 ; for ( int j = 0 ; j < N ; j ++ ) sum += arrB [ j ] ; if ( sum > maxSum ) { maxSum = sum ; ans = arrB ; } } for ( int val : ans ) { cout << val << " ▁ " ; } } int main ( ) { int A [ ] = { 10 , 6 , 8 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; maximumSumArray ( A , N ) ; return 0 ; }
Minimize product of two scores possible by at most M reductions | C ++ program for the above approach ; Utility function to find the minimum product of R1 and R2 possible ; Reaching to its limit ; If M is remaining ; Function to find the minimum product of R1 and R2 ; Case 1 - R1 reduces first ; Case 2 - R2 reduces first ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minProductUtil ( int R1 , int B1 , int R2 , int B2 , int M ) { int x = min ( R1 - B1 , M ) ; M -= x ; R1 -= x ; if ( M > 0 ) { int y = min ( R2 - B2 , M ) ; M -= y ; R2 -= y ; } return R1 * R2 ; } int minProduct ( int R1 , int B1 , int R2 , int B2 , int M ) { int res1 = minProductUtil ( R1 , B1 , R2 , B2 , M ) ; int res2 = minProductUtil ( R2 , B2 , R1 , B1 , M ) ; return min ( res1 , res2 ) ; } int main ( ) { int R1 = 21 , B1 = 10 , R2 = 13 , B2 = 11 , M = 3 ; cout << ( minProduct ( R1 , B1 , R2 , B2 , M ) ) ; return 0 ; }
Maximize the profit after selling the tickets | Set 2 ( For elements in range [ 1 , 10 ^ 6 ] ) | C ++ program for the above approach ; Function to find maximum profit after selling K tickets ; Frequency array to store freq of every element of the array ; Modify the arr [ ] so that the array is sorted in O ( N ) ; Variable to store answer ; Traverse the array while K > 0 and j >= 0 ; If arr [ i ] > arr [ j ] then ticket can be brought from counter [ j + 1 , N ] ; If arr [ j ] = = arr [ i ] decrement j until arr [ j ] != arr [ i ] ; Sell tickets from counter [ j + 1 , N ] ; All elements of array are equal Send tickets from each counter 1 time until K > 0. ; Converting answer from long long to int ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxAmount ( int n , int k , int arr [ ] ) { int A [ 1000001 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { A [ arr [ i ] ] ++ ; } int j = 0 ; for ( int i = 0 ; i < 1000001 ; i ++ ) { while ( A [ i ] != 0 ) { arr [ j ++ ] = i ; A [ i ] -- ; } } long long int ans = 0 ; int mod = 1e9 + 7 ; int i = n - 1 ; j = n - 2 ; while ( k > 0 && j >= 0 ) { if ( arr [ i ] > arr [ j ] ) { ans = ans + min ( k , ( i - j ) ) * arr [ i ] ; k = k - ( i - j ) ; arr [ i ] -- ; } else { while ( j >= 0 && arr [ j ] == arr [ i ] ) j -- ; if ( j < 0 ) break ; ans = ans + min ( k , ( i - j ) ) * arr [ i ] ; k = k - ( i - j ) ; arr [ i ] -- ; } } while ( k > 0 && arr [ i ] != 0 ) { ans = ans + min ( n , k ) * arr [ i ] ; k -= n ; arr [ i ] -- ; } ans = ans % mod ; int x = ans ; return x ; } int main ( ) { int n = 5 ; int k = 3 ; int arr [ n ] = { 4 , 3 , 6 , 2 , 4 } ; int ans = maxAmount ( n , k , arr ) ; cout << ans ; return 0 ; }
Maximize sum of averages of subsequences of lengths lying in a given range | C ++ program for the above approach ; Function to find the maximum sum of average of groups ; Sort the given array ; Stores the sum of averages ; Stores count of array element ; Add the current value to the variable sum ; Increment the count by 1 ; If the current size is X ; If the remaining elements can 't become a group ; Iterate until i is less than N ; Update the value of X ; Update the average ; Find the average ; Reset the sum and count ; Print maximum sum of averages ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxAverage ( int A [ ] , int N , int X , int Y ) { sort ( A , A + N ) ; int sum = 0 ; double res = 0 ; int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += A [ i ] ; count ++ ; if ( count == X ) { if ( N - i - 1 < X ) { i ++ ; int cnt = 0 ; while ( i < N ) { cnt ++ ; sum += A [ i ] ; i ++ ; } X = X + cnt ; res += ( double ) sum / double ( X ) ; break ; } res += ( double ) sum / double ( X ) ; sum = 0 ; count = 0 ; } } cout << fixed << setprecision ( 2 ) << res << " STRNEWLINE " ; } int main ( ) { int A [ ] = { 4 , 10 , 6 , 5 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int X = 2 , Y = 3 ; maxAverage ( A , N , X , Y ) ; return 0 ; }
Rearrange characters in a sorted string such that no pair of adjacent characters are the same | C ++ program for the above approach ; Function to check if a string S contains pair of adjacent characters that are equal or not ; Traverse the string S ; If S [ i ] and S [ i + 1 ] are equal ; Otherwise , return false ; Function to rearrange characters of a string such that no pair of adjacent characters are the same ; Initialize 3 variables ; Iterate until k < N ; If S [ i ] is not equal to S [ j ] ; Increment i and j by 1 ; If j equals k and increment the value of K by 1 ; Else ; If S [ j ] equals S [ k ] ; Increment k by 1 ; Else ; Swap ; Increment i and j by 1 ; If j equals k ; Increment k by 1 ; Function to rearrange characters in a string so that no two adjacent characters are same ; If string is already valid ; If size of the string is 2 ; Function Call ; Reversing the string ; Function Call ; If the string is valid ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isAdjChar ( string & s ) { for ( int i = 0 ; i < s . size ( ) - 1 ; i ++ ) { if ( s [ i ] == s [ i + 1 ] ) return true ; } return false ; } void rearrangeStringUtil ( string & S , int N ) { int i = 0 , j = 1 , k = 2 ; while ( k < N ) { if ( S [ i ] != S [ j ] ) { i ++ ; j ++ ; if ( j == k ) { k ++ ; } } else { if ( S [ j ] == S [ k ] ) { k ++ ; } else { swap ( S [ k ] , S [ j ] ) ; i ++ ; j ++ ; if ( j == k ) { k ++ ; } } } } } string rearrangeString ( string & S , int N ) { if ( isAdjChar ( S ) == false ) { return S ; } if ( S . size ( ) == 2 ) return " - 1" ; rearrangeStringUtil ( S , N ) ; reverse ( S . begin ( ) , S . end ( ) ) ; rearrangeStringUtil ( S , N ) ; if ( isAdjChar ( S ) == false ) { return S ; } return " - 1" ; } int main ( ) { string S = " aaabc " ; int N = S . length ( ) ; cout << rearrangeString ( S , N ) ; return 0 ; }
Lexicographically largest string possible by repeatedly appending first character of two given strings | C ++ program for the above approach ; Function to make the lexicographically largest string by merging two strings ; Stores the resultant string ; If the string word1 is lexographically greater than or equal to word2 ; Update the string merge ; Erase the first index of the string word1 ; Otherwise ; Update the string merge ; Erase the first index of the string word2 ; Return the final string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string largestMerge ( string word1 , string word2 ) { string merge = " " ; while ( word1 . size ( ) != 0 || word2 . size ( ) != 0 ) { if ( word1 >= word2 ) { merge = merge + word1 [ 0 ] ; word1 . erase ( word1 . begin ( ) + 0 ) ; } else { merge = merge + word2 [ 0 ] ; word2 . erase ( word2 . begin ( ) + 0 ) ; } } return merge ; } int main ( ) { string S1 = " xyzxyz " ; string S2 = " xywzxyx " ; cout << largestMerge ( S1 , S2 ) ; return 0 ; }
Maximum rods to put horizontally such that no two rods overlap on X coordinate | C ++ program for the above approach ; Function to find the maximum number of rods that can be put horizontally ; Stores the result ; Stores the last occupied point ; Traverse the array arr [ ] ; If the current point can be put on the left side ; Increment the ans by 1 ; Update prev ; Else if the given point can be put on the right side ; Increment the ans by 1 ; Update prev ; Otherwise , ; Update prev ; Return the ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaximumPoints ( int N , int X [ ] , int H [ ] ) { int ans = 0 ; int prev = INT_MIN ; for ( int i = 0 ; i < N ; ++ i ) { if ( prev < ( X [ i ] - H [ i ] ) ) { ++ ans ; prev = X [ i ] ; } else if ( i == N - 1 || ( X [ i ] + H [ i ] ) < X [ i + 1 ] ) { ++ ans ; prev = X [ i ] + H [ i ] ; } else { prev = X [ i ] ; } } return ans ; } int main ( ) { int X [ ] = { 1 , 2 , 3 } ; int H [ ] = { 2 , 5 , 5 } ; int N = sizeof ( X ) / sizeof ( X [ 0 ] ) ; cout << findMaximumPoints ( N , X , H ) ; }
Maximize the missing values in given time in HH : MM format | C ++ program for the above approach ; Function to find the maximum time by replacing ' ? ' by any digits ; If the 0 th index is ' ? ' ; If the 1 st index is ' ? ' ; If the 3 rd index is ' ? ' ; If the 4 th index is ' ? ' ; Return new string ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void maxTime ( string s ) { if ( s [ 0 ] == ' ? ' ) { if ( s [ 1 ] <= '3' s [ 1 ] == ' ? ' ) s [ 0 ] = '2' ; else s [ 0 ] = '1' ; } if ( s [ 1 ] == ' ? ' ) { if ( s [ 0 ] != '2' ) { s [ 1 ] = 9 ; } else s [ 1 ] = 3 ; } if ( s [ 3 ] == ' ? ' ) s [ 3 ] = '5' ; if ( s [ 4 ] == ' ? ' ) s [ 4 ] = '9' ; cout << s << endl ; } int main ( ) { string S = " ? 4:5 ? " ; maxTime ( S ) ; return 0 ; }
Maximum GCD of two numbers possible by adding same value to them | C ++ implementation of above approach . ; Function to calculate maximum gcd of two numbers possible by adding same value to both a and b ; Driver Code ; Given Input
#include <iostream> NEW_LINE using namespace std ; void maxGcd ( int a , int b ) { cout << abs ( a - b ) ; } int main ( ) { int a = 2231 ; int b = 343 ; maxGcd ( a , b ) ; return 0 ; }
Count the combination of 4 s and / or 5 s required to make each Array element 0 | C ++ program for the above approach ; Function to print the count of the combination of 4 or 5 required to make the arr [ i ] for each 0 < i < N ; Vector to store the answer ; Iterate in the range [ 0 , N - 1 ] ; Initialize sum to store the count of numbers and cnt for the current factor of 4 ; Iterate in the range [ 0 , arr [ i ] ] with increment of 4 ; Check if arr [ i ] - j ( the current factor of 4 ) is divisible by 5 or not ; If sum is not maximum then answer is found ; Finally , print the required answer ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sumOfCombinationOf4OR5 ( vector < int > arr , int N ) { vector < int > ans ( N , -1 ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 4 ) { continue ; } int sum = INT_MAX , cnt = 0 ; for ( int j = 0 ; j <= arr [ i ] ; j += 4 ) { if ( ( arr [ i ] - j ) % 5 == 0 ) { sum = min ( sum , cnt + ( arr [ i ] - j ) / 5 ) ; } cnt ++ ; } if ( sum != INT_MAX ) ans [ i ] = sum ; } for ( auto num : ans ) cout << num << " ▁ " ; } int main ( ) { vector < int > arr = { 7 , 15 , 17 , 22 } ; int N = arr . size ( ) ; sumOfCombinationOf4OR5 ( arr , N ) ; return 0 ; }
Find an N | C ++ program for the above approach ; Function to find an N - length binary string having maximum sum of elements from all given ranges ; Iterate over the range [ 1 , N ] ; If i is odd , then print 0 ; Otherwise , print 1 ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printBinaryString ( int arr [ ] [ 3 ] , int N ) { for ( int i = 1 ; i <= N ; i ++ ) { if ( i % 2 ) { cout << 0 ; } else { cout << 1 ; } } } int main ( ) { int N = 5 , M = 3 ; int arr [ ] [ 3 ] = { { 1 , 3 } , { 2 , 4 } , { 2 , 5 } } ; printBinaryString ( arr , N ) ; return 0 ; }
Maximize 0 s in given Array after replacing each element A [ i ] with ( A [ i ] * D + B [ i ] ) | C ++ program for the above approach ; Function to find the maximum number of 0 s in the array A [ ] after changing the array element to A [ i ] * D + B [ i ] ; Stores the frequency of fractions needed to make each element 0 ; Stores the maximum number of 0 ; Traverse the array ; Find the numerator and the denominator ; Check if den is not equal to 0 ; Divide num and den by their gcd ; Check if num is not greater than 0 ; Check if both num and den are equal to 0 ; Increment the value of { num , den } in the map ; Update the value of ans ; Print the value of ans + cnt ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxZeroes ( vector < int > & A , vector < int > & B ) { map < pair < int , int > , int > mp ; int N = A . size ( ) ; int ans = 0 ; int cnt = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int num = - B [ i ] ; int den = A [ i ] ; int gc = __gcd ( num , den ) ; if ( den != 0 ) { num /= gc ; den /= gc ; } if ( num <= 0 ) { num *= -1 ; den *= -1 ; } if ( den == 0 and num == 0 ) cnt ++ ; if ( den != 0 ) { mp [ { num , den } ] ++ ; ans = max ( mp [ { num , den } ] , ans ) ; } } cout << ans + cnt << endl ; } int main ( ) { vector < int > A = { 1 , 2 , -1 } ; vector < int > B = { -6 , -12 , 6 } ; maxZeroes ( A , B ) ; return 0 ; }
Minimum cost to complete given tasks if cost of 1 , 7 and 30 days are given | C ++ program for the above approach ; Function to find the minimum cost to hire the workers for the given days in the array days [ ] ; Initialize the array dp ; Minimum Cost for Nth day ; Pointer of the array arr [ ] ; Traverse from right to left ; If worker is hired for 1 day ; If worker is hired for 7 days ; If worker is hired for 30 days ; Update the value of dp [ i ] as minimum of 3 options ; If the day is not at the array arr [ ] ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinCost ( int days [ ] , int cost [ ] , int N ) { int size = days [ N - 1 ] + 1 ; int dp [ size ] ; dp [ size - 1 ] = min ( cost [ 0 ] , min ( cost [ 1 ] , cost [ 2 ] ) ) ; int ptr = N - 2 ; for ( int i = size - 2 ; i > 0 ; i -- ) { if ( ptr >= 0 && days [ ptr ] == i ) { int val1 = dp [ i + 1 ] + cost [ 0 ] ; int val2 = cost [ 1 ] + ( ( i + 7 >= size ) ? 0 : dp [ i + 7 ] ) ; int val3 = cost [ 2 ] + ( ( i + 30 >= size ) ? 0 : dp [ i + 30 ] ) ; dp [ i ] = min ( val1 , min ( val2 , val3 ) ) ; ptr -- ; } else { dp [ i ] = dp [ i + 1 ] ; } } return dp [ 1 ] ; } int main ( ) { int arr [ ] = { 2 , 4 , 6 , 7 , 8 , 10 , 17 } ; int cost [ ] = { 3 , 8 , 20 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << MinCost ( arr , cost , N ) ; return 0 ; }
Minimum count of elements to be inserted in Array to form all values in [ 1 , K ] using subset sum | C ++ program for the above approach ; Function to find the count of minimum elements to be inserted to form every number in a range ; Stores the count of numbers needed ; Stores the numbers upto which every numbers can be formed ; Stores the index of the array arr [ ] ; Iterate until requiredSum is less than or equal to K ; If i is less than N and requiredSum is greater than or equal to arr [ i ] ; Increment requiredSum by arr [ i ] ; Increment i by 1 ; Otherwise ; Increment count by 1 ; Increment requiredSum by requiredSum ; Return result ; Driver Code ; Input ; Function Call
#include <iostream> NEW_LINE using namespace std ; int minElements ( int arr [ ] , int N , int K ) { int count = 0 ; long long requiredNum = 1 ; int i = 0 ; while ( requiredNum <= K ) { if ( i < N && requiredNum >= arr [ i ] ) { requiredNum += arr [ i ] ; i ++ ; } else { count ++ ; requiredNum += requiredNum ; } } return count ; } int main ( ) { int arr [ ] = { 1 , 3 } ; int K = 6 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minElements ( arr , N , K ) << endl ; return 0 ; }
Theft at World Bank | C ++ program for the above approach ; Custom comparator ; Function to find the maximum profit ; Stores the pairs of elements of B and A at the same index ; Iterate over the range [ 0 , N ] ; If current integer is perfect square ; Push the pair of B [ i ] and A [ i ] in vector V ; Sorts the vector using the custom comparator ; Stores the maximum profit ; Traverse the vector V ; If V [ i ] . second is less than W ; Increment profit by V [ i ] . first ; Decrement V [ i ] . second from W ; Otherwise ; Update profit ; Return the value of profit ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool comp ( pair < long long , long long > p1 , pair < long long , long long > p2 ) { long double a = p1 . first , b = p1 . second ; long double c = p2 . first , d = p2 . second ; long double val1 = 0 , val2 = 0 ; val1 = a / b ; val2 = c / d ; return val1 > val2 ; } long double maximumProfit ( int A [ ] , int B [ ] , int N , long long W ) { vector < pair < long long , long long > > V ; for ( int i = 0 ; i < N ; i ++ ) { long long temp = sqrt ( A [ i ] ) ; if ( temp * temp == A [ i ] ) continue ; V . push_back ( { B [ i ] , A [ i ] } ) ; } sort ( V . begin ( ) , V . end ( ) , comp ) ; long double profit = 0.00 ; for ( int i = 0 ; i < V . size ( ) ; i ++ ) { if ( V [ i ] . second <= W ) { profit += V [ i ] . first ; W -= V [ i ] . second ; } else { profit += V [ i ] . first * ( ( long double ) W / V [ i ] . second ) ; break ; } } return profit ; } int main ( ) { int N = 3 ; long long W = 10 ; int A [ ] = { 4 , 5 , 7 } ; int B [ ] = { 8 , 5 , 4 } ; cout << maximumProfit ( A , B , N , W ) << endl ; return 0 ; }
Maximize the count of adjacent element pairs with even sum by rearranging the Array | C ++ program for the above approach ; Function to find maximum count pair of adjacent elements with even sum ; Stores count of odd numbers ; Stores count of even numbers ; Traverse the array arr [ ] ; If arr [ i ] % 2 is 1 ; Else ; If odd and even both are greater than 0 ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumCount ( int arr [ ] , int N ) { int odd = 0 ; int even = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 ) odd ++ ; else even ++ ; } if ( odd and even ) return N - 2 ; else return N - 1 ; } int main ( ) { int arr [ ] = { 9 , 13 , 15 , 3 , 16 , 9 , 13 , 18 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumCount ( arr , N ) ; return 0 ; }
Smallest number possible by repeatedly multiplying with K or 2 exactly N times starting from 1 | C ++ program for the above approach ; Function to find the minimum value of X after increment X by K or twice value of X in each of N operations ; Iterate over the range [ 1 , N ] ; If the value of X is less than equal to K ; Otherwise ; Return the minimum value of X ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minPossibleValue ( int N , int K , int X ) { for ( int i = 1 ; i <= N ; i ++ ) { if ( X <= K ) { X = X * 2 ; } else { X = X + K ; } } return X ; } int main ( ) { int N = 7 , K = 4 , X = 1 ; cout << minPossibleValue ( N , K , X ) ; return 0 ; }
Smallest number that can replace all | C ++ program for the above approach ; Function to find the value of K to minimize the value of maximum absolute difference between adjacent elements ; Stores the maximum and minimum among array elements that are adjacent to " - 1" ; Traverse the given array arr [ ] ; If arr [ i ] is - 1 & arr [ i + 1 ] is not - 1 ; If arr [ i + 1 ] is - 1 & arr [ i ] is not - 1 ; If all array element is - 1 ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMissingValue ( int arr [ ] , int N ) { int minE = INT_MAX , maxE = INT_MIN ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] == -1 && arr [ i + 1 ] != -1 ) { minE = min ( minE , arr [ i + 1 ] ) ; maxE = max ( maxE , arr [ i + 1 ] ) ; } if ( arr [ i ] != -1 && arr [ i + 1 ] == -1 ) { minE = min ( minE , arr [ i ] ) ; maxE = max ( maxE , arr [ i ] ) ; } } if ( minE == INT_MAX and maxE == INT_MIN ) { cout << "0" ; } else { cout << ( minE + maxE ) / 2 ; } } int main ( ) { int arr [ ] = { 1 , -1 , -1 , -1 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMissingValue ( arr , N ) ; return 0 ; }
Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times | C ++ program for the above approach ; Function to find the last element after performing given operations ; Length of the array ; Increment j until condition is satisfied ; In each pair every value is repeating r number of times ; Print the result according to the value of k ; Driver Code ; Given K ; Given arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findLastElement ( int N , vector < int > A ) { int l = A . size ( ) ; int j = 0 ; while ( N > l * ( pow ( 2 , j ) ) ) { N = N - l * pow ( 2 , j ) ; j += 1 ; } int k = 1 ; int r = pow ( 2 , j ) ; for ( int i = 1 ; i < l ; i ++ ) { if ( N > r * i ) k += 1 ; } for ( int i = 0 ; i < l ; i ++ ) { if ( i + 1 == k ) { cout << ( A [ i ] ) ; return ; } } } int main ( ) { int K = 7 ; vector < int > A = { 1 , 2 , 3 } ; findLastElement ( K , A ) ; return 0 ; }
Minimum possible value of D which when added to or subtracted from K repeatedly obtains every array element | C ++ program for the above approach ; Recursive function tox previous gcd of a and b ; Function to find the maximum value of D such that every element in the array can be obtained by performing K + D or K - D ; Traverse the array arr [ ] ; Update arr [ i ] ; Stores GCD of the array ; Iterate over the range [ 1 , N ] ; Update the value of D ; Print the value of D ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int findMaxD ( int arr [ ] , int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = abs ( arr [ i ] - K ) ; } int D = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { D = gcd ( D , arr [ i ] ) ; } return D ; } int main ( ) { int arr [ ] = { 1 , 7 , 11 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << findMaxD ( arr , N , K ) ; return 0 ; }
Maximize the number of times a character can be removed from substring 01 from given Binary String | C ++ program for the above approach ; Function to find the maximum moves that can be performed on a string ; Stores 0 s in suffix ; Stores 1 s in prefix ; Iterate over the characters of the string ; Iterate until i is greater than or equal to 0 ; If N is equal to x + y ; Return answer ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxOperations ( string S , int N ) { int X = 0 ; int Y = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '0' ) break ; Y ++ ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( S [ i ] == '1' ) break ; X ++ ; } if ( N == X + Y ) return 0 ; return N - ( X + Y ) - 1 ; } int main ( ) { string S = "001111" ; int N = S . length ( ) ; cout << maxOperations ( S , N ) << endl ; return 0 ; }
Maximize frequency sum of K chosen characters from given string | C ++ program for the above approach ; Function to find the maximum sum of frequencies of the exactly K chosen characters from the string S ; Stores the resultant maximum sum ; Stores the frequency of array elements ; Find the frequency of character ; Sort the frequency array in the descending order ; Iterate to choose K elements greedily ; If the freq [ i ] cards are chosen ; K cards have been picked ; Return the resultant sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( string S , int N , int K ) { int sum = 0 ; int freq [ 256 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { freq [ int ( S [ i ] ) ] ++ ; } sort ( freq , freq + 256 , greater < int > ( ) ) ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( K > freq [ i ] ) { sum += freq [ i ] * freq [ i ] ; K -= freq [ i ] ; } else { sum += freq [ i ] * K ; break ; } } return sum ; } int main ( ) { string S = " GEEKSFORGEEKS " ; int K = 10 ; int N = S . length ( ) ; cout << maximumSum ( S , N , K ) ; return 0 ; }
Count of N | C ++ program for the above approach ; Function to count N - digit numbers having absolute difference between adjacent digits in non - increasing order ; If digit = n + 1 , a valid n - digit number has been formed ; If the state has already been computed ; If the current digit is 1 , then any digit from [ 1 - 9 ] can be placed ; If the current digit is 2 , any digit from [ 0 - 9 ] can be placed ; For other digits , any digit i can be placed which satisfies abs ( prev1 - i ) <= abs ( prev1 - prev2 ) ; If absolute difference is less than or equal to diff ; Function to count N - digit numbers with absolute difference between adjacent digits in non increasing order ; Initialize dp table with - 1 ; Function Call ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 100 ] [ 10 ] [ 10 ] ; int countOfNumbers ( int digit , int prev1 , int prev2 , int n ) { if ( digit == n + 1 ) { return 1 ; } int & val = dp [ digit ] [ prev1 ] [ prev2 ] ; if ( val != -1 ) { return val ; } val = 0 ; if ( digit == 1 ) { for ( int i = ( n == 1 ? 0 : 1 ) ; i <= 9 ; ++ i ) { val += countOfNumbers ( digit + 1 , i , prev1 , n ) ; } } else if ( digit == 2 ) { for ( int i = 0 ; i <= 9 ; ++ i ) { val += countOfNumbers ( digit + 1 , i , prev1 , n ) ; } } else { int diff = abs ( prev2 - prev1 ) ; for ( int i = 0 ; i <= 9 ; ++ i ) { if ( abs ( prev1 - i ) <= diff ) { val += countOfNumbers ( digit + 1 , i , prev1 , n ) ; } } } return val ; } int countNumbersUtil ( int N ) { memset ( dp , -1 , sizeof dp ) ; cout << countOfNumbers ( 1 , 0 , 0 , N ) ; } int main ( ) { int N = 3 ; countNumbersUtil ( N ) ; return 0 ; }
Print all numbers that can be obtained by adding A or B to N exactly M times | C ++ program for the above approach ; Function to find all possible numbers that can be obtained by adding A or B to N exactly N times ; If number of steps is 0 and only possible number is N ; Add A to N and make a recursive call for M - 1 steps ; Add B to N and make a recursive call for M - 1 steps . ; Driver Code ; Given Inputs ; Stores all possible numbers ; Function call ; Print all possible numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; void possibleNumbers ( set < int > & numbers , int N , int M , int A , int B ) { if ( M == 0 ) { numbers . insert ( N ) ; return ; } possibleNumbers ( numbers , N + A , M - 1 , A , B ) ; possibleNumbers ( numbers , N + B , M - 1 , A , B ) ; } int main ( ) { int N = 5 , M = 3 , A = 4 , B = 6 ; set < int > numbers ; possibleNumbers ( numbers , N , M , A , B ) ; for ( int x : numbers ) { cout << x << " ▁ " ; } return 0 ; }
Maximum sum of array after removing a positive or negative subarray | C ++ program for the above approach ; Function to find the maximum sum of array after removing either the contiguous positive or negative elements ; Store the total sum of array ; Store the maximum contiguous negative sum ; Store the sum of current contiguous negative elements ; Store the minimum element of array ; Traverse the array , arr [ ] ; Update the overall sum ; Store minimum element of array ; If arr [ i ] is positive ; Update temp_sum to 0 ; Add arr [ i ] to temp_sum ; Update max_neg ; If no negative element in array then remove smallest positive element ; Print the required sum ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSum ( int arr [ ] , int n ) { int sum = 0 ; int max_neg = INT_MAX ; int tempsum = 0 ; int small = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; small = min ( small , arr [ i ] ) ; if ( arr [ i ] > 0 ) { tempsum = 0 ; } else { tempsum += arr [ i ] ; } max_neg = min ( max_neg , tempsum ) ; } if ( max_neg == 0 ) { max_neg = small ; } cout << sum - max_neg ; } int main ( ) { int arr [ ] = { -2 , -3 , 4 , -1 , -2 , 1 , 5 , -3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxSum ( arr , n ) ; return 0 ; }
Lexicographically largest string possible by at most K replacements | C ++ implementation of the above approach ; Traverse each element of the string ; If the current character can be replaced with ' z ' ; Return the modified string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string largestString ( string s , int k ) { for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] != ' z ' && k > 0 ) { s [ i ] = ' z ' ; k -- ; } } return s ; } int main ( ) { string s = " dbza " ; int k = 1 ; cout << largestString ( s , k ) << endl ; return 0 ; }
Count characters of a string which when removed individually makes the string equal to another string | C ++ program for the above approach ; Function to count characters from string A whose removal makes the strings A and B equal ; Stores the index of the longest prefix ; Stores the index of the longest suffix ; Traverse the string B ; Traverse the string B ; If N - M is equal to 1 and Y is less than or equal to X ; Print the count of characters ; Print the positions of the characters ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void RemoveOneChar ( string A , string B , int N , int M ) { int X = 0 ; int Y = N - 1 ; for ( int i = 0 ; i < M ; i ++ ) { if ( A [ X ] != B [ i ] ) break ; X ++ ; } for ( int i = M - 1 ; i >= 0 ; i -- ) { if ( A [ Y ] != B [ i ] ) break ; Y -- ; } if ( N - M == 1 && Y < X ) { cout << X - Y + 1 << endl ; for ( int i = Y ; i <= X ; i ++ ) cout << i + 1 << " ▁ " ; cout << endl ; } else cout << -1 << endl ; } int main ( ) { string A = " abaac " ; string B = " abac " ; int N = A . length ( ) ; int M = B . length ( ) ; RemoveOneChar ( A , B , N , M ) ; }
Minimum flips or swapping of adjacent characters required to make a string equal to another | C ++ program for the above approach ; Function to find minimum operations required to convert string A to B ; Store the size of the string ; Store the required result ; Traverse the string , a ; If a [ i ] is equal to b [ i ] ; Check if swapping adjacent characters make the same - indexed characters equal or not ; Otherwise , flip the current bit ; Print the minimum number of operations ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumOperation ( string a , string b ) { int n = a . length ( ) ; int i = 0 ; int minoperation = 0 ; while ( i < n ) { if ( a [ i ] == b [ i ] ) { i = i + 1 ; continue ; } else if ( a [ i ] == b [ i + 1 ] && a [ i + 1 ] == b [ i ] && i < n - 1 ) { minoperation ++ ; i = i + 2 ; } else if ( a [ i ] != b [ i ] ) { minoperation ++ ; i = i + 1 ; } else { ++ i ; } } cout << minoperation ; } int main ( ) { string a = "10010010" , b = "00001000" ; minimumOperation ( a , b ) ; return 0 ; }
Minimum replacements required to make sum of all K | C ++ program for the above approach ; Function to find minimum number of operations required to make sum of all subarrays of size K equal ; Stores number of operations ; Iterate in the range [ 0 , K - 1 ] ; Stores frequency of elements separated by distance K ; Stores maximum frequency and corresponding element ; Find max frequency element and its frequency ; Update the number of operations ; Print the result ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinOperations ( int arr [ ] , int N , int K ) { int operations = 0 ; for ( int i = 0 ; i < K ; i ++ ) { unordered_map < int , int > freq ; for ( int j = i ; j < N ; j += K ) freq [ arr [ j ] ] ++ ; int max1 = 0 , num ; for ( auto x : freq ) { if ( x . second > max1 ) { max1 = x . second ; num = x . first ; } } for ( auto x : freq ) { if ( x . first != num ) operations += x . second ; } } cout << operations ; } int main ( ) { int arr [ ] = { 3 , 4 , 3 , 5 , 6 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMinOperations ( arr , N , K ) ; return 0 ; }
Count of pairs of integers up to X and Y that generates equal Quotient and Remainder | C ++ Program for the above approach ; Function to calculate the number of pairs satisfying ( m / n = m % n ) ; Iterate from 1 to sqrt ( x ) ; Combining the conditions - 1 ) n > k 2 ) n <= y 3 ) n <= ( x / k - 1 ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countOfPairs ( int x , int y ) { int count = 0 ; for ( int k = 1 ; k * k <= x ; ++ k ) { count += max ( 0 , min ( y , x / k - 1 ) - k ) ; } cout << count << " STRNEWLINE " ; } int main ( ) { int x = 4 ; int y = 5 ; countOfPairs ( x , y ) ; return 0 ; }
Count permutations of first N natural numbers having sum of adjacent elements equal to a perfect square | C ++ program for the above approach ; Function to count total number of permutation of the first N natural number having the sum of adjacent elements as perfect square ; Create an adjacency matrix ; Count elements whose indegree is 1 ; Generate adjacency matrix ; Find the sum of i and j ; If sum is perfect square . then move from i to j ; Add it in adjacency list of i ; If any list is of size 1 , then the indegree is 1 ; If there is no element whose indegree is 1 , then N such permutations are possible ; If there is 1 or 2 elements whose indegree is 1 , then 2 permutations are possible ; If there are more than 2 elements whose indegree is 1 , then return 0 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPermutations ( int N ) { vector < vector < int > > adj ( 105 ) ; int indeg = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ ) { if ( i == j ) continue ; int sum = i + j ; if ( ceil ( sqrt ( sum ) ) == floor ( sqrt ( sum ) ) ) { adj [ i ] . push_back ( j ) ; } } if ( adj [ i ] . size ( ) == 1 ) indeg ++ ; } if ( indeg == 0 ) return N ; else if ( indeg <= 2 ) return 2 ; else return 0 ; } int main ( ) { int N = 17 ; cout << countPermutations ( N ) ; return 0 ; }
Generate a permutation of first N natural numbers having count of unique adjacent differences equal to K | C ++ program for the above approach ; Function to construct the list with exactly K unique adjacent element differences ; Stores the resultant array ; Stores the left and the right most element of the range ; Traverse the array ; If k is even , the add left to array and increment the left ; If k is odd , the add right to array and decrement the right ; Repeat the steps for k - 1 times ; Print the resultant list ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void makeList ( int N , int K ) { int list [ N ] ; int left = 1 ; int right = N ; for ( int i = 0 ; i < N ; i ++ ) { if ( K % 2 == 0 ) { list [ i ] = left ; left = left + 1 ; } else { list [ i ] = right ; right = right - 1 ; } if ( K > 1 ) K -- ; } for ( int i = 0 ; i < N ; i ++ ) { cout << list [ i ] << " ▁ " ; } } int main ( ) { int N = 6 ; int K = 3 ; makeList ( N , K ) ; }
Find the date after next half year from a given date | C ++ program for the above approach ; Function to find the date after the next half - year ; Stores the number of days in the months of a leap year ; List of months ; Days in half of a year ; Index of current month ; Starting day ; Decrement the value of cnt by 1 ; Increment cur_date ; If cnt is equal to 0 , then break out of the loop ; Update cur_month ; Update cur_date ; Print the resultant date ; Driver Code ; Function Call
#include <iostream> NEW_LINE using namespace std ; void getDate ( int d , string m ) { int days [ ] = { 31 , 29 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 } ; string month [ ] = { " January " , " February " , " March " , " April " , " May " , " June " , " July " , " August " , " September " , " October " , " November " , " December " } ; int cnt = 183 ; int cur_month ; for ( int i = 0 ; i < 12 ; i ++ ) if ( m == month [ i ] ) cur_month = i ; int cur_date = d ; while ( 1 ) { while ( cnt > 0 && cur_date <= days [ cur_month ] ) { cnt -= 1 ; cur_date += 1 ; } if ( cnt == 0 ) break ; cur_month = ( cur_month + 1 ) % 12 ; cur_date = 1 ; } cout << cur_date << " ▁ " << month [ cur_month ] << endl ; } int main ( ) { int D = 15 ; string M = " January " ; getDate ( D , M ) ; return 0 ; }
Maximum number made up of distinct digits whose sum is equal to N | C ++ program for the above approach ; Function to find the largest positive number made up of distinct digits having the sum of its digits as N ; If given number is greater than 45 , print - 1 ; Store the required number and the digit to be considered ; Loop until N > 0 and digit > 0 ; If the current digit is at most N then , add it to number num ; Update the value of num ; Decrement N by digit ; Consider the next lower digit ; Add 0 at the end and return the number num ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long largestNumber ( int N ) { if ( N > 45 ) return -1 ; int num = 0 , digit = 9 ; while ( N > 0 && digit > 0 ) { if ( digit <= N ) { num *= 10 ; num += digit ; N -= digit ; } digit -= 1 ; } return num * 10 ; } int main ( ) { int N = 25 ; cout << largestNumber ( N ) ; return 0 ; }
Minimum number that can be obtained by applying ' + ' and ' * ' operations on array elements | C ++ program for the above approach ; Function to find the smallest number that can be obtained after applying the arithmetic operations mentioned in the string S ; Stores the count of multiplication operator in the string ; Store the required result ; Iterate in the range to create the mask ; Checking the number of bits that are set in the mask ; Check if the number of bits that are set in the mask is multiplication operation ; Storing the elements that is to be added ; Apply the multiplications operation first ; If sign is ' * ' , then multiply last element of deque with arr [ i ] ; Push last multiplied element in the deque ; If the element is to be added , then add it to the deque ; Add all the element of the deque ; Minimize the answer with the given sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumSum ( int A [ ] , int N , string S ) { int mul = 0 ; for ( int i = 0 ; i < ( int ) S . size ( ) ; i ++ ) { if ( S [ i ] == ' * ' ) mul += 1 ; } int ans = 1000000 ; for ( int i = 0 ; i < ( 1 << ( N - 1 ) ) ; i ++ ) { int cnt = 0 ; vector < char > v ; for ( int j = 0 ; j < N - 1 ; j ++ ) { if ( ( 1 << j ) & ( i ) ) { cnt += 1 ; v . push_back ( ' * ' ) ; } else { v . push_back ( ' + ' ) ; } } if ( cnt == mul ) { deque < int > d ; d . push_back ( A [ 0 ] ) ; for ( int j = 0 ; j < N - 1 ; j ++ ) { if ( v [ j ] == ' * ' ) { int x = d . back ( ) ; d . pop_back ( ) ; x = x * A [ j + 1 ] ; d . push_back ( x ) ; } else { d . push_back ( A [ j + 1 ] ) ; } } int sum = 0 ; while ( d . size ( ) > 0 ) { int x = d . front ( ) ; sum += x ; d . pop_front ( ) ; } ans = min ( ans , sum ) ; } } return ans ; } int main ( ) { int A [ ] = { 2 , 2 , 2 , 2 } ; string S = " * * + " ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minimumSum ( A , N , S ) ; return 0 ; }
Minimum sum of medians of all possible K length subsequences of a sorted array | C ++ program for the above approach ; Function to find the minimum sum of all the medians of the K sized sorted arrays formed from the given array ; Stores the distance between the medians ; Stores the number of subsequences required ; Stores the resultant sum ; Iterate from start and add all the medians ; Add the value of arr [ i ] to the variable minsum ; Increment i by select the median to get the next median index ; Decrement the value of totalArrays by 1 ; Print the resultant minimum sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sumOfMedians ( int arr [ ] , int N , int K ) { int selectMedian = ( K + 1 ) / 2 ; int totalArrays = N / K ; int minSum = 0 ; int i = selectMedian - 1 ; while ( i < N and totalArrays != 0 ) { minSum = minSum + arr [ i ] ; i = i + selectMedian ; totalArrays -- ; } cout << minSum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int K = 2 ; sumOfMedians ( arr , N , K ) ; return 0 ; }
Find K positive integers not exceeding N and having sum S | C ++ implementation for the above approach ; Function to represent S as the sum of K positive integers less than or equal to N ; If S can cannot be represented as sum of K integers ; If sum of first i natural numbers exceeds S ; Insert i into nums [ ] ; Insert first K - 1 positive numbers into answer [ ] ; Insert the K - th number ; Traverse the array answer [ ] ; If current element exceeds N ; Add the extra value to the previous element ; Reduce current element to N ; Printing the K numbers ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int S , int K , int N ) { if ( K > N ) { cout << " - 1" << endl ; return ; } int max_sum = 0 , min_sum = 0 ; for ( int i = 1 ; i <= K ; i ++ ) { min_sum += i ; max_sum += N - i + 1 ; } if ( S < min_sum S > max_sum ) { cout << " - 1" << endl ; return ; } int s1 = 0 ; vector < int > nums ; for ( int i = 1 ; i <= N ; i ++ ) { if ( s1 > S ) break ; s1 += i ; nums . push_back ( i ) ; } vector < int > answer ; int s2 = 0 ; for ( int i = 0 ; i < K - 1 ; i ++ ) { answer . push_back ( nums [ i ] ) ; s2 += nums [ i ] ; } answer . push_back ( S - s2 ) ; int Max = N ; for ( int i = answer . size ( ) - 1 ; i >= 0 ; i -- ) { if ( answer [ i ] > Max ) { int extra = answer [ i ] - Max ; if ( i - 1 >= 0 ) answer [ i - 1 ] += extra ; answer [ i ] = Max ; Max -- ; } else break ; } for ( auto x : answer ) cout << x << " ▁ " ; cout << endl ; } int main ( ) { int S = 15 , K = 4 , N = 8 ; solve ( S , K , N ) ; return 0 ; }
Generate an N | C ++ program for the above approach ; Function to minimize the maximum element present in an N - length array having sum of elements divisible by K ; Return the ceil value of ( K / N ) ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumValue ( int N , int K ) { return ceil ( ( double ) K / ( double ) N ) ; } int main ( ) { int N = 4 , K = 50 ; cout << minimumValue ( N , K ) ; return 0 ; }
Minimum removal of elements from end of an array required to obtain sum K | C ++ program for the above approach ; Function to find the minimum number of elements required to be removed from the ends of an array to obtain a sum K ; Number of elements removed from the left and right ends of the array ; Sum of left and right subarrays ; No element is taken from left initially ; Start taking elements from right side ; ( left + 1 ) : Count of elements removed from the left ( N - right ) : Count of elements removed from the right ; If sum is greater than K ; If it is not possible to obtain sum K ; Driver Code ; Given Array ; Given target sum
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSizeArr ( int A [ ] , int N , int K ) { int leftTaken = N , rightTaken = N ; int leftSum = 0 , rightSum = 0 ; for ( int left = -1 ; left < N ; left ++ ) { if ( left != -1 ) leftSum += A [ left ] ; rightSum = 0 ; for ( int right = N - 1 ; right > left ; right -- ) { rightSum += A [ right ] ; if ( leftSum + rightSum == K ) { if ( leftTaken + rightTaken > ( left + 1 ) + ( N - right ) ) { leftTaken = left + 1 ; rightTaken = N - right ; } break ; } if ( leftSum + rightSum > K ) break ; } } if ( leftTaken + rightTaken <= N ) { for ( int i = 0 ; i < leftTaken ; i ++ ) cout << A [ i ] << " ▁ " ; for ( int i = 0 ; i < rightTaken ; i ++ ) cout << A [ N - i - 1 ] << " ▁ " ; } else cout << -1 ; } int main ( ) { int N = 7 ; int A [ ] = { 3 , 2 , 1 , 1 , 1 , 1 , 3 } ; int K = 10 ; minSizeArr ( A , N , K ) ; return 0 ; }
Minimum removal of elements from end of an array required to obtain sum K | C ++ program for the above approach ; Function to find the smallest array that can be removed from the ends of an array to obtain sum K ; Sum of complete array ; If given number is greater than sum of the array ; If number is equal to the sum of array ; tar is sum of middle subarray ; Find the longest subarray with sum equal to tar ; If there is no subarray with sum equal to tar ; Driver Code ; Given Array ; Given target sum
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minSizeArr ( int A [ ] , int N , int K ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += A [ i ] ; if ( K > sum ) { cout << -1 ; return ; } if ( K == sum ) { for ( int i = 0 ; i < N ; i ++ ) { cout << A [ i ] << " ▁ " ; } return ; } int tar = sum - K ; unordered_map < int , int > um ; um [ 0 ] = -1 ; int left , right ; int cur = 0 , maxi = -1 ; for ( int i = 0 ; i < N ; i ++ ) { cur += A [ i ] ; if ( um . find ( cur - tar ) != um . end ( ) && i - um [ cur - tar ] > maxi ) { maxi = i - um [ cur - tar ] ; right = i ; left = um [ cur - tar ] ; } if ( um . find ( cur ) == um . end ( ) ) um [ cur ] = i ; } if ( maxi == -1 ) cout << -1 ; else { for ( int i = 0 ; i <= left ; i ++ ) cout << A [ i ] << " ▁ " ; for ( int i = 0 ; i < right ; i ++ ) cout << A [ N - i - 1 ] << " ▁ " ; } } int main ( ) { int N = 7 ; int A [ ] = { 3 , 2 , 1 , 1 , 1 , 1 , 3 } ; int K = 10 ; minSizeArr ( A , N , K ) ; return 0 ; }
Minimum product modulo N possible for any pair from a given range | C ++ program for the above approach ; Function to return the minimum possible value of ( i * j ) % N ; Stores the minimum remainder ; Iterate from L to R ; Iterate from L to R ; Print the minimum value of remainder ; If R - L >= N ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; void minModulo ( int L , int R , int N ) { if ( R - L < N ) { int ans = INT_MAX ; for ( ll i = L ; i <= R ; i ++ ) for ( ll j = L ; j <= R ; j ++ ) if ( i != j ) ans = min ( 0ll + ans , ( i * j ) % N ) ; cout << ans ; } else { cout << 0 ; } } int main ( ) { int L = 6 , R = 10 , N = 2019 ; minModulo ( L , R , N ) ; return 0 ; }
Count numbers having GCD with N equal to the number itself | C ++ program for the above approach ; Function to count numbers whose GCD with N is the number itself ; Stores the count of factors of N ; Iterate over the range [ 1 , sqrt ( N ) ] ; If i is divisible by i ; Increment count ; Avoid counting the same factor twice ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countNumbers ( int N ) { int count = 0 ; for ( int i = 1 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { count ++ ; if ( N / i != i ) { count ++ ; } } } return count ; } int main ( ) { int N = 10 ; cout << countNumbers ( N ) ; return 0 ; }
Maximum length of all possible K equal length ropes generated by cutting N ropes | C ++ program for the above approach ; Function to find the maximum size of ropes having frequency at least K by cutting the given ropes ; Stores the left and the right boundaries ; Stores the maximum length of rope possible ; Iterate while low is less than or equal to high ; Stores the mid value of the range [ low , high ] ; Stores the count of ropes of length mid ; Traverse the array arr [ ] ; If count is at least K ; Assign mid to ans ; Update the value of low ; Otherwise , update the value of high ; Return the value of ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSize ( int a [ ] , int k , int n ) { int low = 1 ; int high = * max_element ( a , a + n ) ; int ans = -1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; int count = 0 ; for ( int c = 0 ; c < n ; c ++ ) { count += a / mid ; } if ( count >= k ) { ans = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 9 } ; int K = 6 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( maximumSize ( arr , K , n ) ) ; }
Quadratic equation whose roots are K times the roots of given equation | C ++ program for the above approach ; Function to find the quadratic equation whose roots are K times the roots of the given equation ; Print quadratic equation ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findEquation ( int A , int B , int C , int K ) { cout << A << " ▁ " << K * B << " ▁ " << K * K * C ; } int main ( ) { int A = 1 , B = 2 , C = 1 , K = 2 ; findEquation ( A , B , C , K ) ; return 0 ; }
Maximum the value of a given expression for any pair of coordinates on a 2D plane | C ++ program for the above approach ; Function to find the maximum value of the given expression possible for any pair of co - ordinates ; Stores the differences between pairs ; Stores the maximum value ; Traverse the array arr [ ] [ ] ; While pq is not empty and difference between point [ 0 ] and pq . top ( ) [ 1 ] > K ; Removes the top element ; If pq is not empty ; Update the value res ; Push pair { point [ 1 ] - point [ 0 ] , point [ 0 ] } in pq ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxValueOfEquation ( vector < vector < int > > & arr , int K ) { priority_queue < vector < int > > pq ; int res = INT_MIN ; for ( auto point : arr ) { while ( ! pq . empty ( ) && point [ 0 ] - pq . top ( ) [ 1 ] > K ) { pq . pop ( ) ; } if ( ! pq . empty ( ) ) { res = max ( res , pq . top ( ) [ 0 ] + point [ 0 ] + point [ 1 ] ) ; } pq . push ( { point [ 1 ] - point [ 0 ] , point [ 0 ] } ) ; } cout << res ; } int main ( ) { vector < vector < int > > arr = { { 1 , 3 } , { 2 , 0 } , { 5 , 10 } , { 6 , -10 } } ; int K = 1 ; findMaxValueOfEquation ( arr , K ) ; return 0 ; }
Minimum increments required to make absolute difference of all pairwise adjacent array elements even | C ++ program for the above approach ; Function to find the minimum number of increments of array elements required to make difference between all pairwise adjacent elements even ; Stores the count of odd and even elements ; Traverse the array ; Increment odd count ; Increment even count ; Return the minimum number of operations required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int arr [ ] , int n ) { int oddcount = 0 , evencount = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 1 ) oddcount ++ ; else evencount ++ ; } return min ( oddcount , evencount ) ; } int main ( ) { int arr [ ] = { 2 , 4 , 3 , 1 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperations ( arr , N ) ; return 0 ; }
Count numbers up to C that can be reduced to 0 by adding or subtracting A or B | C ++ program for the above approach ; Function to calculate GCD of the two numbers a and b ; Base Case ; Recursively find the GCD ; Function to count the numbers up to C that can be reduced to 0 by adding or subtracting A or B ; Stores GCD of A and B ; Stores the count of multiples of g in the range ( 0 , C ] ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long gcd ( long long a , long long b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } void countDistinctNumbers ( long long A , long long B , long long C ) { long long g = gcd ( A , B ) ; long long count = C / g ; cout << count ; } int main ( ) { long long A = 2 , B = 3 , C = 5 ; countDistinctNumbers ( A , B , C ) ; return 0 ; }
Find the last element after repeatedly removing every second element from either end alternately | C ++ program for the above approach ; Function to find the last element remaining in the array after performing the given operations ; Checks if traversal is from left to right or vice versa ; Store the elements currently present in the array ; Store the distance between 2 consecutive array elements ; Store the first element of the remaining array ; Iterate while elements are greater than 1 ; If left to right turn ; Update head ; Otherwise , check if the remaining elements are odd ; If true , update head ; Eleminate half of the array elements ; Double the steps after each turn ; Alter the turn ; Print the remaining element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printLastElement ( int arr [ ] , int N ) { bool leftTurn = true ; int remainElements = N ; int step = 1 ; int head = 1 ; while ( remainElements > 1 ) { if ( leftTurn ) { head = head + step ; } else { if ( remainElements % 2 == 1 ) head = head + step ; } remainElements = remainElements / 2 ; step = step * 2 ; leftTurn = ! leftTurn ; } cout << arr [ head - 1 ] ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printLastElement ( arr , N ) ; return 0 ; }
Distributed C candies among N boys such that difference between maximum and minimum candies received is K | C ++ program for the above approach ; Function to calculate the maximum and minimum number of candies a boy can possess ; All candies will be given to one boy ; All the candies will be given to 1 boy ; Give K candies to 1 st boy initially ; Count remaining candies ; If the last candy of remaining candies is given to the last boy , i . e Nth boy ; Increase minimum count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max_min ( int N , int C , int K ) { int maximum , minimum ; if ( N == 1 ) { maximum = minimum = C ; } else if ( K >= C ) { maximum = C ; minimum = 0 ; } else { maximum = K ; minimum = 0 ; int remain_candy = C - K ; maximum += remain_candy / N ; minimum = remain_candy / N ; if ( remain_candy % N == N - 1 ) { minimum ++ ; } } cout << " Maximum ▁ = ▁ " << maximum << endl ; cout << " Minimum ▁ = ▁ " << minimum ; return 0 ; } int main ( ) { int N = 4 ; int C = 12 ; int K = 3 ; max_min ( N , C , K ) ; return 0 ; }
Length of smallest subarray required to be removed to make remaining elements consecutive | C ++ program for the above approach ; Function to find the length of the smallest subarray to be removed to make remaining array elements consecutive ; Store the ending index of the longest prefix consecutive array ; Traverse the array to find the longest prefix consecutive sequence ; A [ 0. . . left_index ] is the prefix consecutive sequence ; Store the starting index of the longest suffix consecutive sequence ; Traverse the array to find the longest suffix consecutive sequence ; A [ right_index ... N - 1 ] is the consecutive sequence ; Store the smallest subarray required to be removed ; Check if subarray from the middle can be removed ; Update the right index s . t . A [ 0 , N - 1 ] is consecutive ; If updated_right < N , then update the minimumLength ; Print the required result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void shortestSubarray ( int * A , int N ) { int i ; int left_index ; for ( i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] + 1 != A [ i + 1 ] ) break ; } left_index = i ; int right_index ; for ( i = N - 1 ; i >= 1 ; i -- ) { if ( A [ i ] != A [ i - 1 ] + 1 ) break ; } right_index = i ; int updated_right ; int minLength = min ( N - left_index - 1 , right_index ) ; if ( A [ right_index ] <= A [ left_index ] + 1 ) { updated_right = right_index + A [ left_index ] - A [ right_index ] + 1 ; if ( updated_right < N ) minLength = min ( minLength , updated_right - left_index - 1 ) ; } cout << minLength ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 7 , 4 , 3 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; shortestSubarray ( arr , N ) ; return 0 ; }
Check if a string can be split into 3 substrings such that one of them is a substring of the other two | C ++ program for the above approach ; Function to check if string S contains any character with frequency >= 3 or not ; Stores frequency of characters ; Iterate over the string ; Update the frequency of current character ; Iterate over the hash array ; If any character has frequency >= 3 ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string freqCheck ( string S , int N ) { int hash [ 26 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { hash [ S [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < 26 ; i ++ ) { if ( hash [ i ] > 2 ) { return " Yes " ; } } return " No " ; } int main ( ) { string S = " geekseekforgeeks " ; int N = S . length ( ) ; cout << freqCheck ( S , N ) ; return 0 ; }
Minimize length of a string by removing suffixes and prefixes of same characters | C ++ program for the above approach ; Function to find the minimum length of the string after removing the same characters from the end and front of the two strings after dividing into 2 substrings ; Initialize two pointers ; Traverse the string S ; Current char on left pointer ; Shift i towards right ; Shift j towards left ; Return the minimum possible length of string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minLength ( string s ) { int i = 0 , j = s . length ( ) - 1 ; for ( ; i < j && s [ i ] == s [ j ] ; ) { char d = s [ i ] ; while ( i <= j && s [ i ] == d ) i ++ ; while ( i <= j && s [ j ] == d ) j -- ; } return j - i + 1 ; } int main ( ) { string S = " aacbcca " ; cout << minLength ( S ) ; }
Number of Binary Search Trees of height H consisting of H + 1 nodes | C ++ program for the above approach ; Function to calculate x ^ y modulo 1000000007 in O ( log y ) ; Stores the value of x ^ y ; Update x if it exceeds mod ; If x is divisible by mod ; If y is odd , then multiply x with result ; Divide y by 2 ; Update the value of x ; Return the value of x ^ y ; Function to count the number of of BSTs of height H consisting of ( H + 1 ) nodes ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1000000007 ; int power ( long long x , unsigned int y ) { int res = 1 ; x = x % mod ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % mod ; y = y >> 1 ; x = ( x * x ) % mod ; } return res ; } int CountBST ( int H ) { return power ( 2 , H ) ; } int main ( ) { int H = 2 ; cout << CountBST ( H ) ; return 0 ; }
Check if any pair of consecutive 1 s can be separated by at most M 0 s by circular rotation of a Binary String | C ++ program for the above approach ; Function to check if any pair of consecutive 1 s can be separated by at most M 0 s by circular rotation of string S ; Stores the indices of all 1 s ; Store the number of pairs separated by at least M 0 s ; Traverse the string ; Store the current index ; Traverse the array containing indices ; If the number of 0 s > M , then increment cnt by 1 ; Increment cnt ; Check if at least M '0' s lie between the first and last occurrence of '1' ; Increment cnt ; If the value of cnt <= 1 , then rotation of string is possible ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rotateString ( int n , int m , string s ) { vector < int > v ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) { v . push_back ( i ) ; } } for ( int i = 1 ; i < ( int ) v . size ( ) ; i ++ ) { if ( ( v [ i ] - v [ i - 1 ] - 1 ) > m ) { cnt ++ ; } } if ( v . size ( ) >= 2 && ( n - ( v . back ( ) - v [ 0 ] ) - 1 ) > m ) { cnt ++ ; } if ( cnt <= 1 ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { string S = "101001" ; int M = 1 ; int N = S . size ( ) ; rotateString ( N , M , S ) ; return 0 ; }
Number obtained by reducing sum of digits of 2 N into a single digit | C ++ program for the above approach ; Function to find the number obtained by reducing sum of digits of 2 ^ N into a single digit ; Stores answers for different values of N ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumber ( int N ) { int ans [ 6 ] = { 1 , 2 , 4 , 8 , 7 , 5 } ; return ans [ N % 6 ] ; } int main ( ) { int N = 6 ; cout << findNumber ( N ) << endl ; return 0 ; }
Check if two piles of coins can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other | C ++ program for the above approach ; Function to check if two given piles can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other ; If maximum of A & B exceeds the twice of minimum of A & B ; Not possible to empty the piles ; If sum of both the coins is divisible by 3 , then print Yes ; Otherwise , print " No " ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void canBeEmptied ( int A , int B ) { if ( max ( A , B ) > 2 * min ( A , B ) ) { cout << " No " ; return ; } if ( ( A + B ) % 3 == 0 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int A = 1 , B = 2 ; canBeEmptied ( A , B ) ; return 0 ; }