text: Find K such that changing all elements of the Array greater than K to K will make array sum N | 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: function findK ( arr , size , N ) { arr . sort ( function ( a , b ) { return a - b } ) ; let temp_sum = 0 ; for ( let i = 0 ; i < size ; i ++ ) { temp_sum += arr [ i ] ; if ( N - temp_sum == arr [ i ] * ( size - i - 1 ) ) { return arr [ i ] ; } } return - 1 ; } let arr = [ 3 , 1 , 10 , 4 , 8 ] ; let size = arr . length ; let N = 16 ; document . write ( findK ( arr , size , N ) ) ;