Find minimum value of the expression by choosing K elements from given array | CPP program to find the minimum possible of the expression by choosing exactly K ( ? N ) integers form given array arr ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumValue ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int answer = 0 ; for ( int i = 0 ; i < k ; i ++ ) answer += arr [ i ] * arr [ i ] ; return answer * ( 2 * k - 2 ) ; } int main ( ) { int arr [ ] = { 4 , 21 , 5 , 3 , 8 } , k = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumValue ( arr , n , k ) ; return 0 ; }