Find minimum value of the expression by choosing K elements from given array | Function to find the minimum possible of the expression by choosing exactly K ( ? N ) integers form given array arr ; Sorting the array for least k element selection ; Select first k elements from sorted array ; Return value of solved expression ; Driver code ; Function call
function minimumValue ( arr , n , k ) { arr . sort ( ( a , b ) => a - b ) ; let answer = 0 ; for ( let i = 0 ; i < k ; i ++ ) answer += arr [ i ] * arr [ i ] ; return answer * ( 2 * k - 2 ) ; } let arr = [ 4 , 21 , 5 , 3 , 8 ] , k = 3 ; let n = arr . length ; document . write ( minimumValue ( arr , n , k ) ) ;