text: Find K such that changing all elements of the Array greater than K to K will make array sum N | C ++ implementation of the approach ; Function to return K such that changing all elements greater than K to K will make array sum N otherwise return - 1 ; Sorting the array in increasing order ; Loop through all the elements of the array ; Checking if sum of array equals N ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int findK ( int arr [ ] , int size , int N ) { sort ( arr , arr + size ) ; int temp_sum = 0 ; for ( int i = 0 ; i < size ; i ++ ) { temp_sum += arr [ i ] ; if ( N - temp_sum == arr [ i ] * ( size - i - 1 ) ) { return arr [ i ] ; } } return -1 ; } int main ( ) { int arr [ ] = { 3 , 1 , 10 , 4 , 8 } ; int size = sizeof ( arr ) / sizeof ( int ) ; int N = 16 ; cout << findK ( arr , size , N ) ; return 0 ; }