Find K such that changing all elements of the Array greater than K to K will make array sum N | Java 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
import java . util . * ; class GFG { static int findK ( int arr [ ] , int size , int N ) { Arrays . sort ( arr ) ; 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 ; } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 1 , 10 , 4 , 8 } ; int size = arr . length ; int N = 16 ; System . out . print ( findK ( arr , size , N ) ) ; } }