Open In App

Find minimum value of the expression by choosing K elements from given array

Last Updated : 15 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of integers arr of size N, the task is to find the minimum possible of the expression by choosing exactly K(? N) integers form given array arr. Let say if chosen elements are stored in array B (B1, B2, B3…..Bk) then value of expression: 
x = \sum_{i=1}^k\sum_{j=1}^k(B_i - B_j)^{2}

Examples: 

Input : arr[] = {2, 0, 9, 5}, k = 2 
Output :
Let say, chosen elements are {2, 0}, then x = 8, which is minimum possible

Input : arr[] = {4, 21, 5, 3, 8}, k = 3 
Output : 200 

Approach : 
The above expression can be simplified as:  

  • \sum_{i=1}^k\sum_{j=1}^k(B_i^2 + B_j^2 - 2*B_i*B_j)
  • \sum_{i=1}^k\sum_{j=1}^k{B_i^2} + \sum_{i=1}^k\sum_{j=1}^k{B_j^2} - 2\sum_{i=1}^k\sum_{j=1}^k{B_i*B_j}
  • k*\sum_{i=1}^k{B_i^2} + k*\sum_{i=1}^k{B_j^2} - 2\sum_{i=1}^k{B_i}*\sum_{j=1}^k{B_j}
  • 2*k*\sum_{i=1}^k{B_i^2} - 2\sum_{i=1}^k{B_i^2}
  • (2*k-2)*\sum_{i=1}^k{B_i^2}

So, all we need to do is select the k smallest elements from the array and solve the expression.

Below is the implementation of the above approach:  

C++

// CPP program to find the minimum possible of the expression
// by choosing exactly K(? N) integers form given array arr
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum possible of the expression
// by choosing exactly K(? N) integers form given array arr
int minimumValue(int arr[], int n, int k)
{
 
    // Sorting the array for least k element selection
    sort(arr, arr + n);
 
    int answer = 0;
 
    // Select first k elements from sorted array
    for (int i = 0; i < k; i++)
        answer += arr[i] * arr[i];
 
    // Return value of solved expression
    return answer * (2 * k - 2);
}
 
// Driver code
int main()
{
    int arr[] = { 4, 21, 5, 3, 8 }, k = 3;
     
    int n = sizeof(arr) / sizeof(arr[0]);
     
    // Function call
    cout << minimumValue(arr, n, k);
     
    return 0;
}

                    

Java

// JAVA program to find the minimum possible of the expression
// by choosing exactly K(? N) integers form given array arr 
import java.util.*;
 
class GFG{
 
// Function to find the minimum possible of the expression
// by choosing exactly K(? N) integers form given array arr
static int minimumValue(int arr[], int n, int k)
{
 
    // Sorting the array for least k element selection
    Arrays.sort(arr);
 
    int answer = 0;
 
    // Select first k elements from sorted array
    for (int i = 0; i < k; i++)
        answer += arr[i] * arr[i];
 
    // Return value of solved expression
    return answer * (2 * k - 2);
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 4, 21, 5, 3, 8 }, k = 3;
     
    int n = arr.length;
     
    // Function call
    System.out.print(minimumValue(arr, n, k));    
}
}
 
// This code is contributed by Rajput-Ji

                    

Python3

# Python 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
def minimumValue(arr, n, k):
 
    # Sorting the array for least k element selection
    arr.sort();
 
    answer = 0;
 
    # Select first k elements from sorted array
    for i in range(k):
        answer += arr[i] * arr[i];
 
    # Return value of solved expression
    return answer * (2 * k - 2);
 
# Driver code
if __name__ == '__main__':
    arr = [ 4, 21, 5, 3, 8 ];
    k = 3;
 
    n = len(arr);
 
    # Function call
    print(minimumValue(arr, n, k));
 
# This code is contributed by Rajput-Ji

                    

C#

// C# program to find the minimum possible of the expression
// by choosing exactly K(? N) integers form given array arr 
using System;
 
