text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Minimize cost required to complete all processes | C ++ program to implement the above approach ; Function to find minimum cost required to complete all the process ; Sort the array on descending order of Y ; Stores length of array ; Stores minimum cost required to complete all the process ; Stores minimum cost to initiate any process ; Traverse the array ; If minCostInit is less than the cost to initiate the process ; Update minCost ; Update minCostInit ; Update minCostInit ; Return minCost ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool func ( pair < int , int > i1 , pair < int , int > i2 ) { return ( i1 . first - i1 . second < i2 . first - i2 . second ) ; } int minimumCostReqToCompthePrcess ( vector < pair < int , int > > arr ) { sort ( arr . begin ( ) , arr . end ( ) , func ) ; int n = arr . size ( ) ; int minCost = 0 ; int minCostInit = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] . second > minCostInit ) { minCost += ( arr [ i ] . second - minCostInit ) ; minCostInit = arr [ i ] . second ; } minCostInit -= arr [ i ] . first ; } return minCost ; } int main ( ) { vector < pair < int , int > > arr = { { 1 , 2 } , { 2 , 4 } , { 4 , 8 } } ; cout << ( minimumCostReqToCompthePrcess ( arr ) ) ; } |
Split array into equal length subsets with maximum sum of Kth largest element of each subset | C ++ program to implement the above approach ; Function to find the maximum sum of Kth largest element of M equal length partition ; Stores sum of K_th largest element of equal length partitions ; If N is not divisible by M ; Stores length of each partition ; If K is greater than length of partition ; Sort array in descending porder ; Traverse the array ; Update maxSum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumKthLargestsumPart ( int arr [ ] , int N , int M , int K ) { int maxSum = 0 ; if ( N % M ) return -1 ; int sz = ( N / M ) ; if ( K > sz ) return -1 ; sort ( arr , arr + N , greater < int > ( ) ) ; for ( int i = 1 ; i <= M ; i ++ ) { maxSum += arr [ i * K - 1 ] ; } return maxSum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int M = 2 ; int K = 1 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumKthLargestsumPart ( arr , N , M , K ) ; return 0 ; } |
Minimize difference between maximum and minimum array elements by exactly K removals | C ++ program for the above approach ; Function to minimize the difference of the maximum and minimum array elements by removing K elements ; Base Condition ; Sort the array ; Initialize left and right pointers ; Iterate for K times ; Removing right element to reduce the difference ; Removing the left element to reduce the difference ; Print the minimum difference ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void minimumRange ( int arr [ ] , int N , int K ) { if ( K >= N ) { cout << 0 ; return ; } sort ( arr , arr + N ) ; int left = 0 , right = N - 1 , i ; for ( i = 0 ; i < K ; i ++ ) { if ( arr [ right - 1 ] - arr [ left ] < arr [ right ] - arr [ left + 1 ] ) right -- ; else left ++ ; } cout << arr [ right ] - arr [ left ] ; } int main ( ) { int arr [ ] = { 5 , 10 , 12 , 14 , 21 , 54 , 61 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 4 ; minimumRange ( arr , N , K ) ; return 0 ; } |
Split array into K subsets to maximize sum of their second largest elements | C ++ program to implement the above approach ; Function to split array into K subsets having maximum sum of their second maximum elements ; Sort the array ; Stores the maximum possible sum of second maximums ; Add second maximum of current subset ; Proceed to the second maximum of next subset ; Print the maximum sum obtained ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void splitArray ( int arr [ ] , int n , int K ) { sort ( arr , arr + n ) ; int i = n - 1 ; int result = 0 ; while ( K -- ) { result += arr [ i - 1 ] ; i -= 2 ; } cout << result ; } int main ( ) { int arr [ ] = { 1 , 3 , 1 , 5 , 1 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; splitArray ( arr , N , K ) ; return 0 ; } |
Count subsequences for every array element in which they are the maximum | C ++ program for the above approach ; Function to merge the subarrays arr [ l . . m ] and arr [ m + 1 , . . r ] based on indices [ ] ; If a [ indices [ l ] ] is less than a [ indices [ j ] ] , add indice [ l ] to temp ; Else add indices [ j ] ; Add remaining elements ; Add remainging elements ; Recursive function to divide the array into to parts ; Recursive call for elements before mid ; Recursive call for elements after mid ; Merge the two sorted arrays ; Function to find the number of subsequences for each element ; Sorting the indices according to array arr [ ] ; Array to store output numbers ; Initialize subseq ; B [ i ] is 2 ^ i ; Doubling the subsequences ; Print the final output , array B [ ] ; Driver Code ; Given array ; Given length ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void merge ( int * indices , int * a , int l , int mid , int r ) { int temp_ind [ r - l + 1 ] , j = mid + 1 ; int i = 0 , temp_l = l , k ; while ( l <= mid && j <= r ) { if ( a [ indices [ l ] ] < a [ indices [ j ] ] ) temp_ind [ i ++ ] = indices [ l ++ ] ; else temp_ind [ i ++ ] = indices [ j ++ ] ; } while ( l <= mid ) temp_ind [ i ++ ] = indices [ l ++ ] ; while ( j <= r ) temp_ind [ i ++ ] = indices [ j ++ ] ; for ( k = 0 ; k < i ; k ++ ) indices [ temp_l ++ ] = temp_ind [ k ] ; } void divide ( int * indices , int * a , int l , int r ) { if ( l >= r ) return ; int mid = l / 2 + r / 2 ; divide ( indices , a , l , mid ) ; divide ( indices , a , mid + 1 , r ) ; merge ( indices , a , l , mid , r ) ; } void noOfSubsequences ( int arr [ ] , int N ) { int indices [ N ] , i ; for ( i = 0 ; i < N ; i ++ ) indices [ i ] = i ; divide ( indices , arr , 0 , N - 1 ) ; int B [ N ] ; int subseq = 1 ; for ( i = 0 ; i < N ; i ++ ) { B [ indices [ i ] ] = subseq ; subseq *= 2 ; } for ( i = 0 ; i < N ; i ++ ) cout << B [ i ] << " β " ; } int main ( ) { int arr [ ] = { 2 , 3 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; noOfSubsequences ( arr , N ) ; return 0 ; } |
Find the order of execution of given N processes in Round Robin Scheduling | C ++ program for the above approach ; Function to sort the array order [ ] on the basis of the array freq [ ] ; If order [ i ] th is less than order [ temp ] th process ; Otherwise ; Add the left half to tempOrder [ ] ; Add right half to tempOrder [ ] ; Copy the tempOrder [ ] array to order [ ] array ; Utility function to sort the array order [ ] on the basis of freq [ ] ; Base Case ; Divide array into 2 parts ; Sort the left array ; Sort the right array ; Merge the sorted arrays ; Function to find the order of processes in which execution occurs ; Store the frequency ; Find elements in array freq [ ] ; Store the order of completion of processes ; Initialize order [ i ] as i ; Function Call to find the order of execution ; Print order of completion of processes ; Driver Code ; Burst Time of the processes ; Quantum Time ; Function Call | #include <iostream> NEW_LINE using namespace std ; void merge ( int * order , int * freq , int i , int mid , int j ) { int tempOrder [ j - i + 1 ] ; int temp = mid + 1 , index = -1 ; while ( i <= mid && temp <= j ) { if ( freq [ order [ i ] ] <= freq [ order [ temp ] ] ) { tempOrder [ ++ index ] = order [ i ++ ] ; } else { tempOrder [ ++ index ] = order [ temp ++ ] ; } } while ( i <= mid ) { tempOrder [ ++ index ] = order [ i ++ ] ; } while ( temp <= j ) { tempOrder [ ++ index ] = order [ temp ++ ] ; } for ( index ; index >= 0 ; index -- ) { order [ j -- ] = tempOrder [ index ] ; } } void divide ( int * order , int * freq , int i , int j ) { if ( i >= j ) return ; int mid = i / 2 + j / 2 ; divide ( order , freq , i , mid ) ; divide ( order , freq , mid + 1 , j ) ; merge ( order , freq , i , mid , j ) ; } void orderProcesses ( int A [ ] , int N , int q ) { int i = 0 ; int freq [ N ] ; for ( i = 0 ; i < N ; i ++ ) { freq [ i ] = ( A [ i ] / q ) + ( A [ i ] % q > 0 ) ; } int order [ 4 ] ; for ( i = 0 ; i < N ; i ++ ) { order [ i ] = i ; } divide ( order , freq , 0 , N - 1 ) ; for ( i = 0 ; i < N ; i ++ ) { cout << order [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 3 , 7 , 4 } ; int Q = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; orderProcesses ( arr , N , Q ) ; return 0 ; } |
Maximize cost to empty given array by repetitively removing K array elements | C ++ program to implement the above approach ; Function to find the maximum cost to remove all array elements ; Stores maximum cost to remove array elements ; Sort array in ascending order ; Traverse the array ; Update maxCost ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxCostToRemove ( int arr [ ] , int N , int K ) { int maxCost = 0 ; sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; i += K ) { maxCost += arr [ i + 1 ] ; } return maxCost ; } int main ( ) { int arr [ ] = { 1 , 3 , 4 , 1 , 5 , 1 , 5 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 4 ; cout << maxCostToRemove ( arr , N , K ) ; } |
Print all numbers up to N in words in lexicographical order | C ++ program for the above approach ; Function to convert a number to words ; Stores the digits ; Base cases ; Stores strings of unit place ; Stores strings for corner cases ; Stores strings for ten 's place digits ; Stores strings for powers of 10 ; If given number contains a single digit ; Iterate over all the digits ; Represent first 2 digits in words ; Represent last 2 digits in words ; Explicitly handle corner cases [ 10 , 19 ] ; Explicitly handle corner case 20 ; For rest of the two digit numbers i . e . , 21 to 99 ; Function to print all the numbers up to n in lexicographical order ; Convert all numbers in words ; Sort all strings ; Print answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string convert_to_words ( int n ) { char num [ 1000 ] ; string str = to_string ( n ) ; strcpy ( num , str . c_str ( ) ) ; char * arr_ptr = & num [ 0 ] ; int len = strlen ( arr_ptr ) ; string ans = " " ; if ( len == 0 ) { ans += " Empty β String " ; return ans ; } string single_digits [ ] = { " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " } ; string two_digits [ ] = { " " , " ten " , " eleven " , " twelve " , " thirteen " , " fourteen " , " fifteen " , " sixteen " , " seventeen " , " eighteen " , " nineteen " } ; string tens_multiple [ ] = { " " , " " , " twenty " , " thirty " , " forty " , " fifty " , " sixty " , " seventy " , " eighty " , " ninety " } ; string tens_power [ ] = { " hundred " , " thousand " } ; if ( len == 1 ) { ans += single_digits [ num [ 0 ] - '0' ] ; return ans ; } int x = 0 ; while ( x < len ) { if ( len >= 3 ) { if ( num [ x ] - '0' != 0 ) { ans += single_digits [ num [ x ] - '0' ] ; ans += " β " ; ans += tens_power [ len - 3 ] ; ans += " β " ; } -- len ; } else { if ( num [ x ] - '0' == 1 ) { int sum = num [ x ] - '0' + num [ x ] - '0' ; ans += two_digits [ sum ] ; return ans ; } else if ( num [ x ] - '0' == 2 && num [ x + 1 ] - '0' == 0 ) { ans += " twenty " ; return ans ; } else { int i = ( num [ x ] - '0' ) ; if ( i > 0 ) { ans += tens_multiple [ i ] ; ans += " β " ; } else ans += " " ; ++ x ; if ( num [ x ] - '0' != 0 ) ans += single_digits [ num [ x ] - '0' ] ; } } ++ x ; } return " " ; } static void lexNumbers ( int n ) { vector < string > s ; for ( int i = 1 ; i <= n ; i ++ ) { s . push_back ( convert_to_words ( i ) ) ; } sort ( s . begin ( ) , s . end ( ) ) ; vector < string > ans ; for ( int i = 0 ; i < n ; i ++ ) ans . push_back ( s [ i ] ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) cout << ans [ i ] << " , β " ; cout << ans [ n - 1 ] ; } int main ( ) { int n = 5 ; lexNumbers ( n ) ; return 0 ; } |
Minimize cost to convert all array elements to 0 | C ++ program for the above approach ; Function to calculate the minimum cost of converting all array elements to 0 s ; Stores subarrays of 0 s only ; Traverse the array ; If consecutive 0 s occur ; Increment if needed ; Push the current length of consecutive 0 s in a vector ; Update lengths as 0 ; Sorting vector ; Stores the number of subarrays consisting of 1 s ; Traverse the array ; If current element is 1 ; Otherwise ; Increment count of consecutive ones ; Stores the minimum cost ; Traverse the array ; First element ; Traverse the subarray sizes ; Update cost ; Cost of performing X and Y operations ; Find the minimum cost ; Print the minimum cost ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumCost ( int * binary , int n , int a , int b ) { vector < int > groupOfZeros ; int len = 0 , i = 0 ; bool increment_need = true ; while ( i < n ) { increment_need = true ; while ( i < n && binary [ i ] == 0 ) { len ++ ; i ++ ; increment_need = false ; } if ( increment_need == true ) { i ++ ; } if ( len != 0 ) { groupOfZeros . push_back ( len ) ; } len = 0 ; } sort ( groupOfZeros . begin ( ) , groupOfZeros . end ( ) ) ; i = 0 ; bool found_ones = false ; int NumOfOnes = 0 ; while ( i < n ) { found_ones = false ; while ( i < n && binary [ i ] == 1 ) { i ++ ; found_ones = true ; } if ( found_ones == false ) i ++ ; else NumOfOnes ++ ; } int ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { int curr = 0 , totalOnes = NumOfOnes ; if ( i == 0 ) { curr = totalOnes * a ; } else { int mark = i , num_of_changes = 0 ; for ( int x : groupOfZeros ) { if ( mark >= x ) { totalOnes -- ; mark -= x ; num_of_changes += x ; } else { break ; } } curr = ( num_of_changes * b ) + ( totalOnes * a ) ; } ans = min ( ans , curr ) ; } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 0 , 1 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 10 , Y = 4 ; minimumCost ( arr , N , X , Y ) ; return 0 ; } |
Reduce array to longest sorted array possible by removing either half of given array in each operation | C ++ program to implement the above approach ; Function to check if the subarray arr [ i . . j ] is a sorted subarray or not ; Traverse all elements of the subarray arr [ i ... j ] ; If the previous element of the subarray exceeds current element ; Return 0 ; Return 1 ; Recursively partition the array into two equal halves ; If atmost one element is left in the subarray arr [ i . . j ] ; Checks if subarray arr [ i . . j ] is a sorted subarray or not ; If the subarray arr [ i ... j ] is a sorted subarray ; Stores middle element of the subarray arr [ i . . j ] ; Recursively partition the current subarray arr [ i . . j ] into equal halves ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int isSortedparitions ( int arr [ ] , int i , int j ) { for ( int k = i + 1 ; k <= j ; k ++ ) { if ( arr [ k ] < arr [ k - 1 ] ) { return 0 ; } } return 1 ; } int partitionsArr ( int arr [ ] , int i , int j ) { if ( i >= j ) return 1 ; bool flag = isSortedparitions ( arr , i , j ) ; if ( flag ) { return ( j - i + 1 ) ; } int mid = ( i + j ) / 2 ; int X = partitionsArr ( arr , i , mid ) ; int Y = partitionsArr ( arr , mid + 1 , j ) ; return max ( X , Y ) ; } int main ( ) { int arr [ ] = { 11 , 12 , 1 , 2 , 13 , 14 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << partitionsArr ( arr , 0 , N - 1 ) ; return 0 ; } |
Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array | C ++ program to implement the above approach ; Function to check if it is possible to merge the two given arrays with given conditions ; Stores index of the array A [ ] ; Stores index of the array B [ ] ; Check if the previous element are from the array A [ ] or from the array B [ ] ; Check if it is possible to merge the two given sorted arrays with given conditions ; Traverse both the arrays ; If A [ i ] is less than B [ j ] and previous element are not from A [ ] ; Update prev ; Update i ; If B [ j ] is less than A [ i ] and previous element are not from B [ ] ; Update prev ; Update j ; If A [ i ] equal to B [ j ] ; If previous element are not from B [ ] ; Update prev ; Update j ; If previous element is not from A [ ] ; Update prev ; Update i ; If it is not possible to merge two sorted arrays with given conditions ; Update flag ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkIfPossibleMerge ( int A [ ] , int B [ ] , int N ) { int i = 0 ; int j = 0 ; int prev = -1 ; int flag = 1 ; while ( i < N && j < N ) { if ( A [ i ] < B [ j ] && prev != 0 ) { prev = 0 ; i ++ ; } else if ( B [ j ] < A [ i ] && prev != 1 ) { prev = 1 ; j ++ ; } else if ( A [ i ] == B [ j ] ) { if ( prev != 1 ) { prev = 1 ; j ++ ; } else { prev = 0 ; i ++ ; } } else { flag = 0 ; break ; } } return flag ; } int main ( ) { int A [ 3 ] = { 3 , 5 , 8 } ; int B [ 3 ] = { 2 , 4 , 6 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; if ( checkIfPossibleMerge ( A , B , N ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Minimize array sum by replacing greater and smaller elements of pairs by half and double of their values respectively atmost K times | C ++ program to implement the above approach ; Function to find the minimum sum of array elements by given operations ; Base case ; Return 0 ; Base case ; Perform K operations ; Stores smallest element in the array ; Stores index of the smallest array element ; Stores largest element in the array ; Stores index of the largest array element ; Traverse the array elements ; If current element exceeds largest_element ; Update the largest element ; Update index of the largest array element ; If current element is smaller than smallest_element ; Update the smallest element ; Update index of the smallest array element ; Stores the value of smallest element by given operations ; Stores the value of largest element by given operations ; If the value of a + b less than the sum of smallest and largest element of the array ; Update smallest element of the array ; Update largest element of the array ; Stores sum of elements of the array by given operations ; Traverse the array ; Update ans ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimum_possible_sum ( int arr [ ] , int n , int k ) { if ( n == 0 ) { return 0 ; } if ( n == 1 ) { return arr [ 0 ] ; } for ( int i = 0 ; i < k ; i ++ ) { int smallest_element = arr [ 0 ] ; int smallest_pos = 0 ; int largest_element = arr [ 0 ] ; int largest_pos = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] >= largest_element ) { largest_element = arr [ i ] ; largest_pos = i ; } if ( arr [ i ] < smallest_element ) { smallest_element = arr [ i ] ; smallest_pos = i ; } } int a = smallest_element * 2 ; int b = largest_element / 2 ; if ( a + b < smallest_element + largest_element ) { arr [ smallest_pos ] = a ; arr [ largest_pos ] = b ; } } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans += arr [ i ] ; } return ans ; } int main ( ) { int arr [ ] = { 50 , 1 , 100 , 100 , 1 } ; int K = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimum_possible_sum ( arr , n , K ) ; return 0 ; } |
Rearrange array elements excluded by given ranges to maximize sum of subarrays starting from the first index | C ++ program for the above approach ; Function that finds the maximum sum all subarrays from the starting index after rearranging the array ; Stores elements after rearranging ; Keeps track of visited elements ; Traverse the queries ; Mark elements that are not allowed to rearranged ; Stores the indices ; Get indices and elements that are allowed to rearranged ; Store the current index and element ; Sort vector v in descending order ; Insert elements in array ; Stores the resultant sum ; Stores the prefix sums ; Traverse the given array ; Return the maximum sum ; Driver Code ; Given array ; Given size ; Queries ; Number of queries ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int n , int a [ ] , int l [ ] [ 2 ] , int q ) { vector < int > v ; int d [ n ] = { 0 } ; for ( int i = 0 ; i < q ; i ++ ) { for ( int x = l [ i ] [ 0 ] ; x <= l [ i ] [ 1 ] ; x ++ ) { if ( d [ x ] == 0 ) { d [ x ] = 1 ; } } } set < int > st ; for ( int i = 0 ; i < n ; i ++ ) { if ( d [ i ] == 0 ) { v . push_back ( a [ i ] ) ; st . insert ( i ) ; } } sort ( v . begin ( ) , v . end ( ) , greater < int > ( ) ) ; int c = 0 ; for ( auto it : st ) { a [ it ] = v ; c ++ ; } int pref_sum = 0 ; int temp_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { temp_sum += a [ i ] ; pref_sum += temp_sum ; } return pref_sum ; } int main ( ) { int arr [ ] = { -8 , 4 , -2 , -6 , 4 , 7 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int q [ ] [ 2 ] = { { 0 , 0 } , { 4 , 5 } } ; int queries = sizeof ( q ) / sizeof ( q [ 0 ] ) ; cout << maxSum ( N , arr , q , queries ) ; return 0 ; } |
Count pairs with Bitwise XOR greater than both the elements of the pair | C ++ program for the above approach ; Function to count pairs whose XOR is greater than the pair itself ; Stores the count of pairs ; Sort the array ; Traverse the array ; If current element is 0 , then ignore it ; Traverse all the bits of element A [ i ] ; If current bit is set then update the count ; Update bits [ ] at the most significant bit of A [ i ] ; Print the count ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int A [ ] , int N ) { int count = 0 ; sort ( A , A + N ) ; int bits [ 32 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] == 0 ) { continue ; } for ( int j = 0 ; j < 32 ; j ++ ) { if ( ! ( ( 1LL << j ) & A [ i ] ) ) { count += bits [ j ] ; } } ++ bits [ ( int ) ( log2l ( A [ i ] ) ) ] ; } cout << count ; } int main ( ) { int arr [ ] = { 2 , 4 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , N ) ; return 0 ; } |
Maximum occurred integers after M circular operations in given range | C ++ program for the above approach ; Function to find the maximum occurred integer after completing all circular operations ; Stores the highest visit count for any element ; Stores the number of times an element is visited ; Iterate over the array ; Iterate over the range circularly form start to end ; Count number of times an element is visited ; Increment frequency of N ; Update maxVisited ; Increment frequency of start ; Update maxVisited ; Increment the start ; Increment the count for the last visited element ; Print most visited elements ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void mostvisitedsector ( int N , vector < int > & A ) { int maxVisited = 0 ; map < int , int > mp ; for ( int i = 0 ; i < A . size ( ) - 1 ; i ++ ) { int start = A [ i ] % N ; int end = A [ i + 1 ] % N ; while ( start != end ) { if ( start == 0 ) { mp [ N ] ++ ; if ( mp [ N ] > maxVisited ) { maxVisited = mp [ N ] ; } } else { mp [ start ] ++ ; if ( mp [ start ] > maxVisited ) { maxVisited = mp [ start ] ; } } start = ( start + 1 ) % N ; } } mp [ A . back ( ) ] ++ ; if ( mp [ A . back ( ) ] > maxVisited ) { maxVisited = mp [ A . back ( ) ] ; } for ( auto x : mp ) { if ( x . second == maxVisited ) { cout << x . first << " β " ; } } } int main ( ) { int N = 4 ; vector < int > arr = { 1 , 2 , 1 , 2 } ; mostvisitedsector ( N , arr ) ; return 0 ; } |
Area of the largest rectangle formed by lines parallel to X and Y axis from given set of points | C ++ program for the above approach ; Function to return the area of the largest rectangle formed by lines parallel to X and Y axis from given set of points ; Initialize two arrays ; Store x and y coordinates ; Sort arrays ; Initialize max differences ; Find max adjacent differences ; Return answer ; Driver Code ; Given points ; Total points ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxRectangle ( vector < vector < int > > sequence , int size ) { long long int X_Cord [ size ] , Y_Cord [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { X_Cord [ i ] = sequence [ i ] [ 0 ] ; Y_Cord [ i ] = sequence [ i ] [ 1 ] ; } sort ( X_Cord , X_Cord + size ) ; sort ( Y_Cord , Y_Cord + size ) ; long long int X_Max = 0 , Y_Max = 0 ; for ( int i = 0 ; i < size - 1 ; i ++ ) { X_Max = max ( X_Max , X_Cord [ i + 1 ] - X_Cord [ i ] ) ; Y_Max = max ( Y_Max , Y_Cord [ i + 1 ] - Y_Cord [ i ] ) ; } return X_Max * Y_Max ; } int main ( ) { vector < vector < int > > point = { { -2 , 0 } , { 2 , 0 } , { 4 , 0 } , { 4 , 2 } } ; int n = point . size ( ) ; cout << maxRectangle ( point , n ) ; } |
Rearrange two given arrays such that sum of same indexed elements lies within given range | C ++ program for the above approach ; Function to check if there exists any arrangements of the arrays such that sum of element lie in the range [ K / 2 , K ] ; Sort the array arr1 [ ] in increasing order ; Sort the array arr2 [ ] in decreasing order ; Traverse the array ; If condition is not satisfied break the loop ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkArrangement ( int A1 [ ] , int A2 [ ] , int n , int k ) { sort ( A1 , A1 + n ) ; sort ( A2 , A2 + n , greater < int > ( ) ) ; int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( A1 [ i ] + A2 [ i ] > k ) || ( A1 [ i ] + A2 [ i ] < k / 2 ) ) { flag = 1 ; break ; } } if ( flag == 1 ) cout << " No " ; else cout << " Yes " ; } int main ( ) { int arr1 [ ] = { 1 , 3 , 4 , 5 } ; int arr2 [ ] = { 2 , 0 , 1 , 1 } ; int K = 6 ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; checkArrangement ( arr1 , arr2 , N , K ) ; return 0 ; } |
Rearrange two given arrays to maximize sum of same indexed elements | C ++ program to implement the above approach ; Function to find the maximum possible sum by rearranging the given array elements ; Sort the array A [ ] in ascending order ; Sort the array B [ ] in descending order ; Stores maximum possible sum by rearranging array elements ; Traverse both the arrays ; Update maxSum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxRearrngeSum ( int A [ ] , int B [ ] , int N ) { sort ( A , A + N ) ; sort ( B , B + N , greater < int > ( ) ) ; int maxSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { maxSum += abs ( A [ i ] - B [ i ] ) ; } return maxSum ; } int main ( ) { int A [ ] = { 1 , 2 , 2 , 4 , 5 } ; int B [ ] = { 5 , 5 , 5 , 6 , 6 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << MaxRearrngeSum ( A , B , N ) ; return 0 ; } |
Area of the largest rectangle possible from given coordinates | C ++ program for the above approach ; Function to find the maximum possible area of a rectangle ; Initialize variables ; Sort array arr1 [ ] ; Sort array arr2 [ ] ; Traverse arr1 [ ] and arr2 [ ] ; If arr1 [ i ] is same as arr2 [ j ] ; If no starting point is found yet ; Update maximum end ; If arr [ i ] > arr2 [ j ] ; If no rectangle is found ; Return the area ; Driver Code ; Given point ; Given length ; Given points ; Given length ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int largestArea ( int arr1 [ ] , int n , int arr2 [ ] , int m ) { int end = 0 , start = 0 , i = 0 , j = 0 ; sort ( arr1 , arr1 + n ) ; sort ( arr2 , arr2 + m ) ; while ( i < n and j < m ) { if ( arr1 [ i ] == arr2 [ j ] ) { if ( start == 0 ) start = arr1 [ i ] ; else end = arr1 [ i ] ; i ++ ; j ++ ; } else if ( arr1 [ i ] > arr2 [ j ] ) j ++ ; else i ++ ; } if ( end == 0 or start == 0 ) return 0 ; else return ( end - start ) ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 4 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int arr2 [ ] = { 1 , 3 , 4 } ; int M = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << largestArea ( arr1 , N , arr2 , M ) ; return 0 ; } |
Count pairs from two arrays with difference exceeding K | C ++ program to implement the above approach ; Function to count pairs that satisfy the given conditions ; Stores index of the left pointer . ; Stores index of the right pointer ; Stores count of total pairs that satisfy the conditions ; Sort arr [ ] array ; Sort brr [ ] array ; Traverse both the array and count then pairs ; If the value of ( brr [ j ] - arr [ i ] ) exceeds K ; Update cntPairs ; Update ; Update j ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count_pairs ( int arr [ ] , int brr [ ] , int N , int M , int K ) { int i = 0 ; int j = 0 ; int cntPairs = 0 ; sort ( arr , arr + N ) ; sort ( brr , brr + M ) ; while ( i < N && j < M ) { if ( brr [ j ] - arr [ i ] > K ) { cntPairs += ( M - j ) ; i ++ ; } else { j ++ ; } } return cntPairs ; } int main ( ) { int arr [ ] = { 5 , 9 , 1 , 8 } ; int brr [ ] = { 10 , 12 , 7 , 4 , 2 , 3 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = sizeof ( brr ) / sizeof ( brr [ 0 ] ) ; cout << count_pairs ( arr , brr , N , M , K ) ; return 0 ; } |
Merge two sorted arrays in O ( 1 ) extra space using Heap | C ++ program to implement the above approach ; Function to perform min heapify on array brr [ ] ; Stores index of left child of i . ; Stores index of right child of i . ; Stores index of the smallest element in ( arr [ i ] , arr [ left ] , arr [ right ] ) ; Check if arr [ left ] less than arr [ smallest ] ; Update smallest ; Check if arr [ right ] less than arr [ smallest ] ; Update smallest ; if i is not the index of smallest element ; Swap arr [ i ] and arr [ smallest ] ; Perform heapify on smallest ; Function to merge two sorted arrays ; Traverse the array arr [ ] ; Check if current element is less than brr [ 0 ] ; Swap arr [ i ] and brr [ 0 ] ; Perform heapify on brr [ ] ; Sort array brr [ ] ; Function to print array elements ; Traverse array arr [ ] ; Driver Code ; Function call to merge two array ; Print first array ; Print Second array . | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minHeapify ( int brr [ ] , int i , int M ) { int left = 2 * i + 1 ; int right = 2 * i + 2 ; int smallest = i ; if ( left < M && brr [ left ] < brr [ smallest ] ) { smallest = left ; } if ( right < M && brr [ right ] < brr [ smallest ] ) { smallest = right ; } if ( smallest != i ) { swap ( brr [ i ] , brr [ smallest ] ) ; minHeapify ( brr , smallest , M ) ; } } void merge ( int arr [ ] , int brr [ ] , int N , int M ) { for ( int i = 0 ; i < N ; ++ i ) { if ( arr [ i ] > brr [ 0 ] ) { swap ( arr [ i ] , brr [ 0 ] ) ; minHeapify ( brr , 0 , M ) ; } } sort ( brr , brr + M ) ; } void printArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 2 , 23 , 35 , 235 , 2335 } ; int brr [ ] = { 3 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = sizeof ( brr ) / sizeof ( brr [ 0 ] ) ; merge ( arr , brr , N , M ) ; printArray ( arr , N ) ; printArray ( brr , M ) ; return 0 ; } |
Merge two sorted arrays in O ( 1 ) extra space using QuickSort partition | C ++ program to implement the above approach ; Function to perform the partition around the pivot element ; Stores index of each element of the array , arr [ ] ; Stores index of each element of the array , brr [ ] ; Traverse both the array ; If pivot is smaller than arr [ l ] ; If Pivot is greater than brr [ r ] ; If either arr [ l ] > Pivot or brr [ r ] < Pivot ; Function to merge the two sorted array ; Stores index of each element of the array arr [ ] ; Stores index of each element of the array brr [ ] ; Stores index of each element the final sorted array ; Stores the pivot element ; Traverse both the array ; If pivot element is not found or index < N ; If pivot element is not found or index < N ; Place the first N elements of the sorted array into arr [ ] and the last M elements of the sorted array into brr [ ] ; Sort both the arrays ; Print the first N elements in sorted order ; Print the last M elements in sorted order ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void partition ( int arr [ ] , int N , int brr [ ] , int M , int Pivot ) { int l = N - 1 ; int r = 0 ; while ( l >= 0 && r < M ) { if ( arr [ l ] < Pivot ) l -- ; else if ( brr [ r ] > Pivot ) r ++ ; else { swap ( arr [ l ] , brr [ r ] ) ; l -- ; r ++ ; } } } void Merge ( int arr [ ] , int N , int brr [ ] , int M ) { int l = 0 ; int r = 0 ; int index = -1 ; int Pivot = 0 ; while ( index < N && l < N && r < M ) { if ( arr [ l ] < brr [ r ] ) { Pivot = arr [ l ++ ] ; } else { Pivot = brr [ r ++ ] ; } index ++ ; } while ( index < N && l < N ) { Pivot = arr [ l ++ ] ; index ++ ; } while ( index < N && r < M ) { Pivot = brr [ r ++ ] ; index ++ ; } partition ( arr , N , brr , M , Pivot ) ; sort ( arr , arr + N ) ; sort ( brr , brr + M ) ; for ( int i = 0 ; i < N ; i ++ ) cout << arr [ i ] << " β " ; for ( int i = 0 ; i < M ; i ++ ) cout << brr [ i ] << " β " ; } int main ( ) { int arr [ ] = { 1 , 5 , 9 } ; int brr [ ] = { 2 , 4 , 7 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = sizeof ( brr ) / sizeof ( brr [ 0 ] ) ; Merge ( arr , N , brr , M ) ; return 0 ; } |
Count array elements with rank not exceeding K | C ++ program for the above approach ; Function to find count of array elements with rank less than or equal to k ; Initialize rank and position ; Sort the given array ; Traverse array from right to left ; Update rank with position , if adjacent elements are unequal ; Return position - 1 , if rank greater than k ; Increase position ; Driver Code ; Given array ; Given K ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int rankLessThanK ( int * arr , int k , int n ) { int rank = 1 ; int position = 1 ; sort ( arr , arr + n ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i == n - 1 arr [ i ] != arr [ i + 1 ] ) { rank = position ; if ( rank > k ) return position - 1 ; } position ++ ; } return n ; } int main ( ) { int arr [ 5 ] = { 2 , 2 , 3 , 4 , 5 } ; int N = 5 ; int K = 4 ; cout << rankLessThanK ( arr , K , N ) ; return 0 ; } |
Remove Sub | C ++ program for the above approach ; Function to remove sub - directories from the given lists dir ; Store final result ; Sort the given directories ; Insert 1 st directory ; Iterating in directory ; Current directory ; Our previous valid directory ; Find length of previous directory ; If subdirectory is found ; Else store it in result valid directory ; Driver Code ; Given lists of directories dir [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void eraseSubdirectory ( vector < string > & dir ) { vector < string > res ; sort ( dir . begin ( ) , dir . end ( ) ) ; res . push_back ( dir [ 0 ] ) ; cout << " { " << dir [ 0 ] << " , β " ; for ( int i = 1 ; i < dir . size ( ) ; i ++ ) { string curr = dir [ i ] ; string prev = res . back ( ) ; int l = prev . length ( ) ; if ( curr . length ( ) > l && curr [ l ] == ' / ' && prev == curr . substr ( 0 , l ) ) continue ; res . push_back ( curr ) ; cout << curr << " , β " ; } cout << " } STRNEWLINE " ; } int main ( ) { vector < string > dir = { " / a " , " / a / j " , " / c / d / e " , " / c / d " , " / b " } ; eraseSubdirectory ( dir ) ; return 0 ; } |
Maximize count of pairs ( i , j ) from two arrays having element from first array not exceeding that from second array | C ++ program for the above approach ; Function to return the maximum number of required pairs ; Max Heap to add values of arar2 [ ] ; Sort the array arr1 [ ] ; Push all arr2 [ ] into Max Heap ; Initialize the ans ; Traverse the arr1 [ ] in decreasing order ; Remove element until a required pair is found ; Return maximum number of pairs ; Driver Code ; Given arrays ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfPairs ( int arr1 [ ] , int n , int arr2 [ ] , int m ) { priority_queue < int > pq ; int i , j ; sort ( arr1 , arr1 + n ) ; for ( j = 0 ; j < m ; j ++ ) { pq . push ( arr2 [ j ] ) ; } int ans = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( pq . top ( ) >= 2 * arr1 [ i ] ) { ans ++ ; pq . pop ( ) ; } } return ans ; } int main ( ) { int arr1 [ ] = { 3 , 1 , 2 } ; int arr2 [ ] = { 3 , 4 , 2 , 1 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int M = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << numberOfPairs ( arr1 , N , arr2 , M ) ; return 0 ; } |
Minimum number of operations to convert a given sequence into a Geometric Progression | Set 2 | C ++ program for above approach ; Function to find minimum cost ; Sort the array ; Maximum possible common ratios ; Iterate over all possible common ratios ; Calculate operations required for the current common ratio ; Calculate minimum cost ; Driver Code ; Given N ; Given arr [ ] ; Function Calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minCost ( int arr [ ] , int n ) { if ( n == 1 ) { cout << 0 << endl ; return ; } sort ( arr , arr + n ) ; float raised = 1 / float ( n - 1 ) ; float temp = pow ( arr [ n - 1 ] , raised ) ; int r = round ( temp ) + 1 ; int i , j , min_cost = INT_MAX ; int common_ratio = 1 ; for ( j = 1 ; j <= r ; j ++ ) { int curr_cost = 0 , prod = 1 ; for ( i = 0 ; i < n ; i ++ ) { curr_cost += abs ( arr [ i ] - prod ) ; prod *= j ; if ( curr_cost >= min_cost ) break ; } if ( i == n ) { min_cost = min ( min_cost , curr_cost ) ; common_ratio = j ; } } cout << min_cost << ' β ' ; cout << common_ratio << ' β ' ; } int main ( ) { int N = 6 ; int arr [ ] = { 1 , 11 , 4 , 27 , 15 , 33 } ; minCost ( arr , N ) ; return 0 ; } |
Mth bit in Nth binary string from a sequence generated by the given operations | C ++ program for above approach ; Function to calculate N Fibonacci numbers ; Function to find the mth bit in the string Sn ; Base case ; Length of left half ; Length of the right half ; Recursive check in the left half ; Recursive check in the right half ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxN 10 NEW_LINE void calculateFib ( int fib [ ] , int n ) { fib [ 0 ] = fib [ 1 ] = 1 ; for ( int x = 2 ; x < n ; x ++ ) { fib [ x ] = fib [ x - 1 ] + fib [ x - 2 ] ; } } int find_mth_bit ( int n , int m , int fib [ ] ) { if ( n <= 1 ) { return n ; } int len_left = fib [ n - 2 ] ; int len_right = fib [ n - 1 ] ; if ( m <= len_left ) { return find_mth_bit ( n - 2 , len_left + 1 - m , fib ) ; } else { return find_mth_bit ( n - 1 , len_right + 1 - ( m - len_left ) , fib ) ; } } void find_mth_bitUtil ( int n , int m ) { int fib [ maxN ] ; calculateFib ( fib , maxN ) ; int ans = find_mth_bit ( n , m , fib ) ; cout << ans << ' β ' ; } int main ( ) { int n = 5 , m = 3 ; find_mth_bitUtil ( n , m ) ; return 0 ; } |
Minimize count of adjacent row swaps to convert given Matrix to a Lower Triangular Matrix | C ++ program to implement the above approach ; Function to count the minimum number of adjacent swaps ; Stores the size of the given matrix ; Stores the count of zero at the end of each row ; Traverse the given matrix ; Count of 0 s at the end of the ith row ; Stores the count of swaps ; Traverse the cntZero array ; If count of zero in the i - th row < ( N - i - 1 ) ; Stores the index of the row where count of zero > ( N - i - 1 ) ; If no row found that satisfy the condition ; Swap the adjacent row ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minAdjSwaps ( vector < vector < int > > & mat ) { int N = mat . size ( ) ; vector < int > cntZero ( N , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = N - 1 ; j >= 0 && mat [ i ] [ j ] == 0 ; j -- ) { cntZero [ i ] ++ ; } } int cntSwaps = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( cntZero [ i ] < ( N - i - 1 ) ) { int First = i ; while ( First < N && cntZero [ First ] < ( N - i - 1 ) ) { First ++ ; } if ( First == N ) { return -1 ; } while ( First > i ) { swap ( cntZero [ First ] , cntZero [ First - 1 ] ) ; First -- ; cntSwaps ++ ; } } } return cntSwaps ; } int main ( ) { vector < vector < int > > mat = { { 0 , 0 , 2 } , { 3 , 1 , 0 } , { 4 , 0 , 0 } } ; cout << minAdjSwaps ( mat ) ; } |
Largest area in a grid unbounded by towers | C ++ Program for the above approach ; Function to calculate the largest area unguarded by towers ; Sort the x - coordinates of the list ; Sort the y - coordinates of the list ; dx -- > maximum uncovered tiles in x coordinates ; dy -- > maximum uncovered tiles in y coordinates ; Calculate the maximum uncovered distances for both x and y coordinates ; Largest unguarded area is max ( dx ) - 1 * max ( dy ) - 1 ; Driver Code ; Length and width of the grid ; No of guard towers ; Array to store the x and y coordinates ; Function call | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void maxArea ( int point_x [ ] , int point_y [ ] , int n , int length , int width ) { sort ( point_x , point_x + n ) ; sort ( point_y , point_y + n ) ; int dx = point_x [ 0 ] ; int dy = point_y [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { dx = max ( dx , point_x [ i ] - point_x [ i - 1 ] ) ; dy = max ( dy , point_y [ i ] - point_y [ i - 1 ] ) ; } dx = max ( dx , ( length + 1 ) - point_x [ n - 1 ] ) ; dy = max ( dy , ( width + 1 ) - point_y [ n - 1 ] ) ; cout << ( dx - 1 ) * ( dy - 1 ) ; cout << endl ; } int main ( ) { int length = 15 , width = 8 ; int n = 3 ; int point_x [ ] = { 3 , 11 , 8 } ; int point_y [ ] = { 8 , 2 , 6 } ; maxArea ( point_x , point_y , n , length , width ) ; return 0 ; } |
Split an Array to maximize subarrays having equal count of odd and even elements for a cost not exceeding K | C ++ program for the above approach ; Function to find the cost of splitting the arrays into subarray with cost less than K ; Store the possible splits ; Stores the cost of each split ; Stores the count of even numbers ; Stores the count of odd numbers ; Count of odd & even elements ; Check the required conditions for a valid split ; Sort the cost of splits ; Find the minimum split costs adding up to sum less than K ; Driver Code ; Given array and K ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int make_cuts ( int arr [ ] , int n , int K ) { int ans = 0 ; vector < int > poss ; int ce = 0 ; int co = 0 ; for ( int x = 0 ; x < n - 1 ; x ++ ) { if ( arr [ x ] % 2 == 0 ) ce ++ ; else co ++ ; if ( ce == co && co > 0 && ce > 0 ) { poss . push_back ( abs ( arr [ x ] - arr [ x + 1 ] ) ) ; } } sort ( poss . begin ( ) , poss . end ( ) ) ; for ( int x : poss ) { if ( K >= x ) { ans ++ ; K -= x ; } else break ; } return ans ; } int main ( ) { int N = 6 ; int K = 4 ; int arr [ ] = { 1 , 2 , 5 , 10 , 15 , 20 } ; cout << make_cuts ( arr , N , K ) ; } |
Cost of rearranging the array such that no element exceeds the sum of its adjacent elements | C ++ program to implement the above approach ; Function to check if given elements can be arranged such that sum of its neighbours is strictly greater ; Initialize the total cost ; Storing the original index of elements in a hashmap ; Sort the given array ; Check if a given condition is satisfies or not ; First number ; Add the cost to overall cost ; Last number ; Add the cost to overall cost ; Add the cost to overall cost ; Printing the cost ; Driver Code ; Given array ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void Arrange ( int arr [ ] , int n ) { int cost = 0 ; unordered_map < int , int > index ; for ( int i = 0 ; i < n ; i ++ ) { index [ arr [ i ] ] = i ; } sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) { if ( arr [ i ] > arr [ i + 1 ] + arr [ n - 1 ] ) { cout << " - 1" ; return ; } else { cost += abs ( index [ arr [ i ] ] - i ) ; } } else if ( i == n - 1 ) { if ( arr [ i ] > arr [ i - 1 ] + arr [ 0 ] ) { cout << " - 1" ; return ; } else { cost += abs ( index [ arr [ i ] ] - i ) ; } } else { if ( arr [ i ] > arr [ i - 1 ] + arr [ i + 1 ] ) { cout << " - 1" ; return ; } else { cost += abs ( index [ arr [ i ] ] - i ) ; } } } cout << cost ; return ; } int main ( ) { int arr [ ] = { 2 , 4 , 5 , 1 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Arrange ( arr , N ) ; return 0 ; } |
XOR of all possible pairwise sum from two given Arrays | C ++ Program to implement the above approach ; Function to calculate the sum of XOR of the sum of every pair ; Stores the XOR of sums of every pair ; Iterate to generate all possible pairs ; Update XOR ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int XorSum ( int A [ ] , int B [ ] , int N ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { ans = ans ^ ( A [ i ] + B [ j ] ) ; } } return ans ; } int main ( ) { int A [ ] = { 4 , 6 , 0 , 0 , 3 , 3 } ; int B [ ] = { 0 , 5 , 6 , 5 , 0 , 3 } ; int N = sizeof A / sizeof A [ 0 ] ; cout << XorSum ( A , B , N ) << endl ; return 0 ; } |
Maximum non | C ++ program for the above approach ; Function to find maximum distinct character after removing K character ; Freq implemented as hash table to store frequency of each character ; Store frequency of each character ; Insert each frequency in v ; Sort the freq of character in non - decreasing order ; Traverse the vector ; Update v [ i ] and k ; If K is still not 0 ; Store the final answer ; Count this character if freq 1 ; Return count of distinct characters ; Driver Code ; Given string ; Given k ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDistinctChar ( string s , int n , int k ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < n ; i ++ ) freq [ s [ i ] ] ++ ; vector < int > v ; for ( auto it = freq . begin ( ) ; it != freq . end ( ) ; it ++ ) { v . push_back ( it -> second ) ; } sort ( v . begin ( ) , v . end ( ) ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { int mn = min ( v [ i ] - 1 , k ) ; v [ i ] -= mn ; k -= mn ; } if ( k > 0 ) { for ( int i = 0 ; i < v . size ( ) ; i ++ ) { int mn = min ( v [ i ] , k ) ; v [ i ] -= mn ; k -= mn ; } } int res = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) if ( v [ i ] == 1 ) res ++ ; return res ; } int main ( ) { string S = " geeksforgeeks " ; int N = S . size ( ) ; int K = 1 ; cout << maxDistinctChar ( S , N , K ) ; return 0 ; } |
Split N as the sum of K numbers satisfying the given conditions | C ++ Program to implement the above approach ; Vector to store prime numbers ; Function to generate prime numbers using SieveOfEratosthenes ; Boolean array to store primes ; If p is a prime ; Mark all its multiples as non - prime ; Print all prime numbers ; Function to generate n as the sum of k numbers where atleast K - 1 are distinct and are product of 2 primes ; Stores the product of every pair of prime number ; Sort the products ; If sum exceeds n ; Otherwise , print the k required numbers ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > primes ; void SieveOfEratosthenes ( ) { bool prime [ 10005 ] ; memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= 1000 ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= 1000 ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= 1000 ; p ++ ) if ( prime [ p ] ) primes . push_back ( p ) ; } void generate ( int n , int k ) { vector < long long > prod ; SieveOfEratosthenes ( ) ; int l = primes . size ( ) ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = i + 1 ; j < l ; j ++ ) { if ( primes [ i ] * primes [ j ] > 0 ) prod . push_back ( primes [ i ] * primes [ j ] ) ; } } sort ( prod . begin ( ) , prod . end ( ) ) ; int sum = 0 ; for ( int i = 0 ; i < k - 1 ; i ++ ) sum += prod [ i ] ; if ( sum > n ) cout << " - 1" ; else { for ( int i = 0 ; i < k - 1 ; i ++ ) { cout << prod [ i ] << " , β " ; } cout << n - sum << " STRNEWLINE " ; } } int main ( ) { int n = 52 , k = 5 ; generate ( n , k ) ; return 0 ; } |
Maximum modified Array sum possible by choosing elements as per the given conditions | C ++ program for the above approach ; Function that finds the maximum sum of the array elements according to the given condition ; Sort the array ; Take the max value from the array ; Iterate from the end of the array ; Check for the number had come before or not ; Take the value which is not occured already ; Change max to new value ; Return the maximum sum ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; ll findMaxValue ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; ll ans = arr [ n - 1 ] ; ll maxPossible = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; -- i ) { if ( maxPossible > 0 ) { if ( arr [ i ] >= maxPossible ) { ans += ( maxPossible - 1 ) ; maxPossible = maxPossible - 1 ; } else { maxPossible = arr [ i ] ; ans += maxPossible ; } } } return ans ; } int main ( ) { int arr [ ] = { 4 , 4 , 1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaxValue ( arr , n ) ; } |
Minimum cost to sort an Array such that swapping X and Y costs XY | C ++ program for the above approach ; Function returns the minimum cost to sort the given array ; Create array of pairs in which 1 st element is the array element and 2 nd element is index of first ; Initialize the total cost ; Sort the array with respect to array value ; Initialize the overall minimum which is the 1 st element ; To keep track of visited elements create a visited array & initialize all elements as not visited ; Iterate over every element of the array ; If the element is visited or in the sorted position , and check for next element ; Create a vector which stores all elements of a cycle ; It covers all the elements of a cycle ; If cycle is found then the swapping is required ; Initialize local minimum with 1 st element of the vector as it contains the smallest element in the beginning ; Stores the cost with using only local minimum value . ; Stores the cost of using both local minimum and overall minimum ; Update the result2 ; Store the minimum of the two result to total cost ; Return the minimum cost ; Driver Code ; Given array arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( int arr [ ] , int n ) { pair < int , int > sorted [ n ] ; int total_cost = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sorted [ i ] . first = arr [ i ] ; sorted [ i ] . second = i ; } sort ( sorted , sorted + n ) ; int overall_minimum = sorted [ 0 ] . first ; bool vis [ n ] = { false } ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis [ i ] && sorted [ i ] . second == i ) continue ; vector < int > v ; int j = i ; while ( ! vis [ j ] ) { vis [ j ] = true ; v . push_back ( sorted [ j ] . first ) ; j = sorted [ j ] . second ; } if ( v . size ( ) > 0 ) { int local_minimum = v [ 0 ] , result1 = 0 , result2 = 0 ; for ( int k = 1 ; k < v . size ( ) ; k ++ ) result1 += ( local_minimum * v [ k ] ) ; for ( int k = 0 ; k < v . size ( ) ; k ++ ) result2 += ( overall_minimum * v [ k ] ) ; result2 += ( overall_minimum * local_minimum ) ; total_cost += min ( result1 , result2 ) ; } } return total_cost ; } int main ( ) { int arr [ ] = { 1 , 8 , 9 , 7 , 6 } ; int n = ( sizeof ( arr ) / sizeof ( int ) ) ; cout << minCost ( arr , n ) ; return 0 ; } |
Maximize the last Array element as per the given conditions | C ++ Program to implement the above approach ; Function to find the maximum possible value that can be placed at the last index ; Sort array in ascending order ; If the first element is not equal to 1 ; Traverse the array to make difference between adjacent elements <= 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximizeFinalElement ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; if ( arr [ 0 ] != 1 ) arr [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] - arr [ i - 1 ] > 1 ) { arr [ i ] = arr [ i - 1 ] + 1 ; } } return arr [ n - 1 ] ; } int main ( ) { int n = 4 ; int arr [ ] = { 3 , 1 , 3 , 4 } ; int max = maximizeFinalElement ( arr , n ) ; cout << max ; return 0 ; } |
Find the point on X | C ++ Program to implement the above approach ; Function to find median of the array ; Sort the given array ; If number of elements are even ; Return the first median ; Otherwise ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findLeastDist ( int A [ ] , int N ) { sort ( A , A + N ) ; if ( N % 2 == 0 ) { return A [ ( N - 1 ) / 2 ] ; } else { return A [ N / 2 ] ; } } int main ( ) { int A [ ] = { 4 , 1 , 5 , 10 , 2 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << " ( " << findLeastDist ( A , N ) << " , β " << 0 << " ) " ; return 0 ; } |
Maximum sum of any submatrix of a Matrix which is sorted row | C ++ program for the above approach ; Function that finds the maximum Sub - Matrix Sum ; Number of rows in the matrix ; Number of columns in the matrix ; dp [ ] [ ] matrix to store the results of each iteration ; Base Case - The largest element in the matrix ; To stores the final result ; Find the max sub matrix sum for the last row ; Check whether the current sub - array yields maximum sum ; Calculate the max sub matrix sum for the last column ; Check whether the current sub - array yields maximum sum ; Build the dp [ ] [ ] matrix from bottom to the top row ; Update sum at each cell in dp [ ] [ ] ; Update the maximum sum ; Return the maximum sum ; Driver Code ; Given matrix mat [ ] [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubMatSum ( vector < vector < int > > mat ) { int n = mat . size ( ) ; int m = mat [ 0 ] . size ( ) ; int i , j ; int dp [ n ] [ m ] ; dp [ n - 1 ] [ m - 1 ] = mat [ n - 1 ] [ m - 1 ] ; int res = dp [ n - 1 ] [ m - 1 ] ; for ( i = m - 2 ; i >= 0 ; i -- ) { dp [ n - 1 ] [ i ] = mat [ n - 1 ] [ i ] + dp [ n - 1 ] [ i + 1 ] ; res = max ( res , dp [ n - 1 ] [ i ] ) ; } for ( i = n - 2 ; i >= 0 ; i -- ) { dp [ i ] [ m - 1 ] = mat [ i ] [ m - 1 ] + dp [ i + 1 ] [ m - 1 ] ; res = max ( res , dp [ i ] [ m - 1 ] ) ; } for ( i = n - 2 ; i >= 0 ; i -- ) { for ( j = m - 2 ; j >= 0 ; j -- ) { dp [ i ] [ j ] = mat [ i ] [ j ] + dp [ i ] [ j + 1 ] + dp [ i + 1 ] [ j ] - dp [ i + 1 ] [ j + 1 ] ; res = max ( res , dp [ i ] [ j ] ) ; } } return res ; } int main ( ) { vector < vector < int > > mat ; mat = { { -6 , -4 , -1 } , { -3 , 2 , 4 } , { 2 , 5 , 8 } } ; cout << maxSubMatSum ( mat ) ; return 0 ; } |
Check if two arrays can be made equal by reversing subarrays multiple times | C ++ implementation to check if two arrays can be made equal ; Function to check if array B can be made equal to array A ; sort both the arrays ; Check if both the arrays are equal or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canMadeEqual ( int A [ ] , int B [ ] , int n ) { sort ( A , A + n ) ; sort ( B , B + n ) ; for ( int i = 0 ; i < n ; i ++ ) if ( A [ i ] != B [ i ] ) return false ; return true ; } int main ( ) { int A [ ] = { 1 , 2 , 3 } ; int B [ ] = { 1 , 3 , 2 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; if ( canMadeEqual ( A , B , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Minimize difference between maximum and minimum of Array by at most K replacements | C ++ program of the approach ; Function to find minimum difference between the maximum and the minimum elements arr [ ] by at most K replacements ; Check if turns are more than or equal to n - 1 then simply return zero ; Sort the array ; Set difference as the maximum possible difference ; Iterate over the array to track the minimum difference in k turns ; Return the answer ; Driver Code ; Given array arr [ ] ; Given K replacements ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxMinDifference ( int arr [ ] , int n , int k ) { if ( k >= n - 1 ) return 0 ; sort ( arr , arr + n ) ; int ans = arr [ n - 1 ] - arr [ 0 ] ; for ( int i = k , j = n - 1 ; i >= 0 ; -- i , -- j ) { ans = min ( arr [ j ] - arr [ i ] , ans ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 4 , 6 , 11 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << maxMinDifference ( arr , N , K ) ; return 0 ; } |
Maximum possible Array sum after performing given operations | C ++ implementation to find the maximum possible sum of array after performing given operations ; Function to get maximum sum after q operations ; priority queue to get maximum sum ; Push pair , value and 1 in the priority queue ; Push pair , value ( to be replaced ) and number of elements ( to be replaced ) ; Add top n elements from the priority queue to get max sum ; pr is the pair pr . first is the value and pr . second is the occurrence ; pop from the priority queue ; Add value to answer ; Update n ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void max_sum ( int ar [ ] , int n , int q , int x [ ] , int y [ ] ) { int ans = 0 , i ; priority_queue < pair < int , int > > pq ; for ( i = 0 ; i < n ; i ++ ) pq . push ( { ar [ i ] , 1 } ) ; for ( i = 0 ; i < q ; i ++ ) pq . push ( { y [ i ] , x [ i ] } ) ; while ( n > 0 ) { auto pr = pq . top ( ) ; pq . pop ( ) ; ans += pr . first * min ( n , pr . second ) ; n -= pr . second ; } cout << ans << " STRNEWLINE " ; } int main ( ) { int ar [ ] = { 200 , 100 , 200 , 300 } ; int n = ( sizeof ar ) / ( sizeof ar [ 0 ] ) ; int q = 2 ; int x [ ] = { 2 , 3 } ; int y [ ] = { 100 , 90 } ; max_sum ( ar , n , q , x , y ) ; return 0 ; } |
Check if a decreasing Array can be sorted using Triple cyclic shift | C ++ program for the above approach ; If array is 3 2 1 can ' t β β be β sorted β because β 2 β is β in β β its β correct β position , β 1 β β and β 3 β can ' t shift right because cyclic right shift takes place between 3 elements ; Check if its possible to sort ; Number of swap is N / 2 always for this approach ; Printing index of the cyclic right shift ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortarray ( int arr [ ] , int N ) { if ( N == 3 ) cout << " NO " << endl ; else if ( N % 4 == 0 N % 4 == 1 ) { cout << " YES " << endl ; cout << ( N / 2 ) << endl ; int k = 1 ; for ( int l = 0 ; l < ( N / 4 ) ; l ++ ) { cout << k << " β " << k + 1 << " β " << N << endl ; cout << k + 1 << " β " << N << " β " << N - 1 << endl ; k = k + 2 ; N = N - 2 ; } } else cout << " NO " << endl ; } int main ( ) { int N = 5 ; int arr [ ] = { 5 , 4 , 3 , 2 , 1 } ; sortarray ( arr , N ) ; return 0 ; } |
Find least non | C ++ program to find the least non - overlapping number from a given set intervals ; function to find the smallest non - overlapping number ; create a visited array ; find the first missing value ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1e5 + 5 ; void find_missing ( vector < pair < int , int > > interval ) { vector < int > vis ( MAX ) ; for ( int i = 0 ; i < interval . size ( ) ; ++ i ) { int start = interval [ i ] . first ; int end = interval [ i ] . second ; vis [ start ] ++ ; vis [ end + 1 ] -- ; } for ( int i = 1 ; i < MAX ; i ++ ) { vis [ i ] += vis [ i - 1 ] ; if ( ! vis [ i ] ) { cout << i << endl ; return ; } } } int main ( ) { vector < pair < int , int > > interval = { { 0 , 14 } , { 86 , 108 } , { 22 , 30 } , { 5 , 17 } } ; find_missing ( interval ) ; return 0 ; } |
Find least non | C ++ program to find the least non - overlapping number from a given set intervals ; function to find the smallest non - overlapping number ; Sort the intervals based on their starting value ; check if any missing value exist ; finally print the missing value ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void find_missing ( vector < pair < int , int > > interval ) { sort ( interval . begin ( ) , interval . end ( ) ) ; int mx = 0 ; for ( int i = 0 ; i < ( int ) interval . size ( ) ; ++ i ) { if ( interval [ i ] . first > mx ) { cout << mx ; return ; } else mx = max ( mx , interval [ i ] . second + 1 ) ; } cout << mx ; } int main ( ) { vector < pair < int , int > > interval = { { 0 , 14 } , { 86 , 108 } , { 22 , 30 } , { 5 , 17 } } ; find_missing ( interval ) ; return 0 ; } |
Maximum bitwise OR value of subsequence of length K | C ++ program for the above approach ; Function to convert bit array to decimal number ; Return the final result ; Function to find the maximum Bitwise OR value of subsequence of length K ; Initialize bit array of size 32 with all value as 0 ; Iterate for each index of bit [ ] array from 31 to 0 , and check if the ith value of bit array is 0 ; Check for maximum contributing element ; Update the bit array if max_contributing element is found ; Decrement the value of K ; Return the result ; Driver Code ; Given array arr [ ] ; Length of subsequence ; Function Call | #include <iostream> NEW_LINE using namespace std ; int build_num ( int bit [ ] ) { int ans = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) if ( bit [ i ] ) ans += ( 1 << i ) ; return ans ; } int maximumOR ( int arr [ ] , int n , int k ) { int bit [ 32 ] = { 0 } ; for ( int i = 31 ; i >= 0 ; i -- ) { if ( bit [ i ] == 0 && k > 0 ) { int temp = build_num ( bit ) ; int temp1 = temp ; int val = -1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( temp1 < ( temp arr [ j ] ) ) { temp1 = temp | arr [ j ] ; val = arr [ j ] ; } } if ( val != -1 ) { k -- ; for ( int j = 0 ; j < 32 ; j ++ ) { if ( val & ( 1 << j ) ) bit [ j ] ++ ; } } } } return build_num ( bit ) ; } int main ( ) { int arr [ ] = { 5 , 9 , 7 , 19 } ; int k = 3 ; int n = sizeof arr / sizeof arr [ 0 ] ; cout << maximumOR ( arr , n , k ) ; return 0 ; } |
Lexicographically smallest string after M operations | C ++ implementation to find the lexicographical smallest string after performing M operations ; Function to find the lexicographical smallest string after performing M operations ; Size of the given string ; Declare an array a ; For each i , a [ i ] contain number of operations to update s [ i ] to ' a ' ; Check if m >= ar [ i ] , then update s [ i ] to ' a ' decrement k by a [ i ] ; Form a cycle of 26 ; update last element of string with the value s [ i ] + ( k % 26 ) ; Return the answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void smallest_string ( string s , int m ) { int n = s . size ( ) ; int a [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int distance = s [ i ] - ' a ' ; if ( distance == 0 ) a [ i ] = 0 ; else a [ i ] = 26 - distance ; } for ( int i = 0 ; i < n ; i ++ ) { if ( m >= a [ i ] ) { s [ i ] = ' a ' ; m = m - a [ i ] ; } } m = m % 26 ; s [ n - 1 ] = s [ n - 1 ] + m ; cout << s ; } int main ( ) { string str = " aazzx " ; int m = 6 ; smallest_string ( str , m ) ; return 0 ; } |
Maximize jobs that can be completed under given constraint | C ++ Program to implement the above approach ; Function to find maxiumum number of jobs ; Min Heap ; Sort ranges by start day ; Stores the minimum and maximum day in the ranges ; Iterating from min_day to max_day ; Insert the end day of the jobs which can be completed on i - th day in a priority queue ; Pop all jobs whose end day is less than current day ; If queue is empty , no job can be completed on the i - th day ; Increment the count of jobs completed ; Pop the job with least end day ; Return the jobs on the last day ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int find_maximum_jobs ( int N , vector < pair < int , int > > ranges ) { priority_queue < int , vector < int > , greater < int > > queue ; sort ( ranges . begin ( ) , ranges . end ( ) ) ; int min_day = ranges [ 0 ] . first ; int max_day = 0 ; for ( int i = 0 ; i < N ; i ++ ) max_day = max ( max_day , ranges [ i ] . second ) ; int index = 0 , count_jobs = 0 ; for ( int i = min_day ; i <= max_day ; i ++ ) { while ( index < ranges . size ( ) && ranges [ index ] . first <= i ) { queue . push ( ranges [ index ] . second ) ; index ++ ; } while ( ! queue . empty ( ) && queue . top ( ) < i ) queue . pop ( ) ; if ( queue . empty ( ) ) continue ; count_jobs ++ ; queue . pop ( ) ; } return count_jobs ; } int main ( ) { int N = 5 ; vector < pair < int , int > > ranges ; ranges . push_back ( { 1 , 5 } ) ; ranges . push_back ( { 1 , 5 } ) ; ranges . push_back ( { 1 , 5 } ) ; ranges . push_back ( { 2 , 3 } ) ; ranges . push_back ( { 2 , 3 } ) ; cout << find_maximum_jobs ( N , ranges ) ; } |
Minimize number of boxes by putting small box inside bigger one | C ++ implementation to minimize the number of the box by putting small box inside the bigger one ; Function to minimize the count ; Initial number of box ; Sort array of box size in increasing order ; check is current box size is smaller than next box size ; Decrement box count Increment current box count Increment next box count ; Check if both box have same size ; Print the result ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minBox ( int arr [ ] , int n ) { int box = n ; sort ( arr , arr + n ) ; int curr_box = 0 , next_box = 1 ; while ( curr_box < n && next_box < n ) { if ( arr [ curr_box ] < arr [ next_box ] ) { box -- ; curr_box ++ ; next_box ++ ; } else if ( arr [ curr_box ] == arr [ next_box ] ) next_box ++ ; } cout << box << endl ; } int main ( ) { int size [ ] = { 1 , 2 , 3 } ; int n = sizeof ( size ) / sizeof ( size [ 0 ] ) ; minBox ( size , n ) ; return 0 ; } |
Sort a string lexicographically using triple cyclic shifts | C ++ Program for sorting a string using cyclic shift of three indices ; Store the indices which haven 't attained its correct position ; Store the indices undergoing cyclic shifts ; If the element is not at it 's correct position ; Check if all 3 indices can be placed to respective correct indices in a single move ; If the i - th index is still not present in its correct position , store the index ; To check if swapping two indices places them in their correct position ; for ( int i = 0 ; i < indices . size ( ) ; i ++ ) { cout << indices [ i ] [ 0 ] << " β " << indices [ i ] [ 1 ] << " β " << indices [ i ] [ 2 ] << endl ; } ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortString ( vector < int > & arr , int n , int moves ) { vector < int > pos ; vector < vector < int > > indices ; bool flag = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != i ) { if ( arr [ arr [ arr [ i ] ] ] == i && arr [ arr [ i ] ] != i ) { int temp = arr [ arr [ i ] ] ; indices . push_back ( { i , arr [ i ] , arr [ arr [ i ] ] } ) ; swap ( arr [ i ] , arr [ arr [ i ] ] ) ; swap ( arr [ i ] , arr [ temp ] ) ; } } if ( arr [ i ] != i ) { pos . push_back ( i ) ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != i ) { int pos1 = i , pos2 = arr [ i ] ; int pos3 = arr [ arr [ i ] ] ; if ( pos3 != pos1 ) { indices . push_back ( { pos1 , pos2 , pos3 } ) ; swap ( arr [ pos1 ] , arr [ pos2 ] ) ; swap ( arr [ pos1 ] , arr [ pos3 ] ) ; pos . erase ( find ( pos . begin ( ) , pos . end ( ) , pos2 ) ) ; pos . erase ( find ( pos . begin ( ) , pos . end ( ) , pos3 ) ) ; if ( arr [ pos1 ] == pos1 ) { pos . erase ( find ( pos . begin ( ) , pos . end ( ) , pos1 ) ) ; } } else { if ( pos3 == * pos . begin ( ) ) { if ( * pos . begin ( ) != pos . back ( ) ) { auto it = ++ pos . begin ( ) ; pos3 = * ( it ) ; if ( * it != pos . back ( ) && pos3 == pos2 ) { pos3 = * ( ++ it ) ; } else if ( * it == pos . back ( ) && pos3 == pos2 ) { flag = true ; break ; } } else { flag = true ; break ; } } indices . push_back ( { pos1 , pos2 , pos3 } ) ; swap ( arr [ pos1 ] , arr [ pos2 ] ) ; swap ( arr [ pos1 ] , arr [ pos3 ] ) ; pos . erase ( find ( pos . begin ( ) , pos . end ( ) , pos2 ) ) ; } } if ( arr [ i ] != i ) { i -- ; } } if ( flag == true || indices . size ( ) > moves ) { cout << " Not β Possible " << endl ; } else { cout << indices . size ( ) << endl ; } } int main ( ) { string s = " adceb " ; vector < int > arr ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { arr . push_back ( s [ i ] - ' a ' ) ; } sortString ( arr , s . size ( ) , floor ( s . size ( ) / 2 ) ) ; } |
Count of minimum reductions required to get the required sum K | C ++ Program to find the count of minimum reductions required to get the required sum K ; Function to return the count of minimum reductions ; If the sum is already less than K ; Sort in non - increasing order of difference ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countReductions ( vector < pair < int , int > > & v , int K ) { int sum = 0 ; for ( auto i : v ) { sum += i . first ; } if ( sum <= K ) { return 0 ; } sort ( v . begin ( ) , v . end ( ) , [ & ] ( pair < int , int > a , pair < int , int > b ) { return ( a . first - a . second ) > ( b . first - b . second ) ; } ) ; int i = 0 ; while ( sum > K && i < v . size ( ) ) { sum -= ( v [ i ] . first - v [ i ] . second ) ; i ++ ; } if ( sum <= K ) return i ; return -1 ; } int main ( ) { int N = 4 , K = 25 ; vector < pair < int , int > > v ( N ) ; v [ 0 ] = { 10 , 5 } ; v [ 1 ] = { 20 , 9 } ; v [ 2 ] = { 12 , 10 } ; v [ 3 ] = { 4 , 2 } ; cout << countReductions ( v , K ) << endl ; return 0 ; } |
Merge two unsorted linked lists to get a sorted list | C ++ program for the above approach ; Create structure for a node ; Function to print the linked list ; Store the head of the linked list into a temporary node * and iterate ; Function takes the head of the LinkedList and the data as argument and if no LinkedList exists , it creates one with the head pointing to first node . If it exists already , it appends given node at end of the last node ; Create a new node ; Insert data into the temporary node and point it 's next to NULL ; Check if head is null , create a linked list with temp as head and tail of the list ; Else insert the temporary node after the tail of the existing node and make the temporary node as the tail of the linked list ; Return the list ; Function to concatenate the two lists ; Iterate through the head1 to find the last node join the next of last node of head1 to the 1 st node of head2 ; return the concatenated lists as a single list - head1 ; Sort the linked list using bubble sort ; Compares two adjacent elements and swaps if the first element is greater than the other one . ; Driver Code ; Given Linked List 1 ; Given Linked List 2 ; Merge the two lists in a single list ; Sort the unsorted merged list ; Print the final sorted merged list | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; node * next ; } ; void setData ( node * head ) { node * tmp ; tmp = head ; while ( tmp != NULL ) { cout << tmp -> data << " β - > β " ; tmp = tmp -> next ; } } node * getData ( node * head , int num ) { node * temp = new node ; node * tail = head ; temp -> data = num ; temp -> next = NULL ; if ( head == NULL ) { head = temp ; tail = temp ; } else { while ( tail != NULL ) { if ( tail -> next == NULL ) { tail -> next = temp ; tail = tail -> next ; } tail = tail -> next ; } } return head ; } node * mergelists ( node * * head1 , node * * head2 ) { node * tail = * head1 ; while ( tail != NULL ) { if ( tail -> next == NULL && head2 != NULL ) { tail -> next = * head2 ; break ; } tail = tail -> next ; } return * head1 ; } void sortlist ( node * * head1 ) { node * curr = * head1 ; node * temp = * head1 ; while ( curr -> next != NULL ) { temp = curr -> next ; while ( temp != NULL ) { if ( temp -> data < curr -> data ) { int t = temp -> data ; temp -> data = curr -> data ; curr -> data = t ; } temp = temp -> next ; } curr = curr -> next ; } } int main ( ) { node * head1 = new node ; node * head2 = new node ; head1 = NULL ; head2 = NULL ; head1 = getData ( head1 , 4 ) ; head1 = getData ( head1 , 7 ) ; head1 = getData ( head1 , 5 ) ; head2 = getData ( head2 , 2 ) ; head2 = getData ( head2 , 1 ) ; head2 = getData ( head2 , 8 ) ; head2 = getData ( head2 , 1 ) ; head1 = mergelists ( & head1 , & head2 ) ; sortlist ( & head1 ) ; setData ( head1 ) ; return 0 ; } |
Find K elements whose absolute difference with median of array is maximum | C ++ implementation to find first K elements whose difference with the median of array is maximum ; Function for calculating median ; check for even case ; Function to find the K maximum absolute difference with the median of the array ; Sort the array . ; Store median ; Find and store difference ; If diff [ i ] is greater print it Else print diff [ j ] ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double findMedian ( int a [ ] , int n ) { if ( n % 2 != 0 ) return ( double ) a [ n / 2 ] ; return ( double ) ( a [ ( n - 1 ) / 2 ] + a [ n / 2 ] ) / 2.0 ; } void kStrongest ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; double median = findMedian ( arr , n ) ; int diff [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { diff [ i ] = abs ( median - arr [ i ] ) ; } int i = 0 , j = n - 1 ; while ( k > 0 ) { if ( diff [ i ] > diff [ j ] ) { cout << arr [ i ] << " β " ; i ++ ; } else { cout << arr [ j ] << " β " ; j -- ; } k -- ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int k = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; kStrongest ( arr , n , k ) ; return 0 ; } |
Sort an array by swapping elements of different type specified by another array | C ++ program to check if it is possible to sort the array in non - decreasing order by swapping elements of different types ; Function to check if it is possible to sort the array in non - decreasing order by swapping elements of different types ; Consider the array to be already sorted ; checking if array is already sorted ; Check for a pair which is in decreasing order ; Count the frequency of each type of element ; type0 stores count of elements of type 0 ; type1 stores count of elements of type 1 ; Return true if array is already sorted ; Return false if all elements are of same type and array is unsorted ; Possible for all other cases ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool sorting_possible ( int a [ ] , int b [ ] , int n ) { bool sorted = true ; int type1 = 0 , type0 = 0 , i ; for ( i = 1 ; i < n ; i ++ ) { if ( a [ i ] < a [ i - 1 ] ) { sorted = false ; break ; } } for ( i = 0 ; i < n ; i ++ ) { if ( b [ i ] == 0 ) type0 ++ ; else type1 ++ ; } if ( sorted ) return true ; else if ( type1 == n type0 == n ) return false ; else return true ; } int main ( ) { int a [ ] = { 15 , 1 , 2 , 17 , 6 } ; int b [ ] = { 1 , 1 , 0 , 1 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; bool res = sorting_possible ( a , b , n ) ; if ( res ) cout << " Yes " ; else cout << " No " ; } |
Shortest path in a directed graph by DijkstraΓ’ β¬β’ s algorithm | C ++ implementation to find the shortest path in a directed graph from source vertex to the destination vertex ; Class of the node ; Adjacency list that shows the vertexNumber of child vertex and the weight of the edge ; Function to add the child for the given node ; Function to find the distance of the node from the given source vertex to the destination vertex ; Stores distance of each vertex from source vertex ; Boolean array that shows whether the vertex ' i ' is visited or not ; Set of vertices that has a parent ( one or more ) marked as visited ; Mark current as visited ; Inserting into the visited vertex ; Condition to check the distance is correct and update it if it is minimum from the previous computed distance ; The new current ; Loop to update the distance of the vertices of the graph ; Function to print the path from the source vertex to the destination vertex ; Condition to check if there is no path between the vertices ; Driver Code ; Loop to create the nodes ; Creating directed weighted edges ; Loop to print the distance of every node from source vertex | #include <bits/stdc++.h> NEW_LINE #define infi 1000000000 NEW_LINE using namespace std ; class Node { public : int vertexNumber ; vector < pair < int , int > > children ; Node ( int vertexNumber ) { this -> vertexNumber = vertexNumber ; } void add_child ( int vNumber , int length ) { pair < int , int > p ; p . first = vNumber ; p . second = length ; children . push_back ( p ) ; } } ; vector < int > dijkstraDist ( vector < Node * > g , int s , vector < int > & path ) { vector < int > dist ( g . size ( ) ) ; bool visited [ g . size ( ) ] ; for ( int i = 0 ; i < g . size ( ) ; i ++ ) { visited [ i ] = false ; path [ i ] = -1 ; dist [ i ] = infi ; } dist [ s ] = 0 ; path [ s ] = -1 ; int current = s ; unordered_set < int > sett ; while ( true ) { visited [ current ] = true ; for ( int i = 0 ; i < g [ current ] -> children . size ( ) ; i ++ ) { int v = g [ current ] -> children [ i ] . first ; if ( visited [ v ] ) continue ; sett . insert ( v ) ; int alt = dist [ current ] + g [ current ] -> children [ i ] . second ; if ( alt < dist [ v ] ) { dist [ v ] = alt ; path [ v ] = current ; } } sett . erase ( current ) ; if ( sett . empty ( ) ) break ; int minDist = infi ; int index = 0 ; for ( int a : sett ) { if ( dist [ a ] < minDist ) { minDist = dist [ a ] ; index = a ; } } current = index ; } return dist ; } void printPath ( vector < int > path , int i , int s ) { if ( i != s ) { if ( path [ i ] == -1 ) { cout << " Path β not β found ! ! " ; return ; } printPath ( path , path [ i ] , s ) ; cout << path [ i ] << " β " ; } } int main ( ) { vector < Node * > v ; int n = 4 , s = 0 , e = 5 ; for ( int i = 0 ; i < n ; i ++ ) { Node * a = new Node ( i ) ; v . push_back ( a ) ; } v [ 0 ] -> add_child ( 1 , 1 ) ; v [ 0 ] -> add_child ( 2 , 4 ) ; v [ 1 ] -> add_child ( 2 , 2 ) ; v [ 1 ] -> add_child ( 3 , 6 ) ; v [ 2 ] -> add_child ( 3 , 3 ) ; vector < int > path ( v . size ( ) ) ; vector < int > dist = dijkstraDist ( v , s , path ) ; for ( int i = 0 ; i < dist . size ( ) ; i ++ ) { if ( dist [ i ] == infi ) { cout << i << " β and β " << s << " β are β not β connected " << endl ; continue ; } cout << " Distance β of β " << i << " th β vertex β from β source β vertex β " << s << " β is : β " << dist [ i ] << endl ; } return 0 ; } |
Sort permutation of N natural numbers using triple cyclic right swaps | C ++ implementation to find the number of operations required to sort the elements of the array ; Function to sort the permutation with the given operations ; Visited array to check the array element is at correct position or not ; Loop to iterate over the elements of the given array ; Condition to check if the elements is at its correct position ; Condition to check if the element is included in any previous cyclic rotations ; Loop to find the cyclic rotations in required ; Condition to check if the cyclic rotation is a valid rotation ; Loop to find the index of the cyclic rotation for the current index ; Condition to if the cyclic rotation is a valid rotation ; Loop to find all the valid operations required to sort the permutation ; Total operation required ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE void sortPermutation ( ll arr [ ] , ll n ) { vector < pair < ll , pair < ll , ll > > > ans ; vector < ll > p ; bool visited [ 200005 ] = { 0 } ; for ( ll i = 1 ; i <= n ; i ++ ) { if ( arr [ i ] == i ) { visited [ i ] = 1 ; continue ; } else { if ( ! visited [ i ] ) { ll x = i ; vector < ll > v ; while ( ! visited [ x ] ) { visited [ x ] = 1 ; v . push_back ( x ) ; x = arr [ x ] ; } if ( ( v . size ( ) - 3 ) % 2 == 0 ) { for ( ll i = 1 ; i < v . size ( ) ; i += 2 ) { ans . push_back ( make_pair ( v [ 0 ] , make_pair ( v [ i ] , v [ i + 1 ] ) ) ) ; } continue ; } p . push_back ( v [ 0 ] ) ; p . push_back ( v [ v . size ( ) - 1 ] ) ; for ( ll i = 1 ; i < v . size ( ) - 1 ; i += 2 ) { ans . push_back ( make_pair ( v [ 0 ] , make_pair ( v [ i ] , v [ i + 1 ] ) ) ) ; } } } } if ( p . size ( ) % 4 ) { cout << -1 << " STRNEWLINE " ; return ; } for ( ll i = 0 ; i < p . size ( ) ; i += 4 ) { ans . push_back ( make_pair ( p [ i ] , make_pair ( p [ i + 1 ] , p [ i + 2 ] ) ) ) ; ans . push_back ( make_pair ( p [ i + 2 ] , make_pair ( p [ i ] , p [ i + 3 ] ) ) ) ; } cout << ans . size ( ) << " STRNEWLINE " ; for ( ll i = 0 ; i < ans . size ( ) ; i ++ ) { cout << ans [ i ] . first << " β " << ans [ i ] . second . first << " β " << ans [ i ] . second . second << " STRNEWLINE " ; } } int main ( ) { ll arr [ ] = { 0 , 3 , 2 , 4 , 1 } ; ll n = 4 ; sortPermutation ( arr , n ) ; return 0 ; } |
Maximize array sum by X increments when each element is divided by 10 | C ++ program for the above problem ; initialize variables ; add the current contribution of the element to the answer ; if the value is already maximum then we can 't change it ; moves required to move to the next multiple of 10 ; no of times we can add 10 to this value so that its value does not exceed 1000. ; sort the array ; adding the values to increase the numbers to the next multiple of 10 ; if the total moves are less than X then increase the answer ; if the moves exceed X then we cannot increase numbers ; if there still remain some moves ; remaining moves ; add minimim of increments and remaining / 10 to the answer ; output the final answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maximizeval10 ( int a [ ] , int n , int k ) { int increments = 0 ; int ans = 0 ; vector < int > v ; for ( int i = 0 ; i < n ; i ++ ) { ans += ( a [ i ] / 10 ) ; if ( a [ i ] == 1000 ) continue ; else { v . push_back ( 10 - a [ i ] % 10 ) ; increments += ( 100 - ( ( a [ i ] ) / 10 ) - 1 ) ; } } sort ( v . begin ( ) , v . end ( ) ) ; int sum = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { sum += v [ i ] ; if ( sum <= k ) { ans ++ ; } else break ; } if ( sum < k ) { int remaining = k - sum ; ans += min ( increments , remaining / 10 ) ; } cout << ans ; } int main ( ) { int N = 4 ; int X = 6 ; int A [ N ] = { 4 , 8 , 8 , 8 } ; maximizeval10 ( A , N , X ) ; return 0 ; } |
Split array into two subarrays such that difference of their maximum is minimum | C ++ Program to split a given array such that the difference between their maximums is minimized . ; Sort the array ; Return the difference between two highest elements ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinDif ( int arr [ ] , int N ) { sort ( arr , arr + N ) ; return ( arr [ N - 1 ] - arr [ N - 2 ] ) ; } int main ( ) { int arr [ ] = { 7 , 9 , 5 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMinDif ( arr , N ) ; return 0 ; } |
Count of available non | C ++ implementation of the above approach ; Function to find the pivot index ; Function to implement Quick Sort ; Pivot is pointing to pivot index before which every element is smaller and after pivot , every element is greater ; Sort the array before pivot element ; Sort the array after pivot element ; Function to count the available intervals from the given range of numbers ; If range starts after 0 then an interval is available from 0 to start [ 0 ] ; When a new interval starts ; Since index variable i is being incremented , the current active interval will also get incremented ; When the current interval ends ; Since index variable j is being decremented , the currect active interval will also get decremented ; When start and end both are same there is no change in currActive ; If the end of interval is before the range so interval is available at the end ; Driver code ; Sort the start array ; Sort the end array ; Calling the function | #include <iostream> NEW_LINE using namespace std ; int partition ( int arr [ ] , int l , int h ) { int pivot = arr [ l ] ; int i = l + 1 ; int j = h ; while ( i <= j ) { while ( i <= h && arr [ i ] < pivot ) { i ++ ; } while ( j > l && arr [ j ] > pivot ) { j -- ; } if ( i < j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; i ++ ; j -- ; } else i ++ ; } arr [ l ] = arr [ j ] ; arr [ j ] = pivot ; return j ; } void sortArray ( int arr [ ] , int l , int h ) { if ( l >= h ) return ; int pivot = partition ( arr , l , h ) ; sortArray ( arr , l , pivot - 1 ) ; sortArray ( arr , pivot + 1 , h ) ; } int findMaxIntervals ( int start [ ] , int end [ ] , int n , int R ) { int ans = 0 ; int prev = 0 ; int currActive = 0 ; int i = 0 ; int j = 0 ; if ( start [ 0 ] > 0 ) ans ++ ; while ( i < n && j < n ) { if ( start [ i ] < end [ j ] ) { i ++ ; currActive ++ ; } else if ( start [ i ] > end [ j ] ) { j ++ ; currActive -- ; } else { i ++ ; j ++ ; } if ( currActive == 0 ) { ans ++ ; } } if ( end [ n - 1 ] < R ) ans ++ ; return ans ; } int main ( ) { int R , N ; R = 10 ; N = 3 ; int start [ N ] = { 2 , 5 , 8 } ; int end [ N ] = { 3 , 9 , 10 } ; sortArray ( start , 0 , N - 1 ) ; sortArray ( end , 0 , N - 1 ) ; cout << findMaxIntervals ( start , end , N , R ) ; } |
Maximum items that can be bought from the cost Array based on given conditions | C ++ program to find the maximum number of items that can be bought from the given cost array ; Function to find the maximum number of items that can be bought from the given cost array ; Sort the given array ; Variables to store the prefix sum , answer and the counter variables ; Initializing the first element of the prefix array ; If we can buy at least one item ; Iterating through the first K items and finding the prefix sum ; Check the number of items that can be bought ; Finding the prefix sum for the remaining elements ; Check the number of iteams that can be bought ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int number ( int a [ ] , int n , int p , int k ) { sort ( a , a + n ) ; int pre [ n ] = { 0 } , val , i , j , ans = 0 ; pre [ 0 ] = a [ 0 ] ; if ( pre [ 0 ] <= p ) ans = 1 ; for ( i = 1 ; i < k - 1 ; i ++ ) { pre [ i ] = pre [ i - 1 ] + a [ i ] ; if ( pre [ i ] <= p ) ans = i + 1 ; } pre [ k - 1 ] = a [ k - 1 ] ; for ( i = k - 1 ; i < n ; i ++ ) { if ( i >= k ) { pre [ i ] += pre [ i - k ] + a [ i ] ; } if ( pre [ i ] <= p ) ans = i + 1 ; } return ans ; } int main ( ) { int n = 5 ; int arr [ ] = { 2 , 4 , 3 , 5 , 7 } ; int p = 11 ; int k = 2 ; cout << number ( arr , n , p , k ) << endl ; return 0 ; } |
Sort all special primes in their relative positions | C ++ implementation of the approach ; Function for the Sieve of Eratosthenes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to sort the special primes in their relative positions ; Maximum element from the array ; prime [ i ] will be true if i is a prime ; To store the special primes from the array ; If current element is a special prime ; Add it to the ArrayList and set arr [ i ] to - 1 ; Sort the special primes ; Position of a special prime ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sieveOfEratosthenes ( bool prime [ ] , int n ) { prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } } void sortSpecialPrimes ( int arr [ ] , int n ) { int maxVal = * max_element ( arr , arr + n ) ; bool prime [ maxVal + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; sieveOfEratosthenes ( prime , maxVal ) ; vector < int > list ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] && prime [ arr [ i ] - 2 ] ) { list . push_back ( arr [ i ] ) ; arr [ i ] = -1 ; } } sort ( list . begin ( ) , list . end ( ) ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == -1 ) cout << list [ j ++ ] << " β " ; else cout << arr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 31 , 5 , 2 , 1 , 7 } ; int n = sizeof ( arr ) / sizeof ( int ) ; sortSpecialPrimes ( arr , n ) ; return 0 ; } |
Find the Maximum possible Sum for the given conditions | C ++ program to find the maximum possible Sum for the given conditions ; Function to find the maximum possible sum for the given conditions ; Sorting the array ; Variable to store the answer ; Iterating through the array ; If the value is greater than 0 ; If the value becomes 0 then break the loop because all the weights after this index will be 0 ; Print profit ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProfit ( int arr [ ] , int n ) { sort ( arr , arr + n , greater < int > ( ) ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] - ( 1 * i ) ) > 0 ) ans += ( arr [ i ] - ( 1 * i ) ) ; if ( ( arr [ i ] - ( 1 * i ) ) == 0 ) break ; } return ans ; } int main ( ) { int arr [ ] = { 6 , 6 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxProfit ( arr , n ) ; return 0 ; } |
Check if the array can be sorted only if the elements on given positions can be swapped | C ++ program to check if the array can be sorted only if the elements on the given positions can be swapped ; Function to check if the array can be sorted only if the elements on the given positions can be swapped ; Creating an array for marking the positions ; Iterating through the array and mark the positions ; Iterating through the given array ; If pos [ i ] is 1 , then incrementing till 1 is continuously present in pos ; Sorting the required segment ; Checking if the vector is sorted or not ; Print yes if it is sorted ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void check_vector ( vector < int > A , int n , vector < int > p ) { vector < int > pos ( A . size ( ) ) ; for ( int i = 0 ; i < p . size ( ) ; i ++ ) { pos [ p [ i ] - 1 ] = 1 ; } int flag = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( pos [ i ] == 0 ) continue ; int j = i ; while ( j < n && pos [ j ] ) ++ j ; sort ( A . begin ( ) + i , A . begin ( ) + j + 1 ) ; i = j ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { flag = 0 ; break ; } } if ( flag == 1 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { vector < int > A { 3 , 2 , 1 } ; vector < int > p { 1 , 2 } ; check_vector ( A , A . size ( ) , p ) ; return 0 ; } |
Sort an array of strings based on the given order | C ++ program to sort an array of strings based on the given order ; For storing priority of each character ; Custom comparator function for sort ; Loop through the minimum size between two words ; Check if the characters at position i are different , then the word containing lower valued character is smaller ; When loop breaks without returning , it means the prefix of both words were same till the execution of the loop . Now , the word with the smaller size will occur before in sorted order ; Function to print the new sorted array of strings ; Mapping each character to its occurrence position ; Sorting with custom sort function ; Printing the sorted order of words ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_map < char , int > mp ; bool comp ( string & a , string & b ) { for ( int i = 0 ; i < min ( a . size ( ) , b . size ( ) ) ; i ++ ) { if ( mp [ a [ i ] ] != mp [ b [ i ] ] ) return mp [ a [ i ] ] < mp [ b [ i ] ] ; } return ( a . size ( ) < b . size ( ) ) ; } void printSorted ( vector < string > words , string order ) { for ( int i = 0 ; i < order . size ( ) ; i ++ ) mp [ order [ i ] ] = i ; sort ( words . begin ( ) , words . end ( ) , comp ) ; for ( auto x : words ) cout << x << " β " ; } int main ( ) { vector < string > words = { " word " , " world " , " row " } ; string order = { " worldabcefghijkmnpqstuvxyz " } ; printSorted ( words , order ) ; return 0 ; } |
Sort elements of an array in increasing order of absolute difference of adjacent elements | C ++ implementation to sort the elements of the array in such a way that absolute difference between the adjacent elements are in increasing order ; Function to sort the elements of the array by difference ; Sorting the array ; Array to store the elements of the array ; Iterating over the length of the array to include each middle element of array ; Appending the middle element of the array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortDiff ( vector < int > arr , int n ) { sort ( arr . begin ( ) , arr . end ( ) ) ; vector < int > out ; while ( n > 0 ) { out . push_back ( arr [ n / 2 ] ) ; arr . erase ( arr . begin ( ) + n / 2 ) ; n = n - 1 ; } for ( auto i : out ) cout << i << " β " ; } int main ( ) { vector < int > a = { 8 , 1 , 2 , 3 , 0 } ; int n = 5 ; sortDiff ( a , n ) ; } |
Minimum cost of choosing the array element | C ++ program for the above approach ; Function that find the minimum cost of selecting array element ; Sorting the given array in increasing order ; To store the prefix sum of arr [ ] ; Update the pref [ ] to find the cost selecting array element by selecting at most M element ; Print the pref [ ] for the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumCost ( int arr [ ] , int N , int M ) { sort ( arr , arr + N ) ; int pref [ N ] ; pref [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { pref [ i ] = arr [ i ] + pref [ i - 1 ] ; } for ( int i = M ; i < N ; i ++ ) { pref [ i ] += pref [ i - M ] ; } for ( int i = 0 ; i < N ; i ++ ) { cout << pref [ i ] << ' β ' ; } } int main ( ) { int arr [ ] = { 6 , 19 , 3 , 4 , 4 , 2 , 6 , 7 , 8 } ; int M = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumCost ( arr , N , M ) ; return 0 ; } |
Sort an Array alphabetically when each number is converted into words | C ++ program to sort an array of integers alphabetically ; Variable to store the word form of units digit and up to twenty ; Variable to store the word form of tens digit ; Function to convert a two digit number to the word by using the above defined arrays ; If n is more than 19 , divide it ; If n is non - zero ; Function to print a given number in words ; Stores the word representation of the given number n ; Handles digits at ten millions and hundred millions places ; Handles digits at hundred thousands and one millions places ; Handles digits at thousands and tens thousands places ; Handles digit at hundreds places ; Call the above function to convert the number into words ; Function to sort the array according to the albhabetical order ; Vector to store the number in words with respective elements ; Inserting number in words with respective elements in vector pair ; Sort the vector , this will sort the pair according to the alphabetical order . ; Print the sorted vector content ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string one [ ] = { " " , " one β " , " two β " , " three β " , " four β " , " five β " , " six β " , " seven β " , " eight β " , " nine β " , " ten β " , " eleven β " , " twelve β " , " thirteen β " , " fourteen β " , " fifteen β " , " sixteen β " , " seventeen β " , " eighteen β " , " nineteen β " } ; string ten [ ] = { " " , " " , " twenty β " , " thirty β " , " forty β " , " fifty β " , " sixty β " , " seventy β " , " eighty β " , " ninety β " } ; string numToWords ( int n , string s ) { string str = " " ; if ( n > 19 ) str += ten [ n / 10 ] + one [ n % 10 ] ; else str += one [ n ] ; if ( n ) str += s ; return str ; } string convertToWords ( int n ) { string out ; out += numToWords ( ( n / 10000000 ) , " crore β " ) ; out += numToWords ( ( ( n / 100000 ) % 100 ) , " lakh β " ) ; out += numToWords ( ( ( n / 1000 ) % 100 ) , " thousand β " ) ; out += numToWords ( ( ( n / 100 ) % 10 ) , " hundred β " ) ; if ( n > 100 && n % 100 ) out += " and β " ; out += numToWords ( ( n % 100 ) , " " ) ; return out ; } void sortArr ( int arr [ ] , int n ) { vector < pair < string , int > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( convertToWords ( arr [ i ] ) , arr [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second << " β " ; } int main ( ) { int arr [ ] = { 12 , 10 , 102 , 31 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; } |
Maximum Possible Rating of a Coding Contest | C ++ program to find the Maximum Possible Rating of a Coding Contest ; Function to sort all problems descending to upvotes ; Function to return maximum rating ; Declaring vector of pairs ; Each pair represents a problem with its points and upvotes ; Step ( 1 ) - Sort problems by their upvotes value in decreasing order ; Declaring min_heap or priority queue to track of the problem with minimum points . ; Step ( 2 ) - Loop for i = 0 to K - 1 and do accordingly ; Step ( 3 ) - Loop for i = K to N - 1 and do accordingly ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool Comparator ( pair < int , int > p1 , pair < int , int > p2 ) { return p1 . second > p2 . second ; } int FindMaxRating ( int N , int Point [ ] , int Upvote [ ] , int K ) { vector < pair < int , int > > vec ; for ( int i = 0 ; i < N ; i ++ ) { vec . push_back ( make_pair ( Point [ i ] , Upvote [ i ] ) ) ; } sort ( vec . begin ( ) , vec . end ( ) , Comparator ) ; priority_queue < int , vector < int > , greater < int > > pq ; int total_points = 0 , max_rating = 0 ; for ( int i = 0 ; i < K ; i ++ ) { total_points = total_points + vec [ i ] . first ; max_rating = max ( max_rating , total_points * vec [ i ] . second ) ; pq . push ( vec [ i ] . first ) ; } for ( int i = K ; i < N ; i ++ ) { if ( pq . top ( ) < vec [ i ] . first ) { total_points = total_points - pq . top ( ) + vec [ i ] . first ; max_rating = max ( max_rating , total_points * vec [ i ] . second ) ; pq . pop ( ) ; pq . push ( vec [ i ] . first ) ; } } return max_rating ; } int main ( ) { int Point [ ] = { 2 , 10 , 3 , 1 , 5 , 8 } ; int Upvote [ ] = { 5 , 4 , 3 , 9 , 7 , 2 } ; int N = sizeof ( Point ) / sizeof ( Point [ 0 ] ) ; int K = 2 ; cout << " Maximum β Rating β of β Coding β Contest β is : β " << FindMaxRating ( N , Point , Upvote , K ) ; return 0 ; } |
Find sum of all unique elements in the array for K queries | C ++ implementation to find the sum of all unique elements of the array after Q queries ; Function to find the sum of unique elements after Q Query ; Updating the array after processing each query ; Making it to 0 - indexing ; Iterating over the array to get the final array ; Variable to store the sum ; Hash to maintain perviously occured elements ; Loop to find the maximum sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int uniqueSum ( int A [ ] , int R [ ] [ 2 ] , int N , int M ) { for ( int i = 0 ; i < M ; ++ i ) { int l = R [ i ] [ 0 ] , r = R [ i ] [ 1 ] + 1 ; l -- ; r -- ; A [ l ] ++ ; if ( r < N ) A [ r ] -- ; } for ( int i = 1 ; i < N ; ++ i ) { A [ i ] += A [ i - 1 ] ; } int ans = 0 ; unordered_set < int > s ; for ( int i = 0 ; i < N ; ++ i ) { if ( s . find ( A [ i ] ) == s . end ( ) ) ans += A [ i ] ; s . insert ( A [ i ] ) ; } return ans ; } int main ( ) { int A [ ] = { 0 , 0 , 0 , 0 , 0 , 0 } ; int R [ ] [ 2 ] = { { 1 , 3 } , { 4 , 6 } , { 3 , 4 } , { 3 , 3 } } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int M = sizeof ( R ) / sizeof ( R [ 0 ] ) ; cout << uniqueSum ( A , R , N , M ) ; return 0 ; } |
Find the Kth pair in ordered list of all possible sorted pairs of the Array | C ++ program to find the K - th pair in a lexicographically sorted array ; Function to find the k - th pair ; Sorting the array ; Iterating through the array ; Finding the number of same elements ; Checking if N * T is less than the remaining K . If it is , then arr [ i ] is the first element in the required pair ; Printing the K - th pair ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void kthpair ( int n , int k , int arr [ ] ) { int i , t ; sort ( arr , arr + n ) ; -- k ; for ( i = 0 ; i < n ; i += t ) { for ( t = 1 ; arr [ i ] == arr [ i + t ] ; ++ t ) ; if ( t * n > k ) break ; k = k - t * n ; } cout << arr [ i ] << ' β ' << arr [ k / t ] ; } int main ( ) { int n = 3 , k = 2 ; int arr [ n ] = { 3 , 1 , 5 } ; kthpair ( n , k , arr ) ; } |
Minimum characters to be replaced to make frequency of all characters same | C ++ implementation to find the Minimum characters to be replaced to make frequency of all characters same ; Function to find the Minimum operations to convert given string to another with equal frequencies of characters ; Frequency of characters ; Loop to find the Frequency of each character ; Sort in decreasing order based on frequency ; Maximum possible answer ; Loop to find the minimum operations required such that frequency of every character is equal ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( string s ) { int freq [ 26 ] = { 0 } ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { freq [ s [ i ] - ' A ' ] ++ ; } sort ( freq , freq + 26 , greater < int > ( ) ) ; int answer = n ; for ( int i = 1 ; i <= 26 ; i ++ ) { if ( n % i == 0 ) { int x = n / i ; int y = 0 ; for ( int j = 0 ; j < i ; j ++ ) { y += min ( freq [ j ] , x ) ; } answer = min ( answer , n - y ) ; } } return answer ; } int main ( ) { string s = " BBC " ; cout << minOperations ( s ) ; return 0 ; } |
Check if it is possible to sort an array with conditional swapping of elements at distance K | CPP implementation to Check if it is possible to sort an array with conditional swapping of elements at distance K ; Function for finding if it possible to obtain sorted array or not ; Iterate over all elements until K ; Store elements as multiples of K ; Sort the elements ; Put elements in their required position ; Check if the array becomes sorted or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool fun ( int arr [ ] , int n , int k ) { vector < int > v ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = i ; j < n ; j += k ) { v . push_back ( arr [ j ] ) ; } sort ( v . begin ( ) , v . end ( ) ) ; int x = 0 ; for ( int j = i ; j < n ; j += k ) { arr [ j ] = v [ x ] ; x ++ ; } v . clear ( ) ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) return false ; } return true ; } int main ( ) { int arr [ ] = { 4 , 2 , 3 , 7 , 6 } ; int K = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( fun ( arr , n , K ) ) cout << " yes " << endl ; else cout << " no " << endl ; return 0 ; } |
Sort an Array based on the absolute difference of adjacent elements | C ++ implementation of the above approach ; Function that arrange the array such that all absolute difference between adjacent element are sorted ; To store the resultant array ; Sorting the given array in ascending order ; Variable to represent left and right ends of the given array ; Traversing the answer array in reverse order and arrange the array elements from arr [ ] in reverse order ; Inserting elements in zig - zag manner ; Displaying the resultant array ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortedAdjacentDifferences ( int arr [ ] , int n ) { int ans [ n ] ; sort ( arr + 0 , arr + n ) ; int l = 0 , r = n - 1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i % 2 ) { ans [ i ] = arr [ l ] ; l ++ ; } else { ans [ i ] = arr [ r ] ; r -- ; } } for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 5 , -2 , 4 , 8 , 6 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortedAdjacentDifferences ( arr , n ) ; return 0 ; } |
Minimum steps to convert an Array into permutation of numbers from 1 to N | C ++ program to find minimum number of steps to convert a given sequence into a permutation ; Function to find minimum number of steps to convert a given sequence into a permutation ; Sort the given array ; To store the required minimum number of operations ; Find the operations on each step ; Return the answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int get_permutation ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { result += abs ( arr [ i ] - ( i + 1 ) ) ; } return result ; } int main ( ) { int arr [ ] = { 0 , 2 , 3 , 4 , 1 , 6 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << get_permutation ( arr , n ) ; return 0 ; } |
Minimum increment or decrement required to sort the array | Top | C ++ program of the above approach ; Dp array to memoized the value recursive call ; Function to find the minimum increment or decrement needed to make the array sorted ; If only one element is present , then arr [ ] is sorted ; If dp [ N ] [ maxE ] is precalculated , then return the result ; Iterate from minE to maxE which placed at previous index ; Update the answer according to recurrence relation ; Memoized the value for dp [ N ] [ maxE ] ; Return the final result ; Driver Code ; Find the minimum and maximum element from the arr [ ] ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 1000 ] [ 1000 ] ; int minimumIncDec ( int arr [ ] , int N , int maxE , int minE ) { if ( N == 0 ) { return 0 ; } if ( dp [ N ] [ maxE ] ) return dp [ N ] [ maxE ] ; int ans = INT_MAX ; for ( int k = minE ; k <= maxE ; k ++ ) { int x = minimumIncDec ( arr , N - 1 , k , minE ) ; ans = min ( ans , x + abs ( arr [ N - 1 ] - k ) ) ; } dp [ N ] [ maxE ] = ans ; return dp [ N ] [ maxE ] ; } int main ( ) { int arr [ ] = { 5 , 4 , 3 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int minE = * min_element ( arr , arr + N ) ; int maxE = * max_element ( arr , arr + N ) ; cout << minimumIncDec ( arr , N , maxE , minE ) ; return 0 ; } |
Sort the major diagonal of the matrix | C ++ implementation to sort the major diagonal of the matrix ; Function to sort the major diagonal of the matrix ; Loop to find the ith minimum element from the major diagonal ; Loop to find the minimum element from the unsorted matrix ; Swap to put the minimum element at the beginning of the major diagonal of matrix ; Loop to print the matrix ; Driven Code ; Sort the major Diagonal | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortDiagonal ( int a [ 2 ] [ 2 ] , int M , int N ) { for ( int i = 0 ; i < M ; i ++ ) { int sm = a [ i ] [ i ] ; int pos = i ; for ( int j = i + 1 ; j < N ; j ++ ) { if ( sm > a [ j ] [ j ] ) { sm = a [ j ] [ j ] ; pos = j ; } } swap ( a [ i ] [ i ] , a [ pos ] [ pos ] ) ; } for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) cout << a [ i ] [ j ] << " β " ; cout << endl ; } } int main ( ) { int a [ 2 ] [ 2 ] = { { 4 , 2 } , { 3 , 1 } } ; sortDiagonal ( a , 2 , 2 ) ; return 0 ; } |
Minimum cost to make an Array a permutation of first N natural numbers | C ++ program to calculate minimum cost to make an Array a permutation of first N natural numbers ; Function to calculate minimum cost for making permutation of size N ; sorting the array in ascending order ; To store the required answer ; Traverse the whole array ; Return the required answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int make_permutation ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans += abs ( i + 1 - arr [ i ] ) ; return ans ; } int main ( ) { int arr [ ] = { 5 , 3 , 8 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << make_permutation ( arr , n ) ; } |
Find maximum sum from top to bottom row with no adjacent diagonal elements | C ++ implementation to find maximum sum from top to bottom row with no adjacent diagonal elements ; Function to find the maximum path sum from top to bottom row ; Create an auxiliary array of next row with the element and it 's position ; Sort the auxiliary array ; Find maximum from row above to be added to the current element ; Find the maximum element from the next row that can be added to current row element ; Find the maximum sum ; Driver Code ; Function to find maximum path | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( vector < vector < int > > & V , int n , int m ) { int ans = 0 ; for ( int i = n - 2 ; i >= 0 ; -- i ) { vector < pair < int , int > > aux ; for ( int j = 0 ; j < m ; ++ j ) { aux . push_back ( { V [ i + 1 ] [ j ] , j } ) ; } sort ( aux . begin ( ) , aux . end ( ) ) ; reverse ( aux . begin ( ) , aux . end ( ) ) ; for ( int j = 0 ; j < m ; ++ j ) { for ( int k = 0 ; k < m ; ++ k ) { if ( aux [ k ] . second - j == 0 || abs ( aux [ k ] . second - j ) > 1 ) { V [ i ] [ j ] += aux [ k ] . first ; break ; } } } } for ( int i = 0 ; i < m ; ++ i ) { ans = max ( ans , V [ 0 ] [ i ] ) ; } return ans ; } int main ( ) { vector < vector < int > > V { { 1 , 2 , 3 , 4 } , { 8 , 7 , 6 , 5 } , { 10 , 11 , 12 , 13 } } ; int n = V . size ( ) ; int m = V [ 0 ] . size ( ) ; cout << maxSum ( V , n , m ) ; return 0 ; } |
Count numbers whose maximum sum of distinct digit | C ++ implementation to find the Maximum count of numbers whose sum of distinct digit - sum less than or equal to the given number ; Function to find the digit - sum of a number ; Loop to iterate the number digit - wise to find digit - sum ; variable to store last digit ; Function to find the count of number ; Vector to store the Sum of Digits ; Sum of digits for each element in vector ; Sorting the digitSum vector ; Removing the duplicate elements ; Count variable to store the Count ; Finding the Count of Numbers ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int SumofDigits ( int digit ) { int sum = 0 ; while ( digit != 0 ) { int rem = digit % 10 ; sum += rem ; digit /= 10 ; } return sum ; } int findCountofNumbers ( int arr [ ] , int n , int M ) { vector < int > SumDigits ; for ( int i = 0 ; i < n ; i ++ ) { int s = SumofDigits ( arr [ i ] ) ; SumDigits . push_back ( s ) ; } sort ( SumDigits . begin ( ) , SumDigits . end ( ) ) ; vector < int > :: iterator ip ; ip = unique ( SumDigits . begin ( ) , SumDigits . end ( ) ) ; SumDigits . resize ( distance ( SumDigits . begin ( ) , ip ) ) ; int count = 0 ; int sum = 0 ; for ( int i = 0 ; i < SumDigits . size ( ) ; i ++ ) { if ( sum > M ) break ; sum += SumDigits [ i ] ; if ( sum <= M ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 1 , 45 , 16 , 17 , 219 , 32 , 22 } , M = 10 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findCountofNumbers ( arr , n , M ) ; return 0 ; } |
Minimum sum of product of elements of pairs of the given array | C ++ program to find the minimum product of sum of pair of element in array arr [ ] ; Function to find the minimum product ; Sort the array using STL sort ( ) function ; Initialise product to 1 ; Find product of sum of all pairs ; Return the product ; Driver code ; Function call to find product | #include " bits / stdc + + . h " NEW_LINE using namespace std ; int minimumProduct ( int * arr , int n ) { sort ( arr , arr + n ) ; int product = 1 ; for ( int i = 0 ; i < n ; i += 2 ) { product *= ( arr [ i ] + arr [ i + 1 ] ) ; } return product ; } int main ( ) { int arr [ ] = { 1 , 6 , 3 , 1 , 7 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumProduct ( arr , n ) << endl ; return 0 ; } |
Minimum removals required to make ranges non | ; Sort by minimum starting point ; If the current starting point is less than the previous interval 's ending point (ie. there is an overlap) ; increase rem ; Remove the interval with the higher ending point ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minRemovals ( vector < vector < int > > & ranges ) { int size = ranges . size ( ) , rem = 0 ; if ( size <= 1 ) return 0 ; sort ( ranges . begin ( ) , ranges . end ( ) , [ ] ( const vector < int > & a , const vector < int > & b ) { return a [ 0 ] < b [ 0 ] ; } ) ; int end = ranges [ 0 ] [ 1 ] ; for ( int i = 1 ; i < ranges . size ( ) ; i ++ ) { if ( ranges [ i ] [ 0 ] < end ) { rem ++ ; end = min ( ranges [ i ] [ 1 ] , end ) ; } else end = ranges [ i ] [ 1 ] ; } return rem ; } int main ( ) { vector < vector < int > > input = { { 19 , 25 } , { 10 , 20 } , { 16 , 20 } } ; cout << minRemovals ( input ) << endl ; } |
Check if elements of array can be arranged in AP , GP or HP | C ++ program to check if a given array form AP , GP or HP ; Returns true if arr [ 0. . n - 1 ] can form AP ; Base Case ; Sort array ; After sorting , difference between consecutive elements must be same . ; Traverse the given array and check if the difference between ith element and ( i - 1 ) th element is same or not ; Returns true if arr [ 0. . n - 1 ] can form GP ; Base Case ; Sort array ; After sorting , common ratio between consecutive elements must be same . ; Traverse the given array and check if the common ratio between ith element and ( i - 1 ) th element is same or not ; Returns true if arr [ 0. . n - 1 ] can form HP ; Base Case ; Find reciprocal of arr [ ] ; After finding reciprocal , check if the reciprocal is in A . P . To check for A . P . ; Driver 's Code ; Function to check AP ; Function to check GP ; Function to check HP | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkIsAP ( double arr [ ] , int n ) { if ( n == 1 ) return true ; sort ( arr , arr + n ) ; double d = arr [ 1 ] - arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i ] - arr [ i - 1 ] != d ) { return false ; } } return true ; } bool checkIsGP ( double arr [ ] , int n ) { if ( n == 1 ) return true ; sort ( arr , arr + n ) ; double r = arr [ 1 ] / arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i ] / arr [ i - 1 ] != r ) return false ; } return true ; } bool checkIsHP ( double arr [ ] , int n ) { if ( n == 1 ) { return true ; } double rec [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { rec [ i ] = ( ( 1 / arr [ i ] ) ) ; } if ( checkIsAP ( rec , n ) ) return true ; else return false ; } int main ( ) { double arr [ ] = { 1.0 / 5.0 , 1.0 / 10.0 , 1.0 / 15.0 , 1.0 / 20.0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int flag = 0 ; if ( checkIsAP ( arr , n ) ) { cout << " Yes , β An β AP β can β be β formed " << endl ; flag = 1 ; } if ( checkIsGP ( arr , n ) ) { cout << " Yes , β A β GP β can β be β formed " << endl ; flag = 1 ; } if ( checkIsHP ( arr , n ) ) { cout << " Yes , β A β HP β can β be β formed " << endl ; flag = 1 ; } else if ( flag == 0 ) { cout << " No " ; } return 0 ; } |
Sort the Array by reversing the numbers in it | C ++ implementation of the approach ; Function to return the reverse of n ; Function to sort the array according to the reverse of elements ; Vector to store the reverse with respective elements ; Inserting reverse with elements in the vector pair ; Sort the vector , this will sort the pair according to the reverse of elements ; Print the sorted vector content ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int reversDigits ( int num ) { int rev_num = 0 ; while ( num > 0 ) { rev_num = rev_num * 10 + num % 10 ; num = num / 10 ; } return rev_num ; } void sortArr ( int arr [ ] , int n ) { vector < pair < int , int > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( reversDigits ( arr [ i ] ) , arr [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second << " β " ; } int main ( ) { int arr [ ] = { 12 , 10 , 102 , 31 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; } |
Count number of pairs with positive sum in an array | C ++ program to count the pairs with positive sum ; Returns number of pairs in arr [ 0. . n - 1 ] with positive sum ; Sort the array in increasing order ; Intialise result ; Intialise first and second pointer ; Till the pointers doesn 't converge traverse array to count the pairs ; If sum of arr [ i ] && arr [ j ] > 0 , then the count of pairs with positive sum is the difference between the two pointers ; Increase the count ; Driver 's Code ; Function call to count the pairs with positive sum | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CountPairs ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int count = 0 ; int l = 0 , r = n - 1 ; while ( l < r ) { if ( arr [ l ] + arr [ r ] > 0 ) { count += ( r - l ) ; r -- ; } else { l ++ ; } } return count ; } int main ( ) { int arr [ ] = { -7 , -1 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CountPairs ( arr , n ) ; return 0 ; } |
Sort the given Matrix | Memory Efficient Approach | C ++ implementation to sort the given matrix in strict order ; Function to sort the matrix ; Number of elements in matrix ; Loop to sort the matrix using Bubble Sort ; Condition to check if the Adjacent elements ; Swap if previous value is greater ; Loop to print the matrix ; Driver Code ; Function call to sort ; Function call to print matrix | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 3 NEW_LINE #define M 3 NEW_LINE void sortMat ( int data [ N ] [ M ] , int row , int col ) { int size = row * col ; for ( int i = 0 ; i < size ; i ++ ) { for ( int j = 0 ; j < size - 1 ; j ++ ) { if ( data [ j / col ] [ j % col ] > data [ ( j + 1 ) / col ] [ ( j + 1 ) % col ] ) { int temp = data [ j / col ] [ j % col ] ; data [ j / col ] [ j % col ] = data [ ( j + 1 ) / col ] [ ( j + 1 ) % col ] ; data [ ( j + 1 ) / col ] [ ( j + 1 ) % col ] = temp ; } } } } void printMat ( int mat [ N ] [ M ] , int row , int col ) { for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { cout << mat [ i ] [ j ] << " β " ; } cout << endl ; } } int main ( ) { int mat [ N ] [ M ] = { { 5 , 4 , 7 } , { 1 , 3 , 8 } , { 2 , 9 , 6 } } ; int row = N ; int col = M ; sortMat ( mat , row , col ) ; printMat ( mat , row , col ) ; return 0 ; } |
Partition the array into two odd length groups with minimized absolute difference between their median | C ++ program to minimise the median between partition array ; Function to find minimise the median between partition array ; Sort the given array arr [ ] ; Return the difference of two middle element of the arr [ ] ; Driver Code ; Size of arr [ ] ; Function that returns the minimum the absolute difference between median of partition array | #include " bits / stdc + + . h " NEW_LINE using namespace std ; int minimiseMedian ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; return abs ( arr [ n / 2 ] - arr [ ( n / 2 ) - 1 ] ) ; } int main ( ) { int arr [ ] = { 15 , 25 , 35 , 50 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimiseMedian ( arr , n ) ; return 0 ; } |
Maximum number of overlapping Intervals | C ++ program that print maximum number of overlap among given ranges ; Function that print maximum overlap among ranges ; variable to store the maximum count ; storing the x and y coordinates in data vector ; pushing the x coordinate ; pushing the y coordinate ; sorting of ranges ; Traverse the data vector to count number of overlaps ; if x occur it means a new range is added so we increase count ; if y occur it means a range is ended so we decrease count ; updating the value of ans after every traversal ; printing the maximum value ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void overlap ( vector < pair < int , int > > v ) { int ans = 0 ; int count = 0 ; vector < pair < int , char > > data ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { data . push_back ( { v [ i ] . first , ' x ' } ) ; data . push_back ( { v [ i ] . second , ' y ' } ) ; } sort ( data . begin ( ) , data . end ( ) ) ; for ( int i = 0 ; i < data . size ( ) ; i ++ ) { if ( data [ i ] . second == ' x ' ) count ++ ; if ( data [ i ] . second == ' y ' ) count -- ; ans = max ( ans , count ) ; } cout << ans << endl ; } int main ( ) { vector < pair < int , int > > v = { { 1 , 2 } , { 2 , 4 } , { 3 , 6 } } ; overlap ( v ) ; return 0 ; } |
Making three numbers equal with the given operations | C ++ implementation of the approach ; Function that returns true if a , b and c can be made equal with the given operations ; Sort the three numbers ; Find the sum of difference of the 3 rd and 2 nd element and the 3 rd and 1 st element ; Subtract the difference from k ; Check the required condition ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canBeEqual ( int a , int b , int c , int k ) { int arr [ 3 ] ; arr [ 0 ] = a ; arr [ 1 ] = b ; arr [ 2 ] = c ; sort ( arr , arr + 3 ) ; int diff = 2 * arr [ 2 ] - arr [ 1 ] - arr [ 0 ] ; k = k - diff ; if ( k < 0 k % 3 != 0 ) return false ; return true ; } int main ( ) { int a1 = 6 , b1 = 3 , c1 = 2 , k1 = 7 ; if ( canBeEqual ( a1 , b1 , c1 , k1 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Arrange numbers to form a valid sequence | C ++ implementation of the above approach ; Function to organize the given numbers to form a valid sequence . ; Sorting the array ; Two pointer technique to organize the numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > orgazineInOrder ( vector < int > vec , vector < int > op , int n ) { vector < int > result ( n ) ; sort ( vec . begin ( ) , vec . end ( ) ) ; int i = 0 , j = n - 1 , k = 0 ; while ( i <= j && k <= n - 2 ) { if ( op [ k ] == ' < ' ) { result [ k ] = vec [ i ++ ] ; } else { result [ k ] = vec [ j -- ] ; } k ++ ; } result [ n - 1 ] = vec [ i ] ; return result ; } int main ( ) { vector < int > vec ( { 8 , 2 , 7 , 1 , 5 , 9 } ) ; vector < int > op ( { ' > ' , ' > ' , ' < ' , ' > ' , ' < ' } ) ; vector < int > result = orgazineInOrder ( vec , op , vec . size ( ) ) ; for ( int i = 0 ; i < result . size ( ) ; i ++ ) { cout << result [ i ] << " β " ; } return 0 ; } |
Find the distance between two person after reconstruction of queue | C ++ implementation of the approach ; Function to find the correct order and then return the distance between the two persons ; Make pair of both height & infront and insert to vector ; Sort the vector in ascending order ; Find the correct place for every person ; Insert into position vector according to infront value ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getDistance ( int arr [ ] [ 2 ] , int n , int a , int b ) { vector < pair < int , int > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( { arr [ i ] [ 0 ] , arr [ i ] [ 1 ] } ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; vector < int > pos ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) { int height = vp [ i ] . first ; int k = vp [ i ] . second ; pos . insert ( pos . begin ( ) + k , height ) ; } int first = -1 , second = -1 ; for ( int i = 0 ; i < pos . size ( ) ; i ++ ) { if ( pos [ i ] == a ) first = i ; if ( pos [ i ] == b ) second = i ; } return abs ( first - second ) ; } int main ( ) { int arr [ ] [ 2 ] = { { 5 , 0 } , { 3 , 0 } , { 2 , 0 } , { 6 , 4 } , { 1 , 0 } , { 4 , 3 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int a = 6 , b = 5 ; cout << getDistance ( arr , n , a , b ) ; return 0 ; } |
Minimize the sum of differences of consecutive elements after removing exactly K elements | C ++ implementation of the above approach . ; function to find minimum sum ; variable to store final answer and initialising it with the values when 0 elements is removed from the left and K from the right . ; loop to simulate removal of elements ; removing i elements from the left and and K - i elements from the right and updating the answer correspondingly ; returning final answer ; driver function ; input values ; callin the required function ; | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int * arr , int n , int k ) { int ans = arr [ n - k - 1 ] - arr [ 0 ] ; for ( int i = 1 ; i <= k ; i ++ ) { ans = min ( arr [ n - 1 - ( k - i ) ] - arr [ i ] , ans ) ; } return ans ; } int32_t main ( ) { int arr [ ] = { 1 , 2 , 100 , 120 , 140 } ; int k = 2 ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findSum ( arr , n , k ) ; } |
Minimum elements to be removed from the ends to make the array sorted | C ++ implementation of the approach ; Function to return the minimum number of elements to be removed from the ends of the array to make it sorted ; To store the final answer ; Two pointer loop ; While the array is increasing increment j ; Updating the ans ; Updating the left pointer ; Returning the final answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMin ( int * arr , int n ) { int ans = 1 ; for ( int i = 0 ; i < n ; i ++ ) { int j = i + 1 ; while ( j < n and arr [ j ] > = arr [ j - 1 ] ) j ++ ; ans = max ( ans , j - i ) ; i = j - 1 ; } return n - ans ; } int main ( ) { int arr [ ] = { 3 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findMin ( arr , n ) ; return 0 ; } |
Number of subsequences of maximum length K containing no repeated elements | C ++ implementation of the approach ; Returns number of subsequences of maximum length k and contains no repeated element ; Sort the array a [ ] ; Store the frequencies of all the distinct element in the vector arr ; count is the the number of such subsequences ; Create a 2 - d array dp [ n + 1 ] [ m + 1 ] to store the intermediate result ; Initialize the first row to 1 ; Update the dp [ ] [ ] array based on the recurrence relation ; Return the number of subsequences ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubSeq ( int a [ ] , int n , int k ) { sort ( a , a + n ) ; vector < int > arr ; for ( int i = 0 ; i < n ; ) { int count = 1 , x = a [ i ] ; i ++ ; while ( i < n && a [ i ] == x ) { count ++ ; i ++ ; } arr . push_back ( count ) ; } int m = arr . size ( ) ; n = min ( m , k ) ; int count = 1 ; int dp [ n + 1 ] [ m + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) dp [ 0 ] [ i ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = m ; j >= 0 ; j -- ) { if ( j > m - i ) dp [ i ] [ j ] = 0 ; else { dp [ i ] [ j ] = dp [ i ] [ j + 1 ] + arr [ j ] * dp [ i - 1 ] [ j + 1 ] ; } } count = count + dp [ i ] [ 0 ] ; } return count ; } int main ( ) { int a [ ] = { 2 , 2 , 3 , 3 , 5 } ; int n = sizeof ( a ) / sizeof ( int ) ; int k = 3 ; cout << countSubSeq ( a , n , k ) ; return 0 ; } |
Find the count of unvisited indices in an infinite array | C ++ implementation of the approach ; Function to return the count of unvisited indices starting from the index 0 ; Largest index that cannot be visited ; Push the index to the queue ; To store the required count ; Current index that cannot be visited ; Increment the count for the current index ; ( curr - m ) and ( curr - n ) are also unreachable if they are valid indices ; Return the required count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countUnvisited ( int n , int m ) { int X = ( m * n ) - m - n ; queue < int > queue ; queue . push ( X ) ; int count = 0 ; while ( queue . size ( ) > 0 ) { int curr = queue . front ( ) ; queue . pop ( ) ; count ++ ; if ( curr - m > 0 ) queue . push ( curr - m ) ; if ( curr - n > 0 ) queue . push ( curr - n ) ; } return count ; } int main ( ) { int n = 2 , m = 5 ; cout << countUnvisited ( n , m ) ; return 0 ; } |
Check whether the string S1 can be made equal to S2 with the given operation | CPP implementation of the approach ; Function to return the string formed by the odd indexed characters of s ; Function to return the string formed by the even indexed characters of s ; Function that returns true if s1 can be made equal to s2 with the given operation ; Get the string formed by the even indexed characters of s1 ; Get the string formed by the even indexed characters of s2 ; Get the string formed by the odd indexed characters of s1 ; Get the string formed by the odd indexed characters of s2 ; Sorting all the lists ; If the strings can be made equal ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string partOdd ( string s ) { string st = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( i % 2 != 0 ) st += s [ i ] ; } return st ; } string partEven ( string str ) { string s = " " ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( i % 2 == 0 ) s += str [ i ] ; } return s ; } bool canBeMadeEqual ( string s1 , string s2 ) { string even_s1 = partEven ( s1 ) ; string even_s2 = partEven ( s2 ) ; string odd_s1 = partOdd ( s1 ) ; string odd_s2 = partOdd ( s2 ) ; sort ( even_s1 . begin ( ) , even_s1 . end ( ) ) ; sort ( even_s2 . begin ( ) , even_s2 . end ( ) ) ; sort ( odd_s1 . begin ( ) , odd_s1 . end ( ) ) ; sort ( odd_s2 . begin ( ) , odd_s2 . end ( ) ) ; if ( even_s1 == even_s2 and odd_s1 == odd_s2 ) return true ; return false ; } int main ( ) { string s1 = " cdab " ; string s2 = " abcd " ; if ( canBeMadeEqual ( s1 , s2 ) ) cout << " Yes " << endl ; else cout << " No " << endl ; } |
Sort the given stack elements based on their modulo with K | C ++ implementation of the above approach ; Function to sort the stack using another stack based on the values of elements modulo k ; Pop out the first element ; While temporary stack is not empty ; The top of the stack modulo k is greater than ( temp & k ) or if they are equal then compare the values ; Pop from temporary stack and push it to the input stack ; Push temp in temporary of stack ; Push all the elements in the original stack to get the ascending order ; Print the sorted elements ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortStack ( stack < int > & input , int k ) { stack < int > tmpStack ; while ( ! input . empty ( ) ) { int tmp = input . top ( ) ; input . pop ( ) ; while ( ! tmpStack . empty ( ) ) { int tmpStackMod = tmpStack . top ( ) % k ; int tmpMod = tmp % k ; if ( ( tmpStackMod > tmpMod ) || ( tmpStackMod == tmpMod && tmpStack . top ( ) > tmp ) ) { input . push ( tmpStack . top ( ) ) ; tmpStack . pop ( ) ; } else break ; } tmpStack . push ( tmp ) ; } while ( ! tmpStack . empty ( ) ) { input . push ( tmpStack . top ( ) ) ; tmpStack . pop ( ) ; } while ( ! input . empty ( ) ) { cout << input . top ( ) << " β " ; input . pop ( ) ; } } int main ( ) { stack < int > input ; input . push ( 10 ) ; input . push ( 3 ) ; input . push ( 2 ) ; input . push ( 6 ) ; input . push ( 12 ) ; int k = 4 ; sortStack ( input , k ) ; return 0 ; } |
Longest sub | C ++ implementation of the approach ; Function to return the length of the largest subsequence with non - negative sum ; To store the current sum ; Sort the input array in non - increasing order ; Traverse through the array ; Add the current element to the sum ; Condition when c_sum falls below zero ; Complete array has a non - negative sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLen ( int * arr , int n ) { int c_sum = 0 ; sort ( arr , arr + n , greater < int > ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { c_sum += arr [ i ] ; if ( c_sum < 0 ) return i ; } return n ; } int main ( ) { int arr [ ] = { 3 , 5 , -6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << maxLen ( arr , n ) ; return 0 ; } |
Find Partition Line such that sum of values on left and right is equal | C ++ implementation of the approach ; Function that returns true if the required line exists ; To handle negative values from x [ ] ; Update arr [ ] such that arr [ i ] contains the sum of all v [ j ] such that x [ j ] = i for all valid values of j ; Update arr [ i ] such that arr [ i ] contains the sum of the subarray arr [ 0. . . i ] from the original array ; If all the points add to 0 then the line can be drawn anywhere ; If the line is drawn touching the leftmost possible points ; If the line is drawn just before the current point ; If the line is drawn touching the current point ; If the line is drawn just after the current point ; If the line is drawn touching the rightmost possible points ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000 ; bool lineExists ( int x [ ] , int y [ ] , int v [ ] , int n ) { int size = ( 2 * MAX ) + 1 ; long arr [ size ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { arr [ x [ i ] + MAX ] += v [ i ] ; } for ( int i = 1 ; i < size ; i ++ ) arr [ i ] += arr [ i - 1 ] ; if ( arr [ size - 1 ] == 0 ) return true ; if ( arr [ size - 1 ] - arr [ 0 ] == 0 ) return true ; for ( int i = 1 ; i < size - 1 ; i ++ ) { if ( arr [ i - 1 ] == arr [ size - 1 ] - arr [ i - 1 ] ) return true ; if ( arr [ i - 1 ] == arr [ size - 1 ] - arr [ i ] ) return true ; if ( arr [ i ] == arr [ size - 1 ] - arr [ i ] ) return true ; } if ( arr [ size - 2 ] == 0 ) return true ; return false ; } int main ( ) { int x [ ] = { -3 , 5 , 8 } ; int y [ ] = { 8 , 7 , 9 } ; int v [ ] = { 8 , 2 , 10 } ; int n = sizeof ( x ) / sizeof ( int ) ; if ( lineExists ( x , y , v , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Maximum sum of minimums of pairs in an array | C ++ implementation of the approach ; Function to return the maximum required sum of the pairs ; Sort the array ; To store the sum ; Start making pairs of every two consecutive elements as n is even ; Minimum element of the current pair ; Return the maximum possible sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int a [ ] , int n ) { sort ( a , a + n ) ; int sum = 0 ; for ( int i = 0 ; i < n - 1 ; i += 2 ) { sum += a [ i ] ; } return sum ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 1 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSum ( arr , n ) ; return 0 ; } |
Sort elements by modulo with K | C ++ implementation of the approach ; Utility function to print the contents of an array ; Function to sort the array elements based on their modulo with K ; Create K empty vectors ; Update the vectors such that v [ i ] will contain all the elements that give remainder as i when divided by k ; Sorting all the vectors separately ; Replacing the elements in arr [ ] with the required modulo sorted elements ; Add all the elements of the current vector to the array ; Print the sorted array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } void sortWithRemainder ( int arr [ ] , int n , int k ) { vector < int > v [ k ] ; for ( int i = 0 ; i < n ; i ++ ) { v [ arr [ i ] % k ] . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < k ; i ++ ) sort ( v [ i ] . begin ( ) , v [ i ] . end ( ) ) ; int j = 0 ; for ( int i = 0 ; i < k ; i ++ ) { for ( vector < int > :: iterator it = v [ i ] . begin ( ) ; it != v [ i ] . end ( ) ; it ++ ) { arr [ j ] = * it ; j ++ ; } } printArr ( arr , n ) ; } int main ( ) { int arr [ ] = { 10 , 7 , 2 , 6 , 12 , 3 , 33 , 46 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 4 ; sortWithRemainder ( arr , n , k ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.