text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Check whether the product of every subsequence is a perfect square or not | C ++ program for the above approach ; Function to check if the product of every subsequence of the array is a perfect square or not ; Traverse the given array ; If arr [ i ] is a perfect square or not ; Return " Yes " ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string perfectSquare ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int p = sqrt ( arr [ i ] ) ; if ( p * p != arr [ i ] ) { return " No " ; } } return " Yes " ; } int main ( ) { int arr [ ] = { 1 , 4 , 100 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << perfectSquare ( arr , N ) ; return 0 ; } |
Count of subarrays with average K | C ++ implementation of above approach ; Function to count subarray having average exactly equal to K ; To Store the final answer ; Calculate all subarrays ; Calculate required average ; Check if average is equal to k ; Required average found ; Increment res ; Driver code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countKAverageSubarrays ( int arr [ ] , int n , int k ) { int res = 0 ; for ( int L = 0 ; L < n ; L ++ ) { int sum = 0 ; for ( int R = L ; R < n ; R ++ ) { sum += arr [ R ] ; int len = ( R - L + 1 ) ; if ( sum % len == 0 ) { int avg = sum / len ; if ( avg == k ) res ++ ; } } } return res ; } int main ( ) { int K = 6 ; int arr [ ] = { 12 , 5 , 3 , 10 , 4 , 8 , 10 , 12 , -6 , -1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countKAverageSubarrays ( arr , N , K ) ; } |
Maximize minimum array element possible by exactly K decrements | C ++ program for the above approach ; Function to find the maximized minimum element of the array after performing given operation exactly K times ; Stores the minimum element ; Traverse the given array ; Update the minimum element ; Stores the required operations to make all elements equal to the minimum element ; Update required operations ; If reqOperations < K ; Decrement the value of K by reqOperations ; Update minElement ; Return minimum element ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumElement ( int arr [ ] , int N , int K ) { int minElement = arr [ 0 ] ; for ( int i = 0 ; i < N ; ++ i ) { minElement = min ( minElement , arr [ i ] ) ; } int reqOperations = 0 ; for ( int i = 0 ; i < N ; ++ i ) { reqOperations += arr [ i ] - minElement ; } if ( reqOperations < K ) { K -= reqOperations ; minElement -= ( K + N - 1 ) / N ; } return minElement ; } int main ( ) { int arr [ ] = { 10 , 10 , 10 , 10 } ; int K = 7 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumElement ( arr , N , K ) ; return 0 ; } |
Split the fraction into sum of multiple fractions having numerator as 1 | C ++ program for the above approach ; Function to split the fraction into distinct unit fraction ; To store answer ; While numerator is positive ; Finding x = ceil ( d / n ) ; Add 1 / x to list of ans ; Update fraction ; Driver Code ; Given Input ; Function Call ; Print Answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > FractionSplit ( long long n , long long d ) { vector < string > UnitFactions ; while ( n > 0 ) { long long x = ( d + n - 1 ) / n ; string s = "1 / " + to_string ( x ) ; UnitFactions . push_back ( s ) ; n = n * x - d ; d = d * x ; } return UnitFactions ; } int main ( ) { long long n = 13 , d = 18 ; auto res = FractionSplit ( n , d ) ; for ( string s : res ) cout << s << " , β " ; return 0 ; } |
Find permutation of [ 1 , N ] such that ( arr [ i ] != i + 1 ) and sum of absolute difference between arr [ i ] and ( i + 1 ) is minimum | Function to generate the permutation of the first N natural numbers having sum of absolute difference between element and indices as minimum ; Initialize array arr [ ] from 1 to N ; Swap alternate positions ; Check N is greater than 1 and N is odd ; Swapping last two positions ; Print the permutation ; Driver code | #include <iostream> NEW_LINE using namespace std ; void swap ( int & a , int & b ) { int temp = a ; a = b ; b = temp ; } void findPermutation ( int N ) { int arr [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = i + 1 ; } for ( int i = 1 ; i < N ; i += 2 ) { swap ( arr [ i ] , arr [ i - 1 ] ) ; } if ( N % 2 == 1 && N > 1 ) { swap ( arr [ N - 1 ] , arr [ N - 2 ] ) ; } for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " β " ; } } int main ( ) { int N = 7 ; findPermutation ( N ) ; return 0 ; } |
Find Array obtained after adding terms of AP for Q queries | C ++ program for the above approach ; Function to find array after performing the given query to the array elements ; Traverse the given query ; Traverse the given array ; Update the value of A [ i ] ; Update the value of curr ; Print the array elements ; Driver Code ; Function Call | #include <iostream> NEW_LINE using namespace std ; void addAP ( int A [ ] , int Q , int operations [ 2 ] [ 4 ] ) { for ( int j = 0 ; j < 2 ; ++ j ) { int L = operations [ j ] [ 0 ] , R = operations [ j ] [ 1 ] , a = operations [ j ] [ 2 ] , d = operations [ j ] [ 3 ] ; int curr = a ; for ( int i = L - 1 ; i < R ; i ++ ) { A [ i ] += curr ; curr += d ; } } for ( int i = 0 ; i < 4 ; ++ i ) cout << A [ i ] << " β " ; } int main ( ) { int A [ ] = { 5 , 4 , 2 , 8 } ; int Q = 2 ; int Query [ 2 ] [ 4 ] = { { 1 , 2 , 1 , 3 } , { 1 , 4 , 4 , 1 } } ; addAP ( A , Q , Query ) ; return 0 ; } |
Maximize the number N by inserting given digit at any position | C ++ program for the above approach ; Function to find the maximum value of N after inserting the digit K ; Convert it into N to string ; Stores the maximum value of N after inserting K ; Iterate till all digits that are not less than K ; Add the current digit to the string result ; Add digit ' K ' to result ; Iterate through all remaining characters ; Add current digit to result ; Print the maximum number formed ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maximizeNumber ( int N , int K ) { string s = to_string ( N ) ; int L = s . length ( ) ; string result ; int i = 0 ; while ( ( i < L ) && ( K <= ( s [ i ] - '0' ) ) ) { result . push_back ( s [ i ] ) ; ++ i ; } result . push_back ( char ( K + '0' ) ) ; while ( i < L ) { result . push_back ( s [ i ] ) ; ++ i ; } cout << result ; } int main ( ) { int N = 6673 , K = 6 ; maximizeNumber ( N , K ) ; return 0 ; } |
Count of N | C ++ program for the above approach ; Function to find the value of X to the power Y ; Stores the value of X ^ Y ; If y is odd , multiply x with result ; Update the value of y and x ; Return the result ; Function to count number of arrays having element over the range [ 0 , 2 ^ K - 1 ] with Bitwise AND value 0 having maximum possible sum ; Print the value of N ^ K ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int x , unsigned int y ) { int res = 1 ; while ( y > 0 ) { if ( y & 1 ) res = res * x ; y = y >> 1 ; x = x * x ; } return res ; } void countArrays ( int N , int K ) { cout << int ( power ( N , K ) ) ; } int main ( ) { int N = 5 , K = 6 ; countArrays ( N , K ) ; return 0 ; } |
Minimum absolute value of ( K β arr [ i ] ) for all possible values of K over the range [ 0 , N β 1 ] | C ++ program for the above approach ; Function to find the minimum absolute value of ( K - arr [ i ] ) for each possible value of K over the range [ 0 , N - 1 ] | ; Traverse the given array arr [ ] ; Stores the mininimum distance to any array element arr [ i ] ; Check if there is no safe position smaller than i ; Check if the current position is between two safe positions ; Take the minimum of two distances ; Check if the current index is a safe position ; Check if there is no safe position greater than i ; Print the minimum distance ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumDistance ( vector < int > arr , int N ) { int ind = 0 ; int prev = arr [ ind ] ; int s = arr . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int distance = INT_MAX ; if ( i < arr [ 0 ] ) { distance = arr [ 0 ] - i ; } else if ( i >= prev && ind + 1 < s && i <= arr [ ind + 1 ] ) { distance = min ( i - prev , arr [ ind + 1 ] - i ) ; if ( i == arr [ ind + 1 ] ) { distance = 0 ; prev = arr [ ind + 1 ] ; ind ++ ; } } else { distance = i - prev ; } cout << distance << " β " ; } } int main ( ) { int N = 5 ; vector < int > arr = { 0 , 4 } ; minimumDistance ( arr , N ) ; return 0 ; } |
Count of pairs in Array such that bitwise AND of XOR of pair and X is 0 | C ++ program for the above approach ; Function to find the number of pairs that satisfy the given criteria i . e . , i < j and ( arr [ i ] ^ arr [ j ] ) & X is 0 ; Stores the resultant count of pairs ; Iterate over the range [ 0 , N ) ; Iterate over the range ; Check for the given condition ; Return the resultant count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOfPairs ( int arr [ ] , int N , int X ) { int count = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( ( ( arr [ i ] ^ arr [ j ] ) & X ) == 0 ) count ++ ; } } return count ; } int main ( ) { int arr [ ] = { 3 , 2 , 5 , 4 , 6 , 7 } ; int X = 6 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countOfPairs ( arr , N , X ) ; return 0 ; } |
Count of pairs in Array such that bitwise AND of XOR of pair and X is 0 | C ++ program for the above approach ; Function to find the number of pairs that satisfy the given criteria i . e . , i < j and ( arr [ i ] ^ arr [ j ] ) & X is 0 ; Stores the resultant count of pairs ; Initializing the map M ; Populating the map ; Count number of pairs for every element in map using mathematical concept of combination ; As nC2 = n * ( n - 1 ) / 2 ; Return the resultant count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOfPairs ( int arr [ ] , int N , int X ) { int count = 0 ; unordered_map < int , int > M ; for ( int i = 0 ; i < N ; i ++ ) { M [ ( arr [ i ] & X ) ] ++ ; } for ( auto m : M ) { int p = m . second ; count += p * ( p - 1 ) / 2 ; } return count ; } int main ( ) { int arr [ ] = { 3 , 2 , 5 , 4 , 6 , 7 } ; int X = 6 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countOfPairs ( arr , N , X ) ; return 0 ; } |
Count of square submatrices with average at least K | C ++ program for the above approach ; Function to count submatrixes with average greater than or equals to K ; Stores count of submatrices ; Stores the prefix sum of matrix ; Iterate over the range [ 1 , N ] ; Iterate over the range [ 1 , M ] ; Update the prefix sum ; Iterate over the range [ 1 , N ] ; Iterate over the range [ 1 , M ] ; Iterate until l and r are greater than 0 ; Update count ; Stores sum of submatrix with bottom right corner as ( i , j ) and top left corner as ( l , r ) ; If sum1 is less than or equal to sum2 ; Increment cnt by 1 ; Return cnt as the answer ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE int cntMatrices ( vector < vector < int > > arr , int N , int M , int K ) { int cnt = 0 ; vector < vector < int > > pre ( N + 1 , vector < int > ( M + 1 , 0 ) ) ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= M ; j ++ ) { pre [ i ] [ j ] = arr [ i - 1 ] [ j - 1 ] + pre [ i - 1 ] [ j ] + pre [ i ] [ j - 1 ] - pre [ i - 1 ] [ j - 1 ] ; } } for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= M ; j ++ ) { for ( int l = i , r = j ; l > 0 && r > 0 ; l -- , r -- ) { int sum1 = ( K * ( i - l + 1 ) * ( i - r + 1 ) ) ; int sum2 = pre [ i ] [ j ] - pre [ l - 1 ] [ r ] - pre [ l ] [ r - 1 ] + pre [ l - 1 ] [ r - 1 ] ; if ( sum1 <= sum2 ) cnt ++ ; } } } return cnt ; } int main ( ) { vector < vector < int > > arr = { { 2 , 2 , 3 } , { 3 , 4 , 5 } , { 4 , 5 , 5 } } ; int K = 4 ; int N = arr . size ( ) ; int M = arr [ 0 ] . size ( ) ; cout << cntMatrices ( arr , N , M , K ) ; return 0 ; } |
Concatenate the Array of elements into a single element | C ++ program for the above approach ; Function to find the integer value obtained by joining array elements together ; Stores the resulting integer value ; Traverse the array arr [ ] ; Stores the count of digits of arr [ i ] ; Update ans ; Increment ans by arr [ i ] ; Return the ans ; Driver Code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ConcatenateArr ( int arr [ ] , int N ) { int ans = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { int l = floor ( log10 ( arr [ i ] ) + 1 ) ; ans = ans * pow ( 10 , l ) ; ans += arr [ i ] ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 23 , 456 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ConcatenateArr ( arr , N ) ; return 0 ; } |
Count of integers K in range [ 0 , N ] such that ( K XOR K + 1 ) equals ( K + 2 XOR K + 3 ) | C ++ program for the above approach ; Function to count all the integers less than N satisfying the given condition ; Store the count of even numbers less than N + 1 ; Return the count ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countXor ( int N ) { int cnt = N / 2 + 1 ; return cnt ; } int main ( ) { int N = 4 ; cout << countXor ( N ) ; return 0 ; } |
Maximize absolute displacement from origin by moving on X | C ++ program for the above approach ; Recursive function to find the maximum absolute displacement from origin by performing the given set of moves ; If i is equal to N ; If S [ i ] is equal to ' L ' ; If S [ i ] is equal to ' R ' ; If S [ i ] is equal to ' ? ' ; Function to find the maximum absolute displacement from the origin ; Return the maximum absolute displacement ; Driver Code ; Input ; Function call | #include <iostream> NEW_LINE using namespace std ; int DistRecursion ( string S , int i , int dist ) { if ( i == S . length ( ) ) return abs ( dist ) ; if ( S [ i ] == ' L ' ) return DistRecursion ( S , i + 1 , dist - 1 ) ; if ( S [ i ] == ' R ' ) return DistRecursion ( S , i + 1 , dist + 1 ) ; return max ( DistRecursion ( S , i + 1 , dist - 1 ) , DistRecursion ( S , i + 1 , dist + 1 ) ) ; } int maxDistance ( string S ) { return DistRecursion ( S , 0 , 0 ) ; } int main ( ) { string S = " ? RRR ? " ; cout << maxDistance ( S ) ; return 0 ; } |
Estimating the value of Pi using Monte Carlo | Parallel Computing Method | C ++ program for the above approach ; Function to find estimated value of PI using Monte Carlo algorithm ; Stores X and Y coordinates of a random point ; Stores distance of a random point from origin ; Stores number of points lying inside circle ; Stores number of points lying inside square ; Parallel calculation of random points lying inside a circle ; Initializes random points with a seed ; Finds random X co - ordinate ; Finds random X co - ordinate ; Finds the square of distance of point ( x , y ) from origin ; If d is less than or equal to 1 ; Increment pCircle by 1 ; Increment pSquare by 1 ; Stores the estimated value of PI ; Prints the value in pi ; Driver Code ; Input ; Function call | #include <iostream> NEW_LINE using namespace std ; void monteCarlo ( int N , int K ) { double x , y ; double d ; int pCircle = 0 ; int pSquare = 0 ; int i = 0 ; #pragma omp parallel firstprivate(x, y, d, i) reduction(+ : pCircle, pSquare) num_threads(K) NEW_LINE { srand48 ( ( int ) time ( NULL ) ) ; for ( i = 0 ; i < N ; i ++ ) { x = ( double ) drand48 ( ) ; y = ( double ) drand48 ( ) ; d = ( ( x * x ) + ( y * y ) ) ; if ( d <= 1 ) { pCircle ++ ; } pSquare ++ ; } } double pi = 4.0 * ( ( double ) pCircle / ( double ) ( pSquare ) ) ; cout << " Final β Estimation β of β Pi β = β " << pi ; } int main ( ) { int N = 100000 ; int K = 8 ; monteCarlo ( N , K ) ; } |
Count of pairs in range [ P , Q ] with numbers as multiple of R and their product lie in range [ P * Q / 4 , P * Q ] | C ++ program for the above approach ; Function to find the number of pairs such that both the elements are in the range [ P , Q ] and the numbers should be multiple of R , and the product of numbers should lie in the range [ P * Q / 4 , P * Q ] ; Store multiple of r in range of [ P , Q ] ; Itearte in the range [ p , q ] ; Vector to store pair of answer ; Iterate through the vector v ; Iterate in the range [ i + 1 , v . size ( ) - 1 ] ; If pair follow this condition insert the pair in vector ans ; If no pair satisfy the conditions , print - 1 ; Print the pairs which satisfy the given condition ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findPairs ( int p , int q , int r ) { vector < int > v ; for ( int i = p ; i <= q ; i ++ ) { if ( i % r == 0 ) { v . push_back ( i ) ; } } vector < pair < int , int > > ans ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < v . size ( ) ; j ++ ) { if ( v [ i ] * v [ j ] >= p * q / 4 && v [ i ] * v [ j ] <= p * q ) { ans . push_back ( { v [ i ] , v [ j ] } ) ; } } } if ( ans . size ( ) == 0 ) { cout << -1 << endl ; } else { for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { cout << ans [ i ] . first << " β " << ans [ i ] . second << endl ; } } } int main ( ) { int p = 14 , q = 30 , r = 5 ; findPairs ( p , q , r ) ; return 0 ; } |
Print rectangular pattern with given center | C ++ program for the above approach ; Function to print the matrix filled with rectangle pattern having center coordinates are c1 , c2 ; Iterate in the range [ 0 , n - 1 ] ; Iterate in the range [ 0 , n - 1 ] ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printRectPattern ( int c1 , int c2 , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { cout << ( max ( abs ( c1 - i ) , abs ( c2 - j ) ) ) << " β " ; } cout << endl ; } } int main ( ) { int c1 = 2 ; int c2 = 2 ; int n = 5 ; printRectPattern ( c1 , c2 , n ) ; return 0 ; } |
Count of numbers in range [ L , R ] with LSB as 0 in their Binary representation | C ++ implementation of the approach ; Function to return the count of required numbers ; If rightmost bit is 0 ; Return the required count ; Driver code ; Call function countNumbers | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countNumbers ( int l , int r ) { int count = 0 ; for ( int i = l ; i <= r ; i ++ ) { if ( ( i & 1 ) == 0 ) { count ++ ; } } return count ; } int main ( ) { int l = 10 , r = 20 ; cout << countNumbers ( l , r ) ; return 0 ; } |
Count of numbers in range [ L , R ] with LSB as 0 in their Binary representation | C ++ implementation of the approach ; Function to return the count of required numbers ; Count of numbers in range which are divisible by 2 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countNumbers ( int l , int r ) { return ( ( r / 2 ) - ( l - 1 ) / 2 ) ; } int main ( ) { int l = 10 , r = 20 ; cout << countNumbers ( l , r ) ; return 0 ; } |
Length of longest Fibonacci subarray | C ++ program for the above approach ; A utility function that returns true if x is perfect square ; Returns true if n is a Fibinacci Number , else false ; Here n is Fibinac ci if one of 5 * n * n + 4 or 5 * n * n - 4 or both is a perferct square ; Function to find the length of the largest sub - array of an array every element of whose is a Fibonacci number ; Traverse the array arr [ ] ; Check if arr [ i ] is a Fibonacci number ; Stores the maximum length of the Fibonacci number subarray ; Finally , return the maximum length ; Driver code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( int x ) { int s = sqrt ( x ) ; return ( s * s == x ) ; } bool isFibonacci ( int n ) { return isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ; } int contiguousFibonacciNumber ( int arr [ ] , int n ) { int current_length = 0 ; int max_length = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isFibonacci ( arr [ i ] ) ) { current_length ++ ; } else { current_length = 0 ; } max_length = max ( max_length , current_length ) ; } return max_length ; } int main ( ) { int arr [ ] = { 11 , 8 , 21 , 5 , 3 , 28 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << contiguousFibonacciNumber ( arr , n ) ; return 0 ; } |
Minimum number of flips required such that a Binary Matrix doesn 't contain any path from the top left to the bottom right consisting only of 0s | C ++ program for the above approach ; The four direction coordinates changes from the current cell ; Function that returns true if there exists any path from the top - left to the bottom - right cell of 0 s ; If the bottom - right cell is reached ; Update the cell to 1 ; Traverse in all four directions ; Find the new coordinates ; If the new cell is valid ; Recursively call DFS ; If path exists , then return true ; Return false , if there doesn 't exists any such path ; Function to flip the minimum number of cells such that there doesn 't exists any such path from (0, 0) to (N - 1, M - 1) cell consisting of 0s ; Case 1 : If no such path exists already ; Case 2 : If there exists only one path ; Case 3 : If there exists two - path ; Driver Code | #include " bits / stdc + + . h " NEW_LINE using namespace std ; int direction [ ] [ 2 ] = { { -1 , 0 } , { 0 , 1 } , { 0 , -1 } , { 1 , 0 } } ; bool dfs ( vector < vector < int > > & matrix , int i , int j , int N , int M ) { if ( i == N - 1 and j == M - 1 ) { return true ; } matrix [ i ] [ j ] = 1 ; for ( int k = 0 ; k < 4 ; k ++ ) { int newX = i + direction [ k ] [ 0 ] ; int newY = j + direction [ k ] [ 1 ] ; if ( newX >= 0 and newX < N and newY > = 0 and newY < M and matrix [ newX ] [ newY ] == 0 ) { if ( dfs ( matrix , newX , newY , N , M ) ) { return true ; } } } return false ; } int solve ( vector < vector < int > > & matrix ) { int N = matrix . size ( ) ; int M = matrix [ 0 ] . size ( ) ; if ( ! dfs ( matrix , 0 , 0 , N , M ) ) { return 0 ; } if ( ! dfs ( matrix , 0 , 0 , N , M ) ) { return 1 ; } return 2 ; } int main ( ) { vector < vector < int > > mat = { { 0 , 1 , 0 , 0 } , { 0 , 1 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; cout << solve ( mat ) ; return 0 ; } |
Maximize product of subarray sum with its maximum element | C ++ program for the above approach ; Function to find the maximum product of the sum of the subarray with its maximum element ; Traverse the array arr [ ] ; Increment currSum by a [ i ] ; Maximize the value of currMax ; Maximize the value of largestSum ; If currSum goes less than 0 then update currSum = 0 ; Return the resultant value ; Function to maximize the product of the sum of the subarray with its maximum element ; Find the largest sum of the subarray ; Multiply each array element with - 1 ; Find the largest sum of the subarray with negation of all array element ; Return the resultant maximum value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Kadane ( int arr [ ] , int n ) { int largestSum = 0 , currMax = 0 ; int currSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { currSum += arr [ i ] ; currMax = max ( currMax , arr [ i ] ) ; largestSum = max ( largestSum , currMax * currSum ) ; if ( currSum < 0 ) { currMax = 0 ; currSum = 0 ; } } return largestSum ; } int maximumWeight ( int arr [ ] , int n ) { int largestSum = Kadane ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = - arr [ i ] ; } largestSum = max ( largestSum , Kadane ( arr , n ) ) ; return largestSum ; } int main ( ) { int arr [ ] = { 2 , -3 , 8 , -2 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumWeight ( arr , N ) ; return 0 ; } |
Partition an array into two subsets with equal count of unique elements | C ++ program for the above approach ; Function to partition the array into two subsets such that count of unique elements in both subsets is the same ; Stores the subset number for each array elements ; Stores the count of unique array elements ; Stores the frequency of elements ; Traverse the array ; Count of elements having a frequency of 1 ; Check if there exists any element with frequency > 2 ; Count of elements needed to have frequency exactly 1 in each subset ; Initialize all values in the / array ans [ ] as 1 ; Traverse the array ans [ ] ; This array element is a part of first subset ; Half array elements with frequency 1 are part of the second subset ; If count of elements is exactly 1 are odd and has no element with frequency > 2 ; If count of elements that occurs exactly once are even ; Print the result ; If the count of elements has exactly 1 frequency are odd and there is an element with frequency greater than 2 ; Print the result ; Driver Codea | #include <bits/stdc++.h> NEW_LINE using namespace std ; void arrayPartition ( int a [ ] , int n ) { int ans [ n ] ; int cnt = 0 ; int ind , flag = 0 ; map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ a [ i ] ] ++ ; } for ( int i = 0 ; i < n ; i ++ ) { if ( mp [ a [ i ] ] == 1 ) cnt ++ ; if ( mp [ a [ i ] ] > 2 && flag == 0 ) { flag = 1 ; ind = i ; } } int p = ( cnt + 1 ) / 2 ; int ans1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans [ i ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp [ a [ i ] ] == 1 && ans1 < p ) { ans [ i ] = 1 ; ans1 ++ ; } else if ( mp [ a [ i ] ] == 1 ) { ans [ i ] = 2 ; } } if ( cnt % 2 == 1 && flag == 0 ) { cout << -1 << endl ; return ; } if ( cnt % 2 == 0 ) { for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " β " ; } } else { for ( int i = 0 ; i < n ; i ++ ) { if ( ind == i ) cout << 2 << " β " ; else cout << ans [ i ] << " β " ; } } } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 , 4 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; arrayPartition ( arr , N ) ; return 0 ; } |
Modify a given array by replacing each element with the sum or product of their digits based on a given condition | C ++ program for the above approach ; Function to modify the given array as per the given conditions ; Traverse the given array arr [ ] ; Initialize the count of even and odd digits ; Initialize temp with the current array element ; For count the number of even digits ; Increment the odd count ; Otherwise ; Divide temp by 10 ; Performe addition ; Performe multiplication ; Otherwise ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void evenOdd ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int even_digits = 0 ; int odd_digits = 0 ; int temp = arr [ i ] ; while ( temp ) { if ( ( temp % 10 ) & 1 ) odd_digits ++ ; else even_digits ++ ; temp /= 10 ; } if ( even_digits > odd_digits ) { int res = 0 ; while ( arr [ i ] ) { res += arr [ i ] % 10 ; arr [ i ] /= 10 ; } cout << res << " β " ; } else if ( odd_digits > even_digits ) { int res = 1 ; while ( arr [ i ] ) { res *= arr [ i ] % 10 ; arr [ i ] /= 10 ; } cout << res << " β " ; } else cout << arr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 113 , 141 , 214 , 3186 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; evenOdd ( arr , N ) ; return 0 ; } |
Find prime factors of Z such that Z is product of all even numbers till N that are product of two distinct prime numbers | C ++ implementation for the above approach ; Function to print the prime factorization of the product of all numbers <= N that are even and can be expressed as a product of two distinct prime numbers ; sieve of Eratosthenese ; Store prime numbers in the range [ 3 , N / 2 ] ; print the coefficient of 2 in the prime factorization ; print the coefficients of other primes ; Driver code ; Input ; Function calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; void primeFactorization ( int N ) { int sieve [ N / 2 + 1 ] = { 0 } ; for ( int i = 2 ; i <= N / 2 ; i ++ ) { if ( sieve [ i ] == 0 ) { for ( int j = i * i ; j <= N / 2 ; j += i ) { sieve [ j ] = 1 ; } } } vector < int > prime ; for ( int i = 3 ; i <= N / 2 ; i ++ ) if ( sieve [ i ] == 0 ) prime . push_back ( i ) ; int x = prime . size ( ) ; cout << "2 - > " << x << endl ; for ( int i : prime ) cout << i << " - > 1" << endl ; } int main ( ) { int N = 18 ; primeFactorization ( N ) ; return 0 ; } |
Sum of the first M elements of Array formed by infinitely concatenating given array | C ++ program for the above approach ; Function to find the sum of first M numbers formed by the infinite concatenation of the array A [ ] ; Stores the resultant sum ; Iterate over the range [ 0 , M - 1 ] ; Add the value A [ i % N ] to sum ; Return the resultant sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfFirstM ( int A [ ] , int N , int M ) { int sum = 0 ; for ( int i = 0 ; i < M ; i ++ ) { sum = sum + A [ i % N ] ; } return sum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int M = 5 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << sumOfFirstM ( arr , N , M ) ; return 0 ; } |
Check if it is possible to reach M from 0 by given paths | C ++ program for the above approach ; Function to check if it is possible to reach M from 0 ; Stores the farther point that can reach from 1 point ; Stores the farthest point it can go for each index i ; Initialize rightMost [ i ] with 0 ; Traverse the array ; Update the rightMost position reached from a1 ; Find the farthest point it can reach from i ; If point < can be reached ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void canReach0toM ( int a [ ] [ 2 ] , int n , int m ) { int rightMost [ m + 1 ] ; int dp [ m + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { rightMost [ i ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { int a1 = a [ i ] [ 0 ] ; int b1 = a [ i ] [ 1 ] ; rightMost [ a1 ] = max ( rightMost [ a1 ] , b1 ) ; } for ( int i = m ; i >= 0 ; i -- ) { dp [ i ] = i ; for ( int j = min ( m , rightMost [ i ] ) ; j > i ; j -- ) { dp [ i ] = max ( dp [ i ] , dp [ j ] ) ; } } if ( dp [ 0 ] >= m ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { int arr [ ] [ 2 ] = { { 0 , 2 } , { 2 , 2 } , { 2 , 5 } , { 4 , 5 } } ; int M = 5 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; canReach0toM ( arr , N , M ) ; return 0 ; } |
Count of non co | C ++ program for the above approach ; Recursive function to return gcd of two numbers ; Function to count the number of non co - prime pairs for each query ; Traverse the array arr [ ] ; Stores the count of non co - prime pairs ; Iterate over the range [ 1 , x ] ; Iterate over the range [ x , y ] ; If gcd of current pair is greater than 1 ; Driver Code ; Given Input ; Function Call | #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 ) ; } void countPairs ( int * arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int count = 0 ; for ( int x = 1 ; x <= arr [ i ] ; x ++ ) { for ( int y = x ; y <= arr [ i ] ; y ++ ) { if ( gcd ( x , y ) > 1 ) count ++ ; } } cout << count << " β " ; } } int main ( ) { int arr [ ] = { 5 , 10 , 20 } ; int N = 3 ; countPairs ( arr , N ) ; return 0 ; } |
Count of non co | C ++ program for the above approach ; Auxiliary function to pre - compute the answer for each array ; Iterate over the range [ 1 , MAX ] ; Iterate over the range [ 1 , MAX ] ; If the number is prime ; Subtract the number of pairs which has i as one of their factors ; Iterate over the range [ 1 , MAX ] ; Function to count the number of non co - prime pairs for each query ; The i - th element stores the count of element that are co - prime with i ; Stores the resulting array ; Function Call ; Traverse the array arr [ ] ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1005 ; void preCalculate ( vector < int > & phi , vector < int > & ans ) { phi [ 0 ] = 0 ; phi [ 1 ] = 1 ; for ( int i = 2 ; i <= MAX ; i ++ ) phi [ i ] = i ; for ( int i = 2 ; i <= MAX ; i ++ ) { if ( phi [ i ] == i ) { for ( int j = i ; j <= MAX ; j += i ) phi [ j ] -= ( phi [ j ] / i ) ; } } for ( int i = 1 ; i <= MAX ; i ++ ) ans [ i ] = ans [ i - 1 ] + ( i - phi [ i ] ) ; } void countPairs ( int * arr , int N ) { vector < int > phi ( 1e5 , 0 ) ; vector < int > ans ( 1e5 , 0 ) ; preCalculate ( phi , ans ) ; for ( int i = 0 ; i < N ; ++ i ) { cout << ans [ arr [ i ] ] << " β " ; } } int main ( ) { int arr [ ] = { 5 , 10 , 20 } ; int N = 3 ; countPairs ( arr , N ) ; } |
Maximum number of multiplication by 3 or division by 2 operations possible on an array | C ++ program for the above approach ; Function to count maximum number of multiplication by 3 or division by 2 operations that can be performed ; Stores the maximum number of operations possible ; Traverse the array arr [ ] ; Iterate until arr [ i ] is even ; Increment count by 1 ; Update arr [ i ] ; Return the value of Count as the answer ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumTurns ( int arr [ ] , int N ) { int Count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { while ( arr [ i ] % 2 == 0 ) { Count ++ ; arr [ i ] = arr [ i ] / 2 ; } } return Count ; } int main ( ) { int arr [ ] = { 5 , 2 , 4 } ; int M = 3 , K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumTurns ( arr , N ) ; return 0 ; } |
Distribute the white and black objects into maximum groups under certain constraints | C ++ program for the above approach ; Function to check if it is possible to distribute W and B into maximum groups possible ; If W is greater than B , swap them ; Distribution is not possible ; Distribution is possible ; Driver code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void isPossible ( int W , int B , int D ) { if ( W > B ) swap ( W , B ) ; if ( B > W * ( D + 1 ) ) cout << " NO " << endl ; else cout << " YES " << endl ; } int main ( ) { int W = 2 ; int B = 5 ; int D = 2 ; isPossible ( W , B , D ) ; return 0 ; } |
Find the maximum GCD possible for some pair in a given range [ L , R ] | C ++ program for the above approach ; Function to calculate GCD ; Function to calculate maximum GCD in a range ; Variable to store the answer ; If Z has two multiples in [ L , R ] ; Update ans ; Return the value ; Driver code ; Input ; Function Call | #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 maxGCDInRange ( int L , int R ) { int ans = 1 ; for ( int Z = R ; Z >= 1 ; Z -- ) { if ( ( R / Z ) - ( L - 1 ) / Z > 1 ) { ans = Z ; break ; } } return ans ; } int main ( ) { int L = 102 ; int R = 139 ; cout << maxGCDInRange ( L , R ) ; return 0 ; } |
Number of ways to form a number with maximum Ks in it | C ++ program for the above approach ; Function to calculate number of ways a number can be formed that has the maximum number of Ks ; convert to string ; calculate length of subarrays that can contribute to the answer ; count length of subarray where adjacent digits add up to K ; Current subarray can contribute to the answer only if it is odd ; return the answer ; Driver code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int noOfWays ( int N , int K ) { string S = to_string ( N ) ; int ans = 1 ; for ( int i = 1 ; i < S . length ( ) ; i ++ ) { int count = 1 ; while ( i < S . length ( ) && S [ i ] - '0' + S [ i - 1 ] - '0' == K ) { count ++ ; i ++ ; } if ( count % 2 ) ans *= ( count + 1 ) / 2 ; } return ans ; } int main ( ) { int N = 1454781 ; int K = 9 ; cout << noOfWays ( N , K ) << endl ; } |
Minimum bit swaps between given numbers to make their Bitwise OR equal to Bitwise AND | C ++ implementation of the above approach ; Function for counting number of set bit ; Function to return the count of minimum operations required ; cnt to count the number of bits set in A and in B ; if odd numbers of total set bits ; one_zero = 1 in A and 0 in B at ith bit similarly for zero_one ; When bitpos is set in B , unset in B ; When bitpos is set in A , unset in B ; number of moves is half of number pairs of each group ; odd number pairs ; Driver code ; Input ; Function call to compute the result | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSetBits ( int n ) { int count = 0 ; while ( n ) { n = n & ( n - 1 ) ; count ++ ; } return count ; } int minOperations ( int A , int B ) { int cnt1 = 0 , cnt2 = 0 ; cnt1 += countSetBits ( A ) ; cnt2 += countSetBits ( B ) ; if ( ( cnt1 + cnt2 ) % 2 != 0 ) return -1 ; int oneZero = 0 , zeroOne = 0 ; int ans = 0 ; for ( int i = 0 ; i < max ( cnt1 , cnt2 ) ; i ++ ) { int bitpos = 1 << i ; if ( ( ! ( bitpos & A ) ) && ( bitpos & B ) ) zeroOne ++ ; if ( ( bitpos & A ) && ( ! ( bitpos & B ) ) ) oneZero ++ ; } ans = ( zeroOne / 2 ) + ( oneZero / 2 ) ; if ( zeroOne % 2 != 0 ) ans += 2 ; return ans ; } int main ( ) { int A = 27 , B = 5 ; cout << minOperations ( A , B ) ; return 0 ; } |
Largest sum subarray of size K containing consecutive elements | C ++ program for the above approach ; Function to find the largest sum subarray such that it contains K consecutive elements ; Stores sum of subarray having K consecutive elements ; Stores the maximum sum among all subarrays of size K having consecutive elements ; Traverse the array ; Store K elements of one subarray at a time ; Sort the duplicate array in ascending order ; Checks if elements in subarray are consecutive or not ; Traverse the k elements ; If not consecutive , break ; If flag is true update the maximum sum ; Stores the sum of elements of the current subarray ; Update the max_sum ; Reset curr_sum ; Return the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( vector < int > A , int N , int K ) { int curr_sum = 0 ; int max_sum = INT_MIN ; for ( int i = 0 ; i < N - K + 1 ; i ++ ) { vector < int > dupl_arr ( A . begin ( ) + i , A . begin ( ) + i + K ) ; sort ( dupl_arr . begin ( ) , dupl_arr . end ( ) ) ; bool flag = true ; for ( int j = 1 ; j < K ; j ++ ) { if ( dupl_arr [ j ] - dupl_arr [ j - 1 ] != 1 ) { flag = false ; break ; } } if ( flag ) { int temp = 0 ; curr_sum = accumulate ( dupl_arr . begin ( ) , dupl_arr . end ( ) , temp ) ; max_sum = max ( max_sum , curr_sum ) ; curr_sum = 0 ; } } return max_sum ; } int main ( ) { vector < int > arr = { 10 , 12 , 9 , 8 , 10 , 15 , 1 , 3 , 2 } ; int K = 3 ; int N = arr . size ( ) ; cout << maximumSum ( arr , N , K ) ; return 0 ; } |
Find the count of Smith Brothers Pairs in a given Array | C ++ program for the above approach ; array to store all prime less than and equal to MAX ; utility function for sieve of sundaram ; Main logic of Sundaram . ; Since 2 is a prime number ; only primes are selected ; Function to check whether a number is a smith number . ; Find sum the digits of prime factors of n ; add its digits of prime factors to pDigitSum . ; one prime factor is still to be summed up ; Now sum the digits of the original number ; return the answer ; Function to check if X and Y are a Smith Brother Pair ; Function to find pairs from array ; Iterate through all pairs ; Increment count if there is a smith brother pair ; Driver code ; Preprocessing ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 10000 ; vector < int > primes ; void sieveSundaram ( ) { bool marked [ MAX / 2 + 100 ] = { 0 } ; for ( int i = 1 ; i <= ( sqrt ( MAX ) - 1 ) / 2 ; i ++ ) for ( int j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) marked [ j ] = true ; primes . push_back ( 2 ) ; for ( int i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked [ i ] == false ) primes . push_back ( 2 * i + 1 ) ; } bool isSmith ( int n ) { int original_no = n ; int pDigitSum = 0 ; for ( int i = 0 ; primes [ i ] <= n / 2 ; i ++ ) { while ( n % primes [ i ] == 0 ) { int p = primes [ i ] ; n = n / p ; while ( p > 0 ) { pDigitSum += ( p % 10 ) ; p = p / 10 ; } } } if ( n != 1 && n != original_no ) { while ( n > 0 ) { pDigitSum = pDigitSum + n % 10 ; n = n / 10 ; } } int sumDigits = 0 ; while ( original_no > 0 ) { sumDigits = sumDigits + original_no % 10 ; original_no = original_no / 10 ; } return ( pDigitSum == sumDigits ) ; } bool isSmithBrotherPair ( int X , int Y ) { return isSmith ( X ) && isSmith ( Y ) && abs ( X - Y ) == 1 ; } int countSmithBrotherPairs ( int A [ ] , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = i + 1 ; j < N ; j ++ ) { if ( isSmithBrotherPair ( A [ i ] , A [ j ] ) ) count ++ ; } return count ; } int main ( ) { sieveSundaram ( ) ; int A [ ] = { 728 , 729 , 28 , 2964 , 2965 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << countSmithBrotherPairs ( A , N ) << endl ; return 0 ; } |
Find the count of Smith Brothers Pairs in a given Array | C ++ program for the above approach ; array to store all prime less than and equal to MAX ; utility function for sieve of sundaram ; Main logic of Sundaram . ; Since 2 is a prime number ; only primes are selected ; Function to check whether a number is a smith number . ; Find sum the digits of prime factors of n ; add its digits of prime factors to pDigitSum . ; one prime factor is still to be summed up ; Now sum the digits of the original number ; return the answer ; Function to check if X and Y are a Smith Brother Pair ; Function to find pairs from array ; Variable to store number of Smith Brothers Pairs ; sort A ; check for consecutive numbers only ; Driver code ; Preprocessing sieve of sundaram ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 10000 ; vector < int > primes ; void sieveSundaram ( ) { bool marked [ MAX / 2 + 100 ] = { 0 } ; for ( int i = 1 ; i <= ( sqrt ( MAX ) - 1 ) / 2 ; i ++ ) for ( int j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) marked [ j ] = true ; primes . push_back ( 2 ) ; for ( int i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked [ i ] == false ) primes . push_back ( 2 * i + 1 ) ; } bool isSmith ( int n ) { int original_no = n ; int pDigitSum = 0 ; for ( int i = 0 ; primes [ i ] <= n / 2 ; i ++ ) { while ( n % primes [ i ] == 0 ) { int p = primes [ i ] ; n = n / p ; while ( p > 0 ) { pDigitSum += ( p % 10 ) ; p = p / 10 ; } } } if ( n != 1 && n != original_no ) { while ( n > 0 ) { pDigitSum = pDigitSum + n % 10 ; n = n / 10 ; } } int sumDigits = 0 ; while ( original_no > 0 ) { sumDigits = sumDigits + original_no % 10 ; original_no = original_no / 10 ; } return ( pDigitSum == sumDigits ) ; } bool isSmithBrotherPair ( int X , int Y ) { return isSmith ( X ) && isSmith ( Y ) ; } int countSmithBrotherPairs ( int A [ ] , int N ) { int count = 0 ; sort ( A , A + N ) ; for ( int i = 0 ; i < N - 2 ; i ++ ) if ( isSmithBrotherPair ( A [ i ] , A [ i + 1 ] ) ) count ++ ; return count ; } int main ( ) { sieveSundaram ( ) ; int A [ ] = { 728 , 729 , 28 , 2964 , 2965 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << countSmithBrotherPairs ( A , N ) << endl ; return 0 ; } |
Count pair sums that are factors of the sum of the array | C ++ program for the above approach ; Function to find the number of pairs whose sums divides the sum of array ; Initialize the totalSum and count as 0 ; Calculate the total sum of array ; Generate all possible pairs ; If the sum is a factor of totalSum or not ; Increment count by 1 ; Print the total count obtained ; Driver Code | #include <iostream> NEW_LINE using namespace std ; void countPairs ( int arr [ ] , int N ) { int count = 0 , totalSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { totalSum += arr [ i ] ; } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( totalSum % ( arr [ i ] + arr [ j ] ) == 0 ) { count += 1 ; } } } cout << count ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , N ) ; return 0 ; } |
Maximize average of the ratios of N pairs by M increments | C ++ program for the above approach ; Function to find the change in the ratio in pair after applying operation ; Stores the current ratio ; Stores the new ratio ; Stores the increase in ratio ; Returns the change ; Function to find the maximum average of the ratio of the pairs by applying M increments ; Stores the required result ; Declare a priority queue for storing the increments ; Store the increase in the ratio after applying one operation ; Push the increased value and index value in priority queue ; Store the ratio ; Update the value of sum ; Iterate while M > 0 ; Add the maximum change to the sum ; Remove the element from the priority queue ; Increase the pairs elements by 1 on which operation is applied ; Push the updated change of the pair in priority queue ; Decrease the operation count ; Update the value of the sum by dividing it by N ; Return the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double change ( int pass , int total ) { double currentPassRatio , newPassRatio ; double increase ; currentPassRatio = ( ( double ) pass ) / total ; newPassRatio = ( ( double ) ( pass + 1 ) ) / ( total + 1 ) ; increase = newPassRatio - currentPassRatio ; return increase ; } double maximumAverage ( vector < vector < int > > v , int M , int N ) { double sum = 0 ; double increase , average ; priority_queue < pair < double , int > > pq ; for ( int i = 0 ; i < N ; i ++ ) { increase = change ( v [ i ] [ 0 ] , v [ i ] [ 1 ] ) ; pq . push ( { increase , i } ) ; average = v [ i ] [ 0 ] * 1.0 / v [ i ] [ 1 ] ; sum += average ; } while ( M > 0 ) { sum += pq . top ( ) . first ; int i = pq . top ( ) . second ; pq . pop ( ) ; v [ i ] [ 0 ] += 1 ; v [ i ] [ 1 ] += 1 ; pq . push ( { change ( v [ i ] [ 0 ] , v [ i ] [ 1 ] ) , i } ) ; M -- ; } double ans = sum / N ; return ans ; } int main ( ) { vector < vector < int > > V = { { 1 , 2 } , { 3 , 5 } , { 2 , 2 } } ; int M = 2 ; int N = V . size ( ) ; cout << maximumAverage ( V , M , N ) ; return 0 ; } |
Print all numbers that are divisors of N and are co | C ++ program for the above approach ; Function to print all numbers that are divisors of N and are co - prime with the quotient of their division ; Iterate upto square root of N ; If divisors are equal and gcd is 1 , then print only one of them ; Otherwise print both ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printUnitaryDivisors ( int n ) { for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i && __gcd ( i , n / i ) == 1 ) { printf ( " % d β " , i ) ; } else { if ( __gcd ( i , n / i ) == 1 ) { printf ( " % d β % d β " , i , n / i ) ; } } } } } int main ( ) { int N = 12 ; printUnitaryDivisors ( N ) ; return 0 ; } |
Maximize K to make given array Palindrome when each element is replaced by its remainder with K | C ++ program for the above approach ; utility function to calculate the GCD of two numbers ; Function to calculate the largest K , replacing all elements of an array A by their modulus with K , makes A a palindromic array ; check if A is palindrome ; A is not palindromic ; K can be infitely large in this case ; variable to store the largest K that makes A palindromic ; return the required answer ; Driver code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; else return gcd ( b , a % b ) ; } int largestK ( int A [ ] , int N ) { int l = 0 , r = N - 1 , flag = 0 ; while ( l < r ) { if ( A [ l ] != A [ r ] ) { flag = 1 ; break ; } l ++ ; r -- ; } if ( flag == 0 ) return -1 ; int K = abs ( A [ 0 ] - A [ N - 1 ] ) ; for ( int i = 1 ; i < N / 2 ; i ++ ) K = gcd ( K , abs ( A [ i ] - A [ N - i - 1 ] ) ) ; return K ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 2 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << largestK ( A , N ) << endl ; return 0 ; } |
Check if N can be represented as sum of distinct powers of 3 | C ++ program for the above approach ; Function to try all permutations of distinct powers ; Base Case ; If the distinct powers sum is obtained ; Otherwise ; If current element not selected in power [ ] ; If current element selected in power [ ] ; Return 1 if any permutation found ; Function to check the N can be represented as the sum of the distinct powers of 3 ; Stores the all distincts powers of three to [ 0 , 15 ] ; Function Call ; print ; Driven Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool PermuteAndFind ( vector < long > power , int idx , long SumSoFar , int target ) { if ( idx == power . size ( ) ) { if ( SumSoFar == target ) return true ; return false ; } bool select = PermuteAndFind ( power , idx + 1 , SumSoFar , target ) ; bool notselect = PermuteAndFind ( power , idx + 1 , SumSoFar + power [ idx ] , target ) ; return ( select notselect ) ; } void DistinctPowersOf3 ( int N ) { vector < long > power ( 16 ) ; power [ 0 ] = 1 ; for ( int i = 1 ; i < 16 ; i ++ ) power [ i ] = 3 * power [ i - 1 ] ; bool found = PermuteAndFind ( power , 0 , 0L , N ) ; if ( found == true ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { int N = 91 ; DistinctPowersOf3 ( N ) ; return 0 ; } |
Check if N can be represented as sum of distinct powers of 3 | C ++ program for the above approach ; Function to check whether the given N can be represented as the sum of the distinct powers of 3 ; Iterate until N is non - zero ; Termination Condition ; Right shift ternary bits by 1 for the next digit ; If N can be expressed as the sum of perfect powers of 3 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void DistinctPowersOf3 ( int N ) { while ( N > 0 ) { if ( N % 3 == 2 ) { cout << " No " ; return ; } N /= 3 ; } cout << " Yes " ; } int main ( ) { int N = 91 ; DistinctPowersOf3 ( N ) ; return 0 ; } |
Generate an N | C ++ program for the above approach ; Function to print the permutation of size N with absolute difference of adjacent elements in range [ 2 , 4 ] ; If N is less than 4 ; Check if N is even ; Traverse through odd integers ; Update the value of i ; Traverse through even integers ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void getPermutation ( int N ) { if ( N <= 3 ) { cout << -1 ; return ; } int i = N ; if ( N % 2 == 0 ) i -- ; while ( i >= 1 ) { cout << i << " β " ; i -= 2 ; } cout << 4 << " β " << 2 << " β " ; i = 6 ; while ( i <= N ) { cout << i << " β " ; i += 2 ; } } int main ( ) { int N = 9 ; getPermutation ( N ) ; return 0 ; } |
Count of distinct values till C formed by adding or subtracting A , B , or 0 any number of times | C ++ program for the above approach ; Function to calculate gcd ; Function to find number of possible final values ; Find the gcd of two numbers ; Calculate number of distinct values ; Return values ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int A , int B ) { if ( B == 0 ) return A ; else return gcd ( B , A % B ) ; } int getDistinctValues ( int A , int B , int C ) { int g = gcd ( A , B ) ; int num_values = C / g ; return num_values ; } int main ( ) { int A = 2 ; int B = 3 ; int C = 10 ; cout << ( getDistinctValues ( A , B , C ) ) ; return 0 ; } |
Find array whose elements are XOR of adjacent elements in given array | C ++ implementation of the above approach ; Function to reconstruct the array arr [ ] with xor of adjacent elements ; Iterate through each element ; Store the xor of current and next element in arr [ i ] ; Function to print the array ; Driver Code ; Inputs ; Length of the array given ; Function call to reconstruct the arr [ ] ; Function call to print arr [ ] | #include <iostream> NEW_LINE using namespace std ; int * game_with_number ( int arr [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { arr [ i ] = arr [ i ] ^ arr [ i + 1 ] ; } return arr ; } void print ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 10 , 11 , 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * new_arr = game_with_number ( arr , n ) ; print ( new_arr , n ) ; } |
Maximize score of same | C ++ program for the above approach ; Function to calculate the score of same - indexed subarrays selected from the arrays a [ ] and b [ ] ; Traverse the current subarray ; Finding the score without reversing the subarray ; Calculating the score of the reversed subarray ; Return the score of subarray ; Function to find the subarray with the maximum score ; Stores the maximum score and the starting and the ending point of subarray with maximum score ; Traverse all the subarrays ; Store the score of the current subarray ; Update the maximum score ; Print the maximum score ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int currSubArrayScore ( int * a , int * b , int l , int r ) { int straightScore = 0 ; int reverseScore = 0 ; for ( int i = l ; i <= r ; i ++ ) { straightScore += a [ i ] * b [ i ] ; reverseScore += a [ r - ( i - l ) ] * b [ i ] ; } return max ( straightScore , reverseScore ) ; } void maxScoreSubArray ( int * a , int * b , int n ) { int res = 0 , start = 0 , end = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { int currScore = currSubArrayScore ( a , b , i , j ) ; if ( currScore > res ) { res = currScore ; start = i ; end = j ; } } } cout << res ; } int main ( ) { int A [ ] = { 13 , 4 , 5 } ; int B [ ] = { 10 , 22 , 2 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; maxScoreSubArray ( A , B , N ) ; return 0 ; } |
Maximize score of same | C ++ program for the above approach ; Function to calculate the score of same - indexed subarrays selected from the arrays a [ ] and b [ ] ; Store the required result ; Iterate in the range [ 0 , N - 1 ] ; Consider the case of odd length subarray ; Update the maximum score ; Expanding the subarray in both directions with equal length so that mid point remains same ; Update both the scores ; Consider the case of even length subarray ; Update both the scores ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxScoreSubArray ( int * a , int * b , int n ) { int res = 0 ; for ( int mid = 0 ; mid < n ; mid ++ ) { int straightScore = a [ mid ] * b [ mid ] , reverseScore = a [ mid ] * a [ mid ] ; int prev = mid - 1 , next = mid + 1 ; res = max ( res , max ( straightScore , reverseScore ) ) ; while ( prev >= 0 && next < n ) { straightScore += ( a [ prev ] * b [ prev ] + a [ next ] * b [ next ] ) ; reverseScore += ( a [ prev ] * b [ next ] + a [ next ] * b [ prev ] ) ; res = max ( res , max ( straightScore , reverseScore ) ) ; prev -- ; next ++ ; } straightScore = 0 ; reverseScore = 0 ; prev = mid - 1 , next = mid ; while ( prev >= 0 && next < n ) { straightScore += ( a [ prev ] * b [ prev ] + a [ next ] * b [ next ] ) ; reverseScore += ( a [ prev ] * b [ next ] + a [ next ] * b [ prev ] ) ; res = max ( res , max ( straightScore , reverseScore ) ) ; prev -- ; next ++ ; } } cout << res ; } int main ( ) { int A [ ] = { 13 , 4 , 5 } ; int B [ ] = { 10 , 22 , 2 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; maxScoreSubArray ( A , B , N ) ; return 0 ; } |
Length of the smallest subarray with maximum possible sum | C ++ program for the above approach ; Function to find the minimum length of the subarray whose sum is maximum ; Stores the starting and the ending index of the resultant subarray ; Traverse the array until a non - zero element is encountered ; If the array contains only of 0 s ; Traverse the array in reverse until a non - zero element is encountered ; Return the resultant size of the subarray ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumSizeSubarray ( int arr [ ] , int N ) { int i = 0 , j = N - 1 ; while ( i < N and arr [ i ] == 0 ) { i ++ ; } if ( i == N ) return 1 ; while ( j >= 0 and arr [ j ] == 0 ) { j -- ; } return ( j - i + 1 ) ; } int main ( ) { int arr [ ] = { 0 , 2 , 0 , 0 , 12 , 0 , 0 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumSizeSubarray ( arr , N ) ; return 0 ; } |
Count ways to represent N as XOR of distinct integers not exceeding N | C ++ program for the above approach ; Function to count number of ways to represent N as the Bitwise XOR of distinct integers ; Count number of subsets using above - mentioned formula ; Print the resultant count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countXorPartition ( int N ) { double a = pow ( 2 , floor ( N - log ( N + 1 ) / log ( 2 ) ) ) ; cout << a ; } int main ( ) { int N = 5 ; countXorPartition ( N ) ; } |
Count numbers less than N whose modulo with A is equal to B | C ++ program for the above approach ; Function to count numbers less than N , whose modulo with A gives B ; If the value of B at least A ; If the value of B is 0 or not ; Stores the resultant count of numbers less than N ; Update the value of ans ; Print the value of ans ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countValues ( int A , int B , int C ) { if ( B >= A ) { cout << 0 ; return ; } if ( B == 0 ) { cout << C / A ; return ; } int ans = C / A ; if ( ans * A + B <= C ) { ans ++ ; } cout << ans ; } int main ( ) { int A = 6 , B = 3 , N = 15 ; countValues ( A , B , N ) ; return 0 ; } |
Reduce a number to 1 by performing given operations | Set 3 | C ++ program for the above approach ; Utility function to check if n is power of 2 ; Utility function to find highest power of 2 less than or equal to given number ; Recursive function to find steps needed to reduce a given integer to 1 ; Base Condition ; If the number is a power of 2 ; Else subtract the greatest power of 2 smaller than N from N ; Driver Code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int highestPowerof2 ( int n ) { int p = ( int ) log2 ( n ) ; return ( int ) pow ( 2 , p ) ; } bool isPowerOfTwo ( int n ) { if ( n == 0 ) return false ; return ( ceil ( log2 ( n ) ) == floor ( log2 ( n ) ) ) ; } int reduceToOne ( int N ) { if ( N == 1 ) { return 0 ; } if ( isPowerOfTwo ( N ) == true ) { return 1 + reduceToOne ( N / 2 ) ; } else { return 1 + reduceToOne ( N - highestPowerof2 ( N ) ) ; } } int main ( ) { int N = 7 ; cout << reduceToOne ( N ) << endl ; } |
Maximum sum of a subsequence whose Bitwise AND is non | C ++ program for the above approach ; Function to find the maximum sum of a subsequence whose Bitwise AND is non - zero ; Stores the resultant maximum sum of the subsequence ; Iterate over all the bits ; Stores the sum of array elements whose i - th bit is set ; Traverse the array elements ; If the bit is set , then add its value to the sum ; Update the resultant maximum sum ; Return the maximum sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( int arr [ ] , int N ) { int ans = 0 ; for ( int bit = 0 ; bit < 32 ; bit ++ ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] & ( 1 << bit ) ) { sum += arr [ i ] ; } } ans = max ( ans , sum ) ; } return ans ; } int main ( ) { int arr [ ] = { 5 , 4 , 1 , 7 , 11 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumSum ( arr , N ) ; return 0 ; } |
Check if an array can be reduced to at most length K by removal of distinct elements | C ++ program for the above approach ; Function to check if it is possible to reduce the size of the array to K by removing the set of the distinct array elements ; Stores all distinct elements present in the array arr [ ] ; Traverse the given array ; Insert array elements into the set ; Condition for reducing size of the array to at most K ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxCount ( int arr [ ] , int N , int K ) { set < int > st ; for ( int i = 0 ; i < N ; i ++ ) { st . insert ( arr [ i ] ) ; } if ( N - st . size ( ) <= K ) { cout << " Yes " ; } else cout << " No " ; } int main ( ) { int arr [ ] = { 2 , 2 , 2 , 3 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maxCount ( arr , N , K ) ; return 0 ; } |
Maximum element present in the array after performing queries to add K to range of indices [ L , R ] | C ++ program for the above approach ; Function to find the max sum after processing q queries ; Store the cumulative sum ; Store the maximum sum ; Iterate over the range 0 to q ; Variables to extract values from vector ; Iterate over the range [ 1 , n ] ; Calculate cumulative sum ; Calculate maximum sum ; Return the maximum sum after q queries ; Driver code ; Stores the size of array and number of queries ; Stores the sum ; Storing input queries ; Function call to find the maximum sum | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max_sum ( int a [ ] , vector < pair < pair < int , int > , int > > v , int q , int n ) { int x = 0 ; int m = INT_MIN ; for ( int i = 0 ; i < q ; i ++ ) { int p , q , k ; p = v [ i ] . first . first ; q = v [ i ] . first . second ; k = v [ i ] . second ; a [ p ] += k ; if ( q + 1 <= n ) a [ q + 1 ] -= k ; } for ( int i = 1 ; i <= n ; i ++ ) { x += a [ i ] ; m = max ( m , x ) ; } return m ; } int main ( ) { int n = 10 , q = 3 ; int a [ n + 5 ] = { 0 } ; vector < pair < pair < int , int > , int > > v ( q ) ; v [ 0 ] . first . first = 1 ; v [ 0 ] . first . second = 5 ; v [ 0 ] . second = 3 ; v [ 1 ] . first . first = 4 ; v [ 1 ] . first . second = 8 ; v [ 1 ] . second = 7 ; v [ 2 ] . first . first = 6 ; v [ 2 ] . first . second = 9 ; v [ 2 ] . second = 1 ; cout << max_sum ( a , v , q , n ) ; return 0 ; } |
Check if a pair of integers from two ranges exists such that their Bitwise XOR exceeds both the ranges | C ++ program for the above approach ; Function to check if there exists any pair ( P , Q ) whose Bitwise XOR is greater than the Bitwise XOR of X and Y ; Stores the Bitwise XOR of X & Y ; Traverse all possible pairs ; If a pair exists ; If a pair is found ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findWinner ( int X , int Y ) { int playerA = ( X ^ Y ) ; bool flag = false ; for ( int i = 1 ; i <= X ; i ++ ) { for ( int j = 1 ; j <= Y ; j ++ ) { int val = ( i ^ j ) ; if ( val > playerA ) { flag = true ; break ; } } if ( flag ) { break ; } } if ( flag ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { int A = 2 , B = 4 ; findWinner ( A , B ) ; return 0 ; } |
Check if a pair of integers from two ranges exists such that their Bitwise XOR exceeds both the ranges | C ++ program for the above approach ; Function to check if there exists any pair ( P , Q ) whose Bitwise XOR is greater than the Bitwise XOR of X and Y ; Check for the invalid condition ; Otherwise , ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findWinner ( int X , int Y ) { int first = ( X ^ Y ) ; int second = ( X + Y ) ; if ( first == second ) { cout << " No " ; } else { cout << " Yes " ; } } int main ( ) { int A = 2 , B = 4 ; findWinner ( A , B ) ; return 0 ; } |
Smallest number required to be added to M to make it divisible by N | C ++ program for the above approach ; Function to find the smallest number greater than or equal to N , that is divisible by k ; Function to find the smallest number required to be added to to M to make it divisible by N ; Stores the smallest multiple of N , greater than or equal to M ; Return the result ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findNum ( int N , int K ) { int rem = ( N + K ) % K ; if ( rem == 0 ) return N ; else return N + K - rem ; } int findSmallest ( int M , int N ) { int x = findNum ( M , N ) ; return x - M ; } int main ( ) { int M = 100 , N = 28 ; cout << findSmallest ( M , N ) ; return 0 ; } |
Prefix Factorials of a Prefix Sum Array | C ++ program for the above approach ; Function to find the factorial of prefix sum at every possible index ; Find the prefix sum array ; Stores the factorial of all the element till the sum of array ; Find the factorial array ; Find the factorials of each array element ; Print the resultant array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void prefixFactorialArray ( int A [ ] , int N ) { for ( int i = 1 ; i < N ; i ++ ) { A [ i ] += A [ i - 1 ] ; } int fact [ A [ N - 1 ] + 1 ] ; fact [ 0 ] = 1 ; for ( int i = 1 ; i <= A [ N - 1 ] ; i ++ ) { fact [ i ] = i * fact [ i - 1 ] ; } for ( int i = 0 ; i < N ; i ++ ) { A [ i ] = fact [ A [ i ] ] ; } for ( int i = 0 ; i < N ; i ++ ) { cout << A [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; prefixFactorialArray ( arr , N ) ; return 0 ; } |
Maximum frequency of any array element possible by at most K increments | C ++ program for the above approach ; Function to find the maximum possible frequency of a most frequent element after at most K increment operations ; Sort the input array ; Stores the sum of sliding window and the maximum possible frequency of any array element ; Traverse the array ; Add the current element to the window ; If it is not possible to make the array elements in the window equal ; Update the value of sum ; Increment the value of start ; Update the maximum possible frequency ; Print the frequency of the most frequent array element after K increments ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxFrequency ( int arr [ ] , int N , int K ) { sort ( arr , arr + N ) ; int start = 0 , end = 0 ; int sum = 0 , res = 0 ; for ( end = 0 ; end < N ; end ++ ) { sum += arr [ end ] ; while ( ( end - start + 1 ) * arr [ end ] - sum > K ) { sum -= arr [ start ] ; start ++ ; } res = max ( res , end - start + 1 ) ; } cout << res << endl ; } int main ( ) { int arr [ ] = { 1 , 4 , 8 , 13 } ; int N = 4 ; int K = 5 ; maxFrequency ( arr , N , K ) ; return 0 ; } |
Count pairs ( i , j ) from an array such that i < j and arr [ j ] | C ++ program for the above approach ; Function to count the number of pairs ( i , j ) such that i < j and arr [ i ] - arr [ j ] = X * ( j - i ) ; Stores the count of all such pairs that satisfies the condition . ; Stores count of distinct values of arr [ i ] - x * i ; Iterate over the Map ; Increase count of pairs ; Print the count of such pairs ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int arr [ ] , int n , int x ) { int count = 0 ; map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ arr [ i ] - x * i ] ++ ; } for ( auto x : mp ) { int n = x . second ; count += ( n * ( n - 1 ) ) / 2 ; } cout << count ; } int main ( ) { int n = 6 , x = 3 ; int arr [ ] = { 5 , 4 , 8 , 11 , 13 , 16 } ; countPairs ( arr , n , x ) ; return 0 ; } |
Queries to find the sum of weights of all nodes with vertical width from given range in a Binary Tree | C ++ program for the above approach ; Structure of a node ; Function to create new node ; Function to pre - compute the sum of weights at each width position ; Base Case ; Update the current width position weight ; Recursive Call to its left ; Recursive Call to its right ; Function to find the sum of the weights of nodes whose vertical widths lies over the range [ L , R ] for Q queries ; Stores the weight sum of each width position ; Function Call to fill um ; Stores the sum of all previous nodes , while traversing Map ; Traverse the Map um ; Iterate over all queries ; Print the result for the current query [ l , r ] ; Driver Code ; Given Tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left ; Node * right ; } ; Node * newNode ( int d ) { Node * n = new Node ; n -> data = d ; n -> left = NULL ; n -> right = NULL ; return n ; } void findwt ( Node * root , int wt [ ] , map < int , int > & um , int width = 0 ) { if ( root == NULL ) { return ; } um [ width ] += wt [ root -> data ] ; findwt ( root -> left , wt , um , width - 1 ) ; findwt ( root -> right , wt , um , width + 1 ) ; } void solveQueries ( int wt [ ] , Node * root , vector < vector < int > > queries ) { map < int , int > um ; findwt ( root , wt , um ) ; int x = 0 ; for ( auto it = um . begin ( ) ; it != um . end ( ) ; it ++ ) { x += it -> second ; um [ it -> first ] = x ; } for ( int i = 0 ; i < queries . size ( ) ; i ++ ) { int l = queries [ i ] [ 0 ] ; int r = queries [ i ] [ 1 ] ; cout << um [ r ] - um [ l - 1 ] << " STRNEWLINE " ; } } int main ( ) { int N = 8 ; Node * root = newNode ( 1 ) ; root -> left = newNode ( 3 ) ; root -> left -> left = newNode ( 5 ) ; root -> left -> right = newNode ( 6 ) ; root -> right = newNode ( 2 ) ; root -> right -> right = newNode ( 4 ) ; root -> right -> right -> left = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 0 ) ; int wt [ ] = { 8 , 6 , 4 , 5 , 1 , 2 , 9 , 1 } ; vector < vector < int > > queries { { -1 , 1 } , { -2 , -1 } , { 0 , 3 } } ; solveQueries ( wt , root , queries ) ; return 0 ; } |
Check if a triplet of buildings can be selected such that the third building is taller than the first building and smaller than the second building | C ++ implementation of the above approach ; Function to check if it is possible to select three buildings that satisfy the given condition ; Stores prefix min array ; Iterate over the range [ 1 , N - 1 ] ; Stores the element from the ending in increasing order ; Iterate until j is greater than or equal to 0 ; If current array element is greater than the prefix min upto j ; Iterate while stack is not empty and top element is less than or equal to preMin [ j ] ; Remove the top element ; If stack is not empty and top element of the stack is less than the current element ; Push the arr [ j ] in stack ; If none of the above case satisfy then return " No " ; Driver code ; Input | #include <bits/stdc++.h> NEW_LINE using namespace std ; string recreationalSpot ( int arr [ ] , int N ) { if ( N < 3 ) { return " No " ; } int preMin [ N ] ; preMin [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { preMin [ i ] = min ( preMin [ i - 1 ] , arr [ i ] ) ; } stack < int > stack ; for ( int j = N - 1 ; j >= 0 ; j -- ) { if ( arr [ j ] > preMin [ j ] ) { while ( ! stack . empty ( ) && stack . top ( ) <= preMin [ j ] ) { stack . pop ( ) ; } if ( ! stack . empty ( ) && stack . top ( ) < arr [ j ] ) { return " Yes " ; } stack . push ( arr [ j ] ) ; } } return " No " ; } int main ( ) { int arr [ ] = { 4 , 7 , 11 , 5 , 13 , 2 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << recreationalSpot ( arr , size ) ; } |
Check if a number N can be expressed as the sum of powers of X or not | C ++ program for the above approach ; Function to check if the number N can be expressed as the sum of different powers of X or not ; While n is a positive number ; Find the remainder ; If rem is at least 2 , then representation is impossible ; Divide the value of N by x ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool ToCheckPowerofX ( int n , int x ) { while ( n > 0 ) { int rem = n % x ; if ( rem >= 2 ) { return false ; } n = n / x ; } return true ; } int main ( ) { int N = 10 , X = 3 ; if ( ToCheckPowerofX ( N , X ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Find the maximum between N and the number formed by reversing 32 | C ++ program for tha above approach ; Function that obtains the number using said operations from N ; Stores the binary representation of the number N ; Find the binary representation of the number N ; Check for the set bits ; Reverse the string S ; Stores the obtained number ; Calculating the decimal value ; Check for set bits ; Function to find the maximum value between N and the obtained number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int reverseBin ( int N ) { string S = " " ; int i ; for ( i = 0 ; i < 32 ; i ++ ) { if ( N & ( 1LL << i ) ) S += '1' ; else S += '0' ; } reverse ( S . begin ( ) , S . end ( ) ) ; int M = 0 ; for ( i = 0 ; i < 32 ; i ++ ) { if ( S [ i ] == '1' ) M += ( 1LL << i ) ; } return M ; } int maximumOfTwo ( int N ) { int M = reverseBin ( N ) ; return max ( N , M ) ; } int main ( ) { int N = 6 ; cout << maximumOfTwo ( N ) ; return 0 ; } |
Sum of Euler Totient Functions obtained for each divisor of N | C ++ program for the above approach ; Function to find the sum of Euler Totient Function of divisors of N ; Return the value of N ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int sumOfDivisors ( int N ) { return N ; } int main ( ) { int N = 5 ; cout << sumOfDivisors ( N ) ; return 0 ; } |
Square root of two Complex Numbers | C ++ program for the above approach ; Function to find the square root of a complex number ; Stores all the square roots ; Stores the first square root ; Push the square root in the ans ; Stores the second square root ; If X2 is not 0 ; Push the square root in the array ans [ ] ; Stores the third square root ; If X3 is greater than 0 ; Push the square root in the array ans [ ] ; Stores the fourth square root ; Push the square root in the array ans [ ] ; Prints the square roots ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void complexRoot ( int A , int B ) { vector < pair < double , double > > ans ; double X1 = abs ( sqrt ( ( A + sqrt ( A * A + B * B ) ) / 2 ) ) ; double Y1 = B / ( 2 * X1 ) ; ans . push_back ( { X1 , Y1 } ) ; double X2 = -1 * X1 ; double Y2 = B / ( 2 * X2 ) ; if ( X2 != 0 ) { ans . push_back ( { X2 , Y2 } ) ; } double X3 = ( A - sqrt ( A * A + B * B ) ) / 2 ; if ( X3 > 0 ) { X3 = abs ( sqrt ( X3 ) ) ; double Y3 = B / ( 2 * X3 ) ; ans . push_back ( { X3 , Y3 } ) ; double X4 = -1 * X3 ; double Y4 = B / ( 2 * X4 ) ; if ( X4 != 0 ) { ans . push_back ( { X4 , Y4 } ) ; } } cout << " The β Square β roots β are : β " << endl ; for ( auto p : ans ) { cout << p . first ; if ( p . second > 0 ) cout << " + " ; if ( p . second ) cout << p . second << " * i " << endl ; else cout << endl ; } } int main ( ) { int A = 0 , B = 1 ; complexRoot ( A , B ) ; return 0 ; } |
Minimum time required to schedule K processes | C ++ program for the above approach ; Function to find minimum required time to schedule all process ; Stores max element from A [ ] ; Find the maximum element ; Stores frequency of each element ; Stores minimum time required to schedule all process ; Count frequencies of elements ; Find the minimum time ; Decrease the value of K ; Increment tmp [ i / 2 ] ; Increment the count ; Return count , if all process are scheduled ; Increment count ; Return the count ; If it is not possible to schedule all process ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minTime ( int A [ ] , int n , int K ) { int max_ability = A [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { max_ability = max ( max_ability , A [ i ] ) ; } int tmp [ max_ability + 1 ] = { 0 } ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { tmp [ A [ i ] ] ++ ; } for ( int i = max_ability ; i >= 0 ; i -- ) { if ( tmp [ i ] != 0 ) { if ( tmp [ i ] * i < K ) { K -= ( i * tmp [ i ] ) ; tmp [ i / 2 ] += tmp [ i ] ; count += tmp [ i ] ; if ( K <= 0 ) { return count ; } } else { if ( K % i != 0 ) { count += ( K / i ) + 1 ; } else { count += ( K / i ) ; } return count ; } } } return -1 ; } int main ( ) { int arr [ ] = { 3 , 1 , 7 , 2 , 4 } ; int N = 5 ; int K = 15 ; cout << minTime ( arr , N , K ) ; return 0 ; } |
Minimum length of a rod that can be split into N equal parts that can further be split into given number of equal parts | C ++ program for the above approach ; Function to find GCD of two numbers a and b ; Base Case ; Find GCD recursively ; Function to find the LCM of the resultant array ; Initialize a variable ans as the first element ; Traverse the array ; Update LCM ; Return the minimum length of the rod ; Function to find the minimum length of the rod that can be divided into N equals parts and each part can be further divided into arr [ i ] equal parts ; Print the result ; 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 findlcm ( int arr [ ] , int n ) { int ans = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { ans = ( ( ( arr [ i ] * ans ) ) / ( gcd ( arr [ i ] , ans ) ) ) ; } return ans ; } void minimumRod ( int A [ ] , int N ) { cout << N * findlcm ( A , N ) ; } int main ( ) { int arr [ ] = { 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumRod ( arr , N ) ; return 0 ; } |
Check if N can be represented as sum of positive integers containing digit D at least once | C ++ program for the above approach ; Function to check if N contains digit D in it ; Iterate until N is positive ; Find the last digit ; If the last digit is the same as digit D ; Return false ; Function to check if the value of N can be represented as sum of integers having digit d in it ; Iterate until N is positive ; Check if N contains digit D or not ; Subtracting D from N ; Return false ; Driver Code | #include <iostream> NEW_LINE using namespace std ; bool findDigit ( int N , int D ) { while ( N > 0 ) { int a = N % 10 ; if ( a == D ) { return true ; } N /= 10 ; } return false ; } bool check ( int N , int D ) { while ( N > 0 ) { if ( findDigit ( N , D ) == true ) { return true ; } N -= D ; } return false ; } int main ( ) { int N = 24 ; int D = 7 ; if ( check ( N , D ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Number of relations that are neither Reflexive nor Irreflexive on a Set | C ++ program for the above approach ; Function to calculate x ^ y modulo 10 ^ 9 + 7 in O ( log y ) ; Stores the result of ( x ^ y ) ; Update x , if it exceeds mod ; If x is divisible by mod ; If y is odd , then multiply x with res ; Divide y by 2 ; Update the value of x ; Return the value of x ^ y ; Function to count the number of relations that are neither reflexive nor irreflexive ; Return the resultant count ; 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 ; } void countRelations ( int N ) { cout << ( power ( 2 , N ) - 2 ) * power ( 2 , N * N - N ) ; } int main ( ) { int N = 2 ; countRelations ( N ) ; return 0 ; } |
Minimum operations required to make all elements in an array of first N odd numbers equal | C ++ program for the above approach ; Function to find the minimum number of operations required to make the array elements equal ; Stores the array elements ; Stores the sum of the array ; Iterate over the range [ 0 , N ] ; Update the value arr [ i ] ; Increment the sum by the value arr [ i ] ; Stores the middle element ; If N is even ; Otherwise ; Stores the result ; Traverse the range [ 0 , N / 2 ] ; Update the value of ans ; Return the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int N ) { int arr [ N ] ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = ( 2 * i ) + 1 ; sum = sum + arr [ i ] ; } int mid = 0 ; if ( N % 2 == 0 ) { mid = sum / N ; } else { mid = arr [ N / 2 ] ; } int ans = 0 ; for ( int i = 0 ; i < N / 2 ; i ++ ) { ans += mid - arr [ i ] ; } return ans ; } int main ( ) { int N = 6 ; cout << minOperations ( N ) ; return 0 ; } |
Minimum operations required to make all elements in an array of first N odd numbers equal | C ++ code for the above approach ; Function to find the minimum number of operations required to make the array elements equal ; If the value of N is even ; Return the value ; Otherwise , N is odd ; Return the value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperation ( int N ) { if ( N % 2 == 0 ) { return ( N / 2 ) * ( N / 2 ) ; } int k = ( N - 1 ) / 2 ; return k * ( k + 1 ) ; } int main ( ) { int N = 6 ; cout << minOperation ( N ) ; return 0 ; } |
Bitwise XOR of Bitwise AND of all pairs from two given arrays | C ++ program for the above approach ; Function to find the Bitwise XOR of Bitwise AND of all pairs from the arrays arr1 [ ] and arr2 [ ] ; Stores the result ; Iterate over the range [ 0 , N - 1 ] ; Iterate over the range [ 0 , M - 1 ] ; Stores Bitwise AND of the pair { arr1 [ i ] , arr2 [ j ] } ; Update res ; Return the res ; Driver Code ; Input | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findXORS ( int arr1 [ ] , int arr2 [ ] , int N , int M ) { int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { int temp = arr1 [ i ] & arr2 [ j ] ; res ^= temp ; } } return res ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 3 } ; int arr2 [ ] = { 6 , 5 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int M = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << findXORS ( arr1 , arr2 , N , M ) ; return 0 ; } |
Bitwise XOR of Bitwise AND of all pairs from two given arrays | C ++ program for the above approach ; Function to find the Bitwise XOR of Bitwise AND of all pairs from the arrays arr1 [ ] and arr2 [ ] ; Stores XOR of array arr1 [ ] ; Stores XOR of array arr2 [ ] ; Traverse the array arr1 [ ] ; Traverse the array arr2 [ ] ; Return the result ; Driver Code ; Input | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findXORS ( int arr1 [ ] , int arr2 [ ] , int N , int M ) { int XORS1 = 0 ; int XORS2 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { XORS1 ^= arr1 [ i ] ; } for ( int i = 0 ; i < M ; i ++ ) { XORS2 ^= arr2 [ i ] ; } return XORS1 and XORS2 ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 3 } ; int arr2 [ ] = { 6 , 5 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int M = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << findXORS ( arr1 , arr2 , N , M ) ; return 0 ; } |
Count numbers up to N that cannot be expressed as sum of at least two consecutive positive integers | C ++ program for the above approach ; Function to check if a number can be expressed as a power of 2 ; f N is power of two ; Function to count numbers that cannot be expressed as sum of two or more consecutive + ve integers ; Stores the resultant count of integers ; Iterate over the range [ 1 , N ] ; Check if i is power of 2 ; Increment the count if i is not power of 2 ; Print the value of count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerof2 ( unsigned int n ) { return ( ( n & ( n - 1 ) ) && n ) ; } void countNum ( int N ) { int count = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { bool flag = isPowerof2 ( i ) ; if ( ! flag ) { count ++ ; } } cout << count << " STRNEWLINE " ; } int main ( ) { int N = 100 ; countNum ( N ) ; return 0 ; } |
Count numbers up to N that cannot be expressed as sum of at least two consecutive positive integers | C ++ program for the above approach ; Function to count numbers that cannot be expressed as sum of two or more consecutive + ve integers ; Stores the count of such numbers ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countNum ( int N ) { int ans = log2 ( N ) + 1 ; cout << ans << " STRNEWLINE " ; } int main ( ) { int N = 100 ; countNum ( N ) ; return 0 ; } |
Partition a Linked List into K continuous groups with difference in their sizes at most 1 | C ++ program for the above approach ; Link List Node ; Function to insert a node into the Linked List ; Allocate a new dynamic node ; Update new_node -> val ; Stores the head_ref ; Update ( * head_ref ) ; Function to split the linked list in K groups ; Stores the K groups ; If head is NULL ; Iterate until K is non - zero ; Stores the length of the linked list ; Stores the head node of the linked list ; Iterate over the linked list ; Update p ; Update N ; Iterate over the linked list ; Stores the length of the current group ; Stores the current node ; Stores the previous node ; If rem is greater than 0 ; Update p ; Decrement rem by 1 ; Iterate until x is non - zero ; If the last is equal to p ; Otherwise ; Join the link between last and the current element ; Update the last node ; Update p node ; Assign NULL to last -> next ; Push the current linked list in ans ; Decrement K ; While K greater than 0 ; Update the value of ans ; Increment K ; Print the result ; Print the value ; Update ans [ i ] ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct ListNode { int val ; struct ListNode * next ; } ; void push ( ListNode * * head_ref , int node_val ) { ListNode * new_node = new ListNode ( ) ; new_node -> val = node_val ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void splitListInParts ( ListNode * head , int K ) { vector < ListNode * > ans ; if ( ! head ) { while ( K -- ) ans . push_back ( NULL ) ; } int N = 0 ; ListNode * p = head ; while ( p ) { p = p -> next ; N ++ ; } int len = N / K ; int rem = N % K ; p = head ; while ( K > 0 && p ) { int x = len ; ListNode * curr_head = p ; ListNode * last = p ; if ( rem > 0 ) { p = p -> next ; rem -- ; } while ( x -- ) { if ( last == p ) p = p -> next ; else { last -> next = p ; last = p ; p = p -> next ; } } last -> next = NULL ; ans . push_back ( curr_head ) ; K -- ; } while ( K > 0 ) { ans . push_back ( NULL ) ; K -- ; } cout << " { " ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { cout << " { " ; while ( ans [ i ] ) { cout << ans [ i ] -> val << " β " ; ans [ i ] = ans [ i ] -> next ; } cout << " } " ; if ( i != ans . size ( ) - 1 ) cout << " , β " ; } cout << " } " ; } int main ( ) { ListNode * root = NULL ; push ( & root , 8 ) ; push ( & root , 7 ) ; push ( & root , 6 ) ; push ( & root , 5 ) ; push ( & root , 4 ) ; push ( & root , 3 ) ; push ( & root , 2 ) ; push ( & root , 1 ) ; int K = 3 ; splitListInParts ( root , K ) ; return 0 ; } |
Replace array elements that contains K as a digit with the nearest power of K | C ++ program for the above approach ; Function to calculate the power of base nearest to x ; Stores logX to the base K ; Function to replace array elements with nearest power of K ; Traverse the array ; Convert integer into a string ; If K is found , then replace with the nearest power of K ; Print the array ; Driver Code ; Given array ; Given value of K ; Function call to replace array elements with nearest power of K | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nearestPow ( int x , int base ) { int k = int ( log ( x ) / log ( base ) ) ; if ( abs ( pow ( base , k ) - x ) < abs ( pow ( base , ( k + 1 ) ) - x ) ) return pow ( base , k ) ; else return pow ( base , ( k + 1 ) ) ; } void replaceWithNearestPowerOfK ( int arr [ ] , int K , int n ) { for ( int i = 0 ; i < n ; i ++ ) { string strEle = to_string ( arr [ i ] ) ; for ( int c = 0 ; c < strEle . length ( ) ; c ++ ) { if ( ( strEle - '0' ) == K ) { arr [ i ] = nearestPow ( arr [ i ] , K ) ; break ; } } } for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 432 , 953 , 232 , 333 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; replaceWithNearestPowerOfK ( arr , K , n ) ; } |
Difference between ceil of array sum divided by K and sum of ceil of array elements divided by K | C ++ program for the above approach ; Function to find absolute difference between array sum divided by x and sum of ceil of array elements divided by x ; Stores the total sum ; Stores the sum of ceil of array elements divided by x ; Traverse the array ; Adding each array element ; Add the value ceil of arr [ i ] / x ; Find the ceil of the total sum divided by x ; Return absolute difference ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ceilDifference ( int arr [ ] , int n , int x ) { int totalSum = 0 ; int perElementSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { totalSum += arr [ i ] ; perElementSum += ceil ( ( double ) ( arr [ i ] ) / ( double ) ( x ) ) ; } int totalCeilSum = ceil ( ( double ) ( totalSum ) / ( double ) ( x ) ) ; return abs ( perElementSum - totalCeilSum ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int K = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ceilDifference ( arr , N , K ) ; return 0 ; } |
Remove trailing zeros from the sum of two numbers ( Using Stack ) | C ++ program for the above approach ; Function to remove trailing zeros from the sum of two numbers ; Stores the sum of A and B ; Stores the digits ; Stores the equivalent string of integer N ; Traverse the string ; Push the digit at i in the stack ; While top element is '0' ; Pop the top element ; Stores the resultant number without tailing 0 's ; While s is not empty ; Append top element of S in res ; Pop the top element of S ; Reverse the string res ; Driver Code ; Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; string removeTailing ( int A , int B ) { int N = A + B ; stack < int > s ; string strsum = to_string ( N ) ; for ( int i = 0 ; i < strsum . length ( ) ; i ++ ) { s . push ( strsum [ i ] ) ; } while ( s . top ( ) == '0' ) s . pop ( ) ; string res = " " ; while ( ! s . empty ( ) ) { res = res + char ( s . top ( ) ) ; s . pop ( ) ; } reverse ( res . begin ( ) , res . end ( ) ) ; return res ; } int main ( ) { int A = 130246 , B = 450164 ; cout << removeTailing ( A , B ) ; return 0 ; } |
Count number of triplets with product not exceeding a given number | C ++ program for the above approach ; Function to count the number of triplets whose product is at most N ; Stores the count of triplets ; Iterate over the range [ 0 , N ] ; Iterate over the range [ 0 , N ] ; If the product of pairs exceeds N ; Increment the count of possible triplets ; Return the total count ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int countTriplets ( int N ) { int ans = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ ) { if ( i * j > N ) break ; ans += N / ( i * j ) ; } } return ans ; } int main ( ) { int N = 10 ; cout << countTriplets ( N ) ; return 0 ; } |
Sum of an Infinite Geometric Progression ( GP ) | C ++ program for the above approach ; Function to calculate the sum of an infinite Geometric Progression ; Case for Infinite Sum ; Store the sum of GP Series ; Print the value of sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSumOfGP ( double a , double r ) { if ( abs ( r ) >= 1 ) { cout << " Infinite " ; return ; } double sum = a / ( 1 - r ) ; cout << sum ; } int main ( ) { double A = 1 , R = 0.5 ; findSumOfGP ( A , R ) ; return 0 ; } |
Number of Relations that are both Irreflexive and Antisymmetric on a Set | C ++ program for the above approach ; Function to calculate x ^ y % mod in O ( log y ) ; Stores the result of x ^ y ; Update x if it exceeds 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 relations that are irreflexive and antisymmetric in a set consisting of N elements ; Return the resultant count ; Driver Code | #include <iostream> NEW_LINE using namespace std ; const int mod = 1000000007 ; int power ( long long x , unsigned int y ) { int res = 1 ; x = x % mod ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % mod ; y = y >> 1 ; x = ( x * x ) % mod ; } return res ; } int numberOfRelations ( int N ) { return power ( 3 , ( N * N - N ) / 2 ) ; } int main ( ) { int N = 2 ; cout << numberOfRelations ( N ) ; return 0 ; } |
Count of numbers up to N having at least one prime factor common with N | C ++ program for the above approach ; Function to count all the numbers in the range [ 1 , N ] having common factor with N other than 1 ; Stores the count of numbers having more than 1 factor with N ; Iterate over the range [ 1 , N ] ; If gcd is not 1 then increment the count ; Print 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 <= N ; i ++ ) { if ( __gcd ( i , N ) != 1 ) count ++ ; } cout << count ; } int main ( ) { int N = 5 ; countNumbers ( N ) ; return 0 ; } |
Count of numbers up to N having at least one prime factor common with N | C ++ program for the above approach ; Function to calculate the value of Euler 's totient function ; Initialize result with N ; Find all prime factors of N and subtract their multiples ; Check if p is a prime factor ; If found to be true , then update N and result ; If N has a prime factor greater than sqrt ( N ) , then there can be at - most one such prime factor ; Function to count all the numbers in the range [ 1 , N ] having common factor with N other than 1 ; Stores the resultant count ; Print the count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int phi ( int N ) { int result = N ; for ( int p = 2 ; p * p <= N ; ++ p ) { if ( N % p == 0 ) { while ( N % p == 0 ) N /= p ; result -= result / p ; } } if ( N > 1 ) result -= result / N ; return result ; } int countNumbers ( int N ) { int count = N - phi ( N ) ; cout << count ; } int main ( ) { int N = 5 ; countNumbers ( N ) ; return 0 ; } |
Queries to update array by adding or multiplying array elements and print the element present at specified index | C ++ program for the above approach ; Function to modify the array by performing given queries ; Stores the multiplication of all integers of type 1 ; Stores the value obtained after performing queries of type 1 & 2 ; Iterate over the queries ; Query of type 0 ; Update the value of add ; Query of type 1 ; Update the value of mul ; Update the value of add ; Otherwise ; Store the element at index Q [ i ] [ 1 ] ; Print the result for the current query ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void Query ( int arr [ ] , int N , vector < vector < int > > Q ) { int mul = 1 ; int add = 0 ; for ( int i = 0 ; i < Q . size ( ) ; i ++ ) { if ( Q [ i ] [ 0 ] == 0 ) { add = add + Q [ i ] [ 1 ] ; } else if ( Q [ i ] [ 0 ] == 1 ) { mul = mul * Q [ i ] [ 1 ] ; add = add * Q [ i ] [ 1 ] ; } else { int ans = arr [ Q [ i ] [ 1 ] ] * mul + add ; cout << ans << " β " ; } } } int main ( ) { int arr [ ] = { 3 , 1 , 23 , 45 , 100 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < vector < int > > Q = { { 1 , 2 } , { 0 , 10 } , { 2 , 3 } , { 1 , 5 } , { 2 , 4 } } ; Query ( arr , N , Q ) ; return 0 ; } |
Minimize cost of converting all array elements to Fibonacci Numbers | C ++ program for the above approach ; Function to find the N - th Fibonacci Number ; Find the value of a , b , and r ; Find the N - th Fibonacci ; Return the result ; Function to find the Fibonacci number which is nearest to X ; Calculate the value of n for X ; Return the nearest Fibonacci Number ; Function to find the minimum cost to convert all array elements to Fibonacci Numbers ; Stores the total minimum cost ; Traverse the given array arr [ ] ; Find the nearest Fibonacci Number ; Add the cost ; Return the final cost ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nthFibo ( int n ) { double a = ( pow ( 5 , 0.5 ) + 1 ) / 2 ; double b = ( -1 * ( pow ( 5 , 0.5 ) ) + 1 ) / 2 ; double r = pow ( 5 , 0.5 ) ; double ans = ( pow ( a , n ) - pow ( b , n ) ) / r ; return int ( ans ) ; } int nearFibo ( int X ) { double a = ( pow ( 5 , 0.5 ) + 1 ) / 2 ; int n = int ( log ( ( pow ( 5 , 0.5 ) ) * X ) / log ( a ) ) ; int nth = nthFibo ( n ) ; int nplus = nthFibo ( n + 1 ) ; if ( abs ( X - nth ) < abs ( X - nplus ) ) return nth ; else return nplus ; } int getCost ( int arr [ ] , int n ) { int cost = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int fibo = nearFibo ( arr [ i ] ) ; cost += abs ( arr [ i ] - fibo ) ; } return cost ; } int main ( ) { int arr [ ] = { 56 , 34 , 23 , 98 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( getCost ( arr , n ) ) ; } |
Maximum sum of pairs that are at least K distance apart in an array | C ++ program for the above approach ; Function to find the largest sum pair that are K distant apart ; Stores the prefix maximum array ; Base Case ; Traverse the array and update the maximum value upto index i ; Stores the maximum sum of pairs ; Iterate over the range [ K , N ] ; Find the maximum value of the sum of valid pairs ; Return the resultant sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxPairSum ( int arr [ ] , int N , int K ) { int preMax [ N ] ; preMax [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { preMax [ i ] = max ( preMax [ i - 1 ] , arr [ i ] ) ; } int res = INT_MIN ; for ( int i = K ; i < N ; i ++ ) { res = max ( res , arr [ i ] + preMax [ i - K ] ) ; } return res ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 8 , 6 , 3 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getMaxPairSum ( arr , N , K ) ; return 0 ; } |
Program to calculate sum of an Infinite Arithmetic | C ++ program for the above approach ; Function to find the sum of the infinite AGP ; Stores the sum of infinite AGP ; Print the required sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sumOfInfiniteAGP ( double a , double d , double r ) { double ans = a / ( 1 - r ) + ( d * r ) / ( 1 - r * r ) ; cout << ans ; } int main ( ) { double a = 0 , d = 1 , r = 0.5 ; sumOfInfiniteAGP ( a , d , r ) ; return 0 ; } |
Count pairs from an array having GCD equal to the minimum element in the pair | C ++ program for the above approach ; Function to count pairs from an array having GCD equal to minimum element of that pair ; Stores the resultant count ; Iterate over the range [ 0 , N - 2 ] ; Iterate over the range [ i + 1 , N ] ; If arr [ i ] % arr [ j ] is 0 or arr [ j ] % arr [ i ] is 0 ; Increment count by 1 ; Return the resultant count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int N ) { int count = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( arr [ i ] % arr [ j ] == 0 arr [ j ] % arr [ i ] == 0 ) { count ++ ; } } } return count ; } int main ( ) { int arr [ ] = { 2 , 3 , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; } |
Count pairs from an array having GCD equal to the minimum element in the pair | C ++ program for the above approach ; Function to count pairs from an array having GCD equal to minimum element of that pair ; Stores the resultant count ; Stores the frequency of each array element ; Traverse the array arr [ ] ; Iterate over the Map mp ; Stores the array element ; Stores the count of array element x ; If x is 1 ; Increment res by N - 1 ; Increment res by yC2 ; Iterate over the range [ 2 , sqrt ( x ) ] ; If x is divisible by j ; Increment the value of res by mp [ j ] ; If j is not equal to x / j ; Increment res by mp [ x / j ] ; Return the resultant count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountPairs ( int arr [ ] , int N ) { int res = 0 ; map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } for ( auto p : mp ) { int x = p . first ; int y = p . second ; if ( x == 1 ) { res += N - 1 ; continue ; } res += ( y * ( y - 1 ) ) / 2 ; for ( int j = 2 ; j <= sqrt ( x ) ; j ++ ) { if ( x % j == 0 ) { res += mp [ j ] ; if ( j != x / j ) res += mp [ x / j ] ; } } } return res ; } int main ( ) { int arr [ ] = { 2 , 3 , 1 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CountPairs ( arr , N ) ; return 0 ; } |
Product of count of set bits present in binary representations of elements in an array | C ++ program for the above approach ; Function to count the set bits in an integer ; Stores the count of set bits ; Iterate while N is not equal to 0 ; Increment count by 1 ; Divide N by 2 ; Return the total count obtained ; Function to find the product of count of set bits present in each element of an array ; Stores the resultant product ; Traverse the array arr [ ] ; Stores the count of set bits of arr [ i ] ; Update the product ; Return the resultant product ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countbits ( int n ) { int count = 0 ; while ( n != 0 ) { if ( n & 1 ) count ++ ; n = n / 2 ; } return count ; } int BitProduct ( int arr [ ] , int N ) { int product = 1 ; for ( int i = 0 ; i < N ; i ++ ) { int bits = countbits ( arr [ i ] ) ; product *= bits ; } return product ; } int main ( ) { int arr [ ] = { 3 , 2 , 4 , 1 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << BitProduct ( arr , N ) ; return 0 ; } |
Queries to calculate sum of array elements consisting of odd number of divisors | C ++ program for the above approach ; Function to get the middle index from the given ranges ; Recursive function to find the sum of values in the given range of the array ; If segment of this node is a part of given range , then return the sum of the segment ; If segment of this node is outside the given range ; If a part of this segment overlaps the given range ; Function to find the sum of elements in the range from index qs ( querystart ) to qe ( query end ) ; Invalid ranges ; Recursive function to construct the Segment Tree for array [ ss . . se ] . si is index of current node in tree st ; If there is one element in the array ; Recur for left and right subtrees and store the sum of values in this node ; Function to construct segment tree from the given array ; Allocate memory for the segment tree Height of segment tree ; Maximum size of segment tree ; Allocate memory ; Fill the allocated memory st ; Return the constructed segment tree ; Function to find the sum of elements having odd number of divisors in index range [ L , R ] for Q queries ; Traverse the array , arr [ ] ; Replace elements that are not perfect squares with 0 ; Build segment tree from the given array ; Iterate through all the queries ; Print sum of values in array from index l to r ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMid ( int s , int e ) { return s + ( e - s ) / 2 ; } int getSumUtil ( int * st , int ss , int se , int qs , int qe , int si ) { if ( qs <= ss && qe >= se ) return st [ si ] ; if ( se < qs ss > qe ) return 0 ; int mid = getMid ( ss , se ) ; return getSumUtil ( st , ss , mid , qs , qe , 2 * si + 1 ) + getSumUtil ( st , mid + 1 , se , qs , qe , 2 * si + 2 ) ; } int getSum ( int * st , int n , int qs , int qe ) { if ( qs < 0 qe > n - 1 qs > qe ) { cout << " Invalid β Input " ; return -1 ; } return getSumUtil ( st , 0 , n - 1 , qs , qe , 0 ) ; } int constructSTUtil ( int arr [ ] , int ss , int se , int * st , int si ) { if ( ss == se ) { st [ si ] = arr [ ss ] ; return arr [ ss ] ; } int mid = getMid ( ss , se ) ; st [ si ] = constructSTUtil ( arr , ss , mid , st , si * 2 + 1 ) + constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 ) ; return st [ si ] ; } int * constructST ( int arr [ ] , int n ) { int x = ( int ) ( ceil ( log2 ( n ) ) ) ; int max_size = 2 * ( int ) pow ( 2 , x ) - 1 ; int * st = new int [ max_size ] ; constructSTUtil ( arr , 0 , n - 1 , st , 0 ) ; return st ; } void OddDivisorsSum ( int n , int q , int arr [ ] , vector < pair < int , int > > Query ) { for ( int i = 0 ; i < n ; i ++ ) { int sq = sqrt ( arr [ i ] ) ; if ( sq * sq != arr [ i ] ) arr [ i ] = 0 ; } int * st = constructST ( arr , n ) ; for ( int i = 0 ; i < q ; i ++ ) { int l = Query [ i ] . first ; int r = Query [ i ] . second ; cout << getSum ( st , n , l , r ) << " β " ; } } int main ( ) { int arr [ ] = { 2 , 4 , 5 , 6 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int Q = 3 ; vector < pair < int , int > > Query = { { 0 , 2 } , { 1 , 3 } , { 1 , 4 } } ; OddDivisorsSum ( N , Q , arr , Query ) ; return 0 ; } |
Queries to calculate sum of array elements consisting of odd number of divisors | C ++ program for the above approach ; Function to find the sum of elements having odd number of divisors in index range [ L , R ] for Q queries ; Initialize the dp [ ] array ; Traverse the array , arr [ ] ; If a [ i ] is a perfect square , then update value of DP [ i ] to a [ i ] ; Find the prefix sum of DP [ ] array ; Iterate through all the queries ; Find the sum for each query ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void OddDivisorsSum ( int n , int q , int a [ ] , vector < pair < int , int > > Query ) { int DP [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int x = sqrt ( a [ i ] ) ; if ( x * x == a [ i ] ) DP [ i ] = a [ i ] ; } for ( int i = 1 ; i < n ; i ++ ) { DP [ i ] = DP [ i - 1 ] + DP [ i ] ; } for ( int i = 0 ; i < q ; i ++ ) { int l = Query [ i ] . first ; int r = Query [ i ] . second ; if ( l == 0 ) { cout << DP [ r ] << " β " ; } else { cout << DP [ r ] - DP [ l - 1 ] << " β " ; } } } int main ( ) { int arr [ ] = { 2 , 4 , 5 , 6 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int Q = 3 ; vector < pair < int , int > > Query = { { 0 , 2 } , { 1 , 3 } , { 1 , 4 } } ; OddDivisorsSum ( N , Q , arr , Query ) ; return 0 ; } |
Smallest subset of maximum sum possible by splitting array into two subsets | C ++ program for the above approach ; Function to split array elements into two subsets having sum of the smaller subset maximized ; Stores the size of the array ; Stores the frequency of array elements ; Stores the total sum of the array ; Stores the sum of the resultant set ; Stores if it is possible to split the array that satisfies the conditions ; Stores the elements of the first subseta ; Traverse the array arr [ ] ; Increment total sum ; Increment count of arr [ i ] ; Sort the array arr [ ] ; Stores the index of the last element of the array ; Traverse the array arr [ ] ; Stores the frequency of arr [ i ] ; If frq + ans . size ( ) is at most remaining size ; Append arr [ i ] to ans ; Decrement totSum by arr [ i ] ; Increment s by arr [ i ] ; Otherwise , decrement i by frq ; If s is greater than totSum ; Mark flag 1 ; If flag is equal to 1 ; Print the arrList ans ; Otherwise , print " - 1" ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; static void findSubset ( vector < int > arr ) { int N = arr . size ( ) ; map < int , int > mp ; int totSum = 0 ; int s = 0 ; int flag = 0 ; vector < int > ans ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { totSum += arr [ i ] ; mp [ arr [ i ] ] = mp [ arr [ i ] ] + 1 ; } sort ( arr . begin ( ) , arr . end ( ) ) ; int i = N - 1 ; while ( i >= 0 ) { int frq = mp [ arr [ i ] ] ; if ( ( frq + ans . size ( ) ) < ( N - ( frq + ans . size ( ) ) ) ) { for ( int k = 0 ; k < frq ; k ++ ) { ans . push_back ( arr [ i ] ) ; totSum -= arr [ i ] ; s += arr [ i ] ; i -- ; } } else { i -= frq ; } if ( s > totSum ) { flag = 1 ; break ; } } if ( flag == 1 ) { for ( i = ans . size ( ) - 1 ; i >= 0 ; i -- ) { cout << ans [ i ] << " β " ; } } else { cout << -1 ; } } int main ( ) { vector < int > arr = { 5 , 3 , 2 , 4 , 1 , 2 } ; findSubset ( arr ) ; } |
Minimize Bitwise XOR of array elements with 1 required to make sum of array at least K | C ++ program for the above approach ; Function to find minimum number of Bitwise XOR of array elements with 1 required to make sum of the array at least K ; Stores the count of even array elements ; Stores sum of the array ; Traverse the array arr [ ] ; Increment sum ; If array element is even ; Increase count of even ; If S is at least K ; If S + E is less than K ; Otherwise , moves = K - S ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minStepK ( int arr [ ] , int N , int K ) { int E = 0 ; int S = 0 ; for ( int i = 0 ; i < N ; i ++ ) { S += arr [ i ] ; if ( arr [ i ] % 2 == 0 ) E += 1 ; } if ( S >= K ) return 0 ; else if ( S + E < K ) return -1 ; else return K - S ; } int main ( ) { int arr [ ] = { 0 , 1 , 1 , 0 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 4 ; cout << minStepK ( arr , N , K ) ; return 0 ; } |
Maximize difference between odd and even | C ++ program for the above approach ; Function to find maximum and minimum value of a number that can be obtained by rotating bits ; Stores the value of N ; Stores the maximum value ; Stores the minimum value ; If temp is odd ; Update the maximum and the minimum value ; If flag is 1 , then return the maximum value ; Otherwise , return the maximum value ; Function to find the maximum difference between the sum of odd and even - indexed array elements possible by rotating bits ; Stores the maximum difference ; Stores the sum of elements present at odd indices ; Stores the sum of elements present at even indices ; Traverse the given array ; If the index is even ; Update the caseOne ; Stores the maximum difference ; Stores the sum of elements placed at odd positions ; Stores the sum of elements placed at even positions ; Traverse the array ; If the index is even ; Update the caseTwo ; Return the maximum of caseOne and caseTwo ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Rotate ( int n , int f ) { int temp = n ; int maxi = n ; int mini = n ; for ( int idx = 0 ; idx < 7 ; idx ++ ) { if ( temp & 1 ) { temp >>= 1 ; temp += pow ( 2 , 7 ) ; } else temp >>= 1 ; mini = min ( mini , temp ) ; maxi = max ( maxi , temp ) ; } if ( f ) return ( maxi ) ; else return ( mini ) ; } int calcMinDiff ( int arr [ ] , int n ) { int caseOne = 0 ; int sumOfodd = 0 ; int sumOfeven = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 ) sumOfodd += Rotate ( arr [ i ] , 0 ) ; else sumOfeven += Rotate ( arr [ i ] , 1 ) ; } caseOne = abs ( sumOfodd - sumOfeven ) ; int caseTwo = 0 ; sumOfodd = 0 ; sumOfeven = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 ) sumOfodd += Rotate ( arr [ i ] , 1 ) ; else sumOfeven += Rotate ( arr [ i ] , 0 ) ; } caseTwo = abs ( sumOfodd - sumOfeven ) ; return max ( caseOne , caseTwo ) ; } int main ( ) { int arr [ ] = { 123 , 86 , 234 , 189 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( calcMinDiff ( arr , n ) ) ; } |
Array element with minimum sum of absolute differences | Set 2 | C ++ program for the above approach ; Function to find the element with minimum sum of differences between any elements in the array ; Stores the required X and sum of absolute differences ; Calculate sum of array elements ; The sum of absolute differences can 't be greater than sum ; Update res that gives the minimum sum ; If the current difference is less than the previous difference ; Update min_diff and res ; Print the resultant value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumDiff ( int arr [ ] , int N ) { int res = arr [ 0 ] , sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; int min_diff = sum ; for ( int i = 0 ; i < N ; i ++ ) { if ( abs ( sum - ( arr [ i ] * N ) ) < min_diff ) { min_diff = abs ( sum - ( arr [ i ] * N ) ) ; res = arr [ i ] ; } } cout << res ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumDiff ( arr , N ) ; return 0 ; } |
Subsets and Splits