class GFG{
  
// Function to find the minimum possible of the expression
// by choosing exactly K(? N) integers form given array arr
static int minimumValue(int []arr, int n, int k)
{
  
    // Sorting the array for least k element selection
    Array.Sort(arr);
  
    int answer = 0;
  
    // Select first k elements from sorted array
    for (int i = 0; i < k; i++)
        answer += arr[i] * arr[i];
  
    // Return value of solved expression
    return answer * (2 * k - 2);
}
  
// Driver code
public static void Main(String[] args)
{
    int []arr = { 4, 21, 5, 3, 8 };
    int k = 3;
      
    int n = arr.Length;
      
    // Function call
    Console.Write(minimumValue(arr, n, k));    
}
}
 
// This code is contributed by 29AjayKumar

                    

Javascript

<script>
 
// JavaScript 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
function minimumValue(arr, n, k)
{
 
    // Sorting the array for least k element selection
    arr.sort((a, b) => a - b);
 
    let answer = 0;
 
    // Select first k elements from sorted array
    for (let i = 0; i < k; i++)
        answer += arr[i] * arr[i];
 
    // Return value of solved expression
    return answer * (2 * k - 2);
}
 
// Driver code
 
    let arr = [ 4, 21, 5, 3, 8 ], k = 3;
     
    let n = arr.length;
     
    // Function call
    document.write(minimumValue(arr, n, k));
      
 
// This code is contributed by Surbhi Tyagi.
 
</script>

                    

Output
200

Time Complexity: O(n * log n)

Auxiliary Space: O(1)

Another Efficient Method: This problem can be solved efficiently using a Priority Queue. As we have to find the k smallest elements from the array in order to solve the expression so we use a priority queue which will find the k smallest elements in O(n*log(k)) time complexity where n is the size of the array and k is the number of smallest elements needed. Once we get the k smallest elements in the priority queue we will use the simplified expression given above to find the minimum value.

Below is the implementation of the above approach:  

C++

// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum possible of the expression
// by choosing exactly K(<= N) integers form given array arr
int minimumValue(int arr[], int n, int k)
{
     
    // Using a Priority Queue
    // to find k smallest elements
    priority_queue<int> heap1;
  
    for (int i = 0; i < n; ++i) {
  
        // Insert elements into
        // the priority queue
        heap1.push(arr[i]);
  
        // If size of the priority
        // queue exceeds k then remove
        // the largest element from
        // the priority queue
        if (heap1.size() > k) {
            heap1.pop();
        }
    }
 
    int answer = 0;
 
    // Using first k elements from priority queue
    // to find the minimum value
    for (int i = 0; i < k; i++)
    {
        answer += heap1.top() * heap1.top();
        heap1.pop();
    }
 
    // Return value of solved expression
    return answer * (2 * k - 2);
}
 
// Driver code
int main()
{
    int arr[] = { 4, 21, 5, 3, 8 }, k = 3;
     
    int n = sizeof(arr) / sizeof(arr[0]);
     
    // Function call
    cout << minimumValue(arr, n, k);
     
    return 0;
}
 
// This code is contributed by Pushpesh Raj

                    

Java

// Java code to implement the approach
import java.util.*;
 
class GFG {
 
  // Function to find the minimum possible of the
  // expression by choosing exactly K(<= N) integers form
  // given array arr
  static int minimumValue(int[] arr, int n, int k)
  {
 
    // Using a Priority Queue
    // to find k smallest elements
    PriorityQueue<Integer> heap1
      = new PriorityQueue<Integer>(
      Collections.reverseOrder());
 
    for (int i = 0; i < n; ++i) {
 
      // Insert elements into
      // the priority queue
      heap1.add(arr[i]);
 
      // If size of the priority
      // queue exceeds k then remove
      // the largest element from
      // the priority queue
      if (heap1.size() > k) {
        heap1.poll();
      }
    }
 
    int answer = 0;
 
    // Using first k elements from priority queue
    // to find the minimum value
    for (var i = 0; i < k; i++) {
      answer += heap1.peek() * heap1.peek();
      heap1.poll();
    }
 
    // Return value of solved expression
    return answer * (2 * k - 2);
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[] arr = { 4, 21, 5, 3, 8 };
    int k = 3;
 
    int n = arr.length;
 
    // Function call
    System.out.println(minimumValue(arr, n, k));
  }
}
 
// This code is contributed by phasing17

                    

Python3

#  Python3 code to implement the approach
 
#  Function to find the minimum possible of the expression
#  by choosing exactly K(<= N) integers form given array arr
def minimumValue(arr, n, k):
 
    #  Using a Priority Queue
    #  to find k smallest elements
    heap1 = [];
  
    for i in range(n):
  
        #  Insert elements into
        #  the priority queue
        heap1.append(arr[i]);
        heap1.sort(reverse = True)
  
        #  If size of the priority
        #  queue exceeds k then remove
        #  the largest element from
        #  the priority queue
        if (len(heap1) > k):
            heap1.pop(0);
         
    answer = 0;
 
    #  Using first k elements from priority queue
    #  to find the minimum value
    for i in range(k):
     
        answer += heap1[0] * heap1[0];
        heap1.pop(0);
     
 
    #  Return value of solved expression
    return answer * (2 * k - 2);
 
#  Driver code
arr = [4, 21, 5, 3, 8 ]
k = 3;
 
n = len(arr);
 
#  Function call
print(minimumValue(arr, n, k));
 
#  This code is contributed by phasing17

                    

C#

// C# code to implement the approach
using System;
using System.Collections.Generic;
 
class GFG
{
   
    // Function to find the minimum possible of the
    // expression by choosing exactly K(<= N) integers form
    // given array arr
    static int minimumValue(int[] arr, int n, int k)
    {
 
        // Using a Priority Queue
        // to find k smallest elements
        List<int> heap1 = new List<int>();
 
        for (int i = 0; i < n; ++i) {
 
            // Insert elements into
            // the priority queue
            heap1.Add(arr[i]);
            heap1.Sort();
            heap1.Reverse();
 
            // If size of the priority
            // queue exceeds k then remove
            // the largest element from
            // the priority queue
            if (heap1.Count > k) {
                heap1.RemoveAt(0);
            }
        }
 
        int answer = 0;
 
        // Using first k elements from priority queue
        // to find the minimum value
        for (var i = 0; i < k; i++) {
            answer += heap1[0] * heap1[0];
            heap1.RemoveAt(0);
        }
 
        // Return value of solved expression
        return answer * (2 * k - 2);
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int[] arr = { 4, 21, 5, 3, 8 };
        int k = 3;
 
        int n = arr.Length;
 
        // Function call
        Console.WriteLine(minimumValue(arr, n, k));
    }
}
 
// This code is contributed by phasing17

                    

Javascript

// JS code to implement the approach
 
// Function to find the minimum possible of the expression
// by choosing exactly K(<= N) integers form given array arr
function minimumValue(arr, n, k)
{
     
    // Using a Priority Queue
    // to find k smallest elements
    let heap1 = [];
  
    for (var i = 0; i < n; ++i) {
  
        // Insert elements into
        // the priority queue
        heap1.push(arr[i]);
        heap1.sort(function(a, b) { return a < b})
  
        // If size of the priority
        // queue exceeds k then remove
        // the largest element from
        // the priority queue
        if (heap1.length > k) {
            heap1.shift();
        }
    }
 
    let answer = 0;
 
    // Using first k elements from priority queue
    // to find the minimum value
    for (var i = 0; i < k; i++)
    {
        answer += heap1[0] * heap1[0];
        heap1.shift();
    }
 
    // Return value of solved expression
    return answer * (2 * k - 2);
}
 
// Driver code
let arr = [4, 21, 5, 3, 8 ]
let k = 3;
 
let n = arr.length;
 
// Function call
console.log(minimumValue(arr, n, k));
 
// This code is contributed by phasing17

                    

Output
200

Time Complexity: O(k+nlog(k)) where n is the size of the array and k is the given number of elements to choose from.
Auxiliary Space: O(k) since the priority queue at any time holds k elements.



Similar Reads

Maximize value of given expression by choosing pair from Array
Given an array A[] of length N, choose any two elements x and y from the array, the task is to find the maximum value of the expression (x * y + x - y). Examples: Input: A[] = {5, 2, 3} Output: 17Explanation: There are six possible pairs:For pairs {2, 3} and {3, 2}, answer = 2 ? 3 + max(2?3, 3?2) = 7For pairs {3, 5} and {5, 3} answer = 5 ? 3 + max(
5 min read
Find the minimum value of the given expression over all pairs of the array
Given an array A of size N, find the minimum value of the expression : [Tex](A_i \&amp; A_j) \oplus (A_i | A_j) [/Tex]over all pairs (i, j) (where i != j). Here [Tex]\&amp; [/Tex], [Tex]| [/Tex]and [Tex]\oplus [/Tex]represent bitwise AND, bitwise OR and bitwise XOR resprectively. Examples: Input: A = [1, 2, 3, 4, 5] Output: 1 Explanation: (A[1] and
8 min read
Maximize the product of sum and least power by choosing at most K elements from given value and power Arrays
Given two arrays arr[] and powr[] of size N and an integer K. Every element arr[i] has its respective power powr[i]. The task is to maximize the value of the given function by choosing at most K elements from the array. The function is defined as : f(N) = (arr[i1] + arr[i2] + arr[i3]+.....arr[in]) * min(powr[i1], powr[i2], powr[i3], .....powr[in])
10 min read
Minimum sum by choosing minimum of pairs from array
Given an array A[] of n-elements. We need to select two adjacent elements and delete the larger of them and store smaller of them to another array say B[]. We need to perform this operation till array A[] contains only single element. Finally, we have to construct the array B[] in such a way that total sum of its element is minimum. Print the total
4 min read
Minimize cost of choosing and skipping array elements to reach end of the given array
Given an integer X and an array cost[] consisting of N integers, the task is to find the minimum cost to reach the end of the given array starting from the first element based on the following constraints: Cost to visit point i is cost[i] where 1 ? i ? N.Cost to skip point i is min(cost[i], X) where 1 ? i ? N.At most 2 points can be skipped in a ro
14 min read
Check if end of given Binary string can be reached by choosing jump value in between given range
Given two positive integers L and R and a binary string S of size N, the task is to check if the end of the string is reached from the index 0 by a series of jumps of indices, say i such that S[i] is 0 jumps are allowed in the range [L, R]. If it is possible to reach, then print Yes. Otherwise, print No. Examples: Input: S = "011010", L = 2, R = 3O
7 min read
Minimum operations to choose Array elements with sum as K by choosing element from front, or rear or both
Given an array arr[] of positive integers of size N, and an integer K. The task is to minimize the number of operations required choose array elements that sum up to K. In one operation, an element can be removed either from the front, or from the rear, or from both front and rear, and added to the sum. If the desired sum can't be achieved, return
14 min read
Minimum cost of choosing 3 increasing elements in an array of size N
Given two arrays arr[] and cost[] where cost[i] is the cost associated with arr[i], the task is to find the minimum cost of choosing three elements from the array such that arr[i] &lt; arr[j] &lt; arr[k]. Examples: Input: arr[] = {2, 4, 5, 4, 10}, cost[] = {40, 30, 20, 10, 40} Output: 90 (2, 4, 5), (2, 4, 10) and (4, 5, 10) are the only valid tripl
12 min read
Find minimum value expression by inserting addition or multiplication operator between digits of given number
Given string str that contains only digits, the task is to return an expression by inserting the '+' or '*' operator between every two digits such that the arithmetic value of the expression is minimized. Example: Input: str = "322"Output: "3+2*2"Explanation: The value of above expression is 7 which is minimum possible over the other expressions "3
6 min read
Maximum modified Array sum possible by choosing elements as per the given conditions
Given an array arr[] of size N, the task is to find the maximum possible sum of the array elements such that the element can be chosen as per the below conditions: For each index i the value of the element is arr[i], then we can add any element from 1 to min(N, arr[i]) into the sum or else leave that element.If some element is already added to the
7 min read