Open In App

Maximize the product of sum and least power by choosing at most K elements from given value and power Arrays

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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]) where, arr[i1], arr[i2], arr[i3], …..arr[in] are the chosen elements.

Examples:

Input: arr[] = {11, 10, 7, 6, 9}, powr[] = {3, 2, 4, 1, 1}, K = 2, N = 5 
Output: 54
Explanation: Choose elements at indices {0, 2} so, f(N) = (11 + 7) * min(3, 4) = 18 * 3 = 54, which is the maximum possible value that can be achieved by choosing at most 2 elements.

Input: arr[] = {5, 12, 11, 9}, powr[] = {2, 1, 10, 1}, K = 3, N = 4 
Output: 110

 

Approach: The idea is to consider every ith element as the minimum power, for this, sort the elements in descending order of power, so the first element will be considered to have the highest power. All times try to maintain a list of elements of size at most K. This list will contain at most K elements with the largest one, not including the current ith element. If already have a list of size K, then remove the element with the smallest length so, size becomes K – 1, then include the current element into the list, size becomes K, and update res with maximum one. In the end, return res which is the answer.

  • Initialize a vector of pairs v[] of size N to store elements along with their power.
  • Iterate over the range [0, N) using the variable i and perform the following tasks:
    • Assign the values power[i] and arr[i] as the first and second values of the array v[].
  • Sort the array v[] in ascending order.
  • Initialize the variables res and sum as 0 to store the result and the sum.
  • Initialize a set of pairs s[].
  • Iterate over the range [N-1, 0] using the variable i and perform the following tasks:
    • Insert the pair {v[i].second, i} into the set s[].
    • Add the value of v[i].second to the variable sum.
    • If s.size() is greater than K then perform the following tasks:
      • Initialize the variable it as the first element of the set s[].
      • Reduce the value it.first from the variable sum.
      • Remove the variable it from the set s[].
    • Set the value of res as the maximum of res or sum*v[i].first.
  • After performing the above steps, print the value of res as the answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to maximize the value of the
// function by choosing at most K elements
// from the given array
int maximumValue(int arr[], int powr[],
                 int K, int N)
{
 
    // Vector to store the power of elements
    // along with the elements in pair
    vector<pair<int, int> > v(N);
 
    // In a pair, the first position contains
    // the power and the second position
    // contains the element
    for (int i = 0; i < N; i++) {
        v[i].first = powr[i];
        v[i].second = arr[i];
    }
 
    // Sort the vector according to the
    // power of the elements
    sort(v.begin(), v.end());
 
    // Variable to store the answer
    int res = 0;
 
    // Variable to store the sum of
    // elements
    int sum = 0;
 
    // Create a set of pairs
    set<pair<int, int> > s;
 
    // Traverse the vector in reverse order
    for (int i = N - 1; i >= 0; i--) {
 
        // Insert the element along with the
        // index in pair
        s.insert(make_pair(v[i].second, i));
        sum += v[i].second;
 
        // If size of set exceeds K, then
        // delete the first pair in the set
        // and update the sum by excluding
        // the elements value from it
        if (s.size() > K) {
            auto it = s.begin();
            sum -= it->first;
            s.erase(it);
        }
 
        // Store the maximum of all sum
        // multiplied by the element's
        // power
        res = max(res, sum * v[i].first);
    }
 
    // Return res
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 11, 10, 7, 6, 9 };
    int powr[] = { 3, 2, 4, 1, 1 };
    int K = 2;
 
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << maximumValue(arr, powr, K, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
 
class GFG {
 
  static class Pair {
    int first;
    int second;
 
    Pair(int first, int second) {
      this.first = first;
      this.second = second;
    }
  }
 
  // Function to maximize the value of the
  // function by choosing at most K elements
  // from the given array
  public static int maximumValue(int arr[], int powr[], int K, int N) {
 
    // Vector to store the power of elements
    // along with the elements in pair
    ArrayList<Pair> v = new ArrayList<Pair>();
 
    // In a pair, the first position contains
    // the power and the second position
    // contains the element
    for (int i = 0; i < N; i++) {
      v.add(new Pair(0, 0));
      v.get(i).first = powr[i];
      v.get(i).second = arr[i];
    }
 
    // Sort the vector according to the
    // power of the elements
    Collections.sort(v, new Comparator<Pair>() {
      @Override
      public int compare(final Pair lhs, Pair rhs) {
        return lhs.first > rhs.first ? 1 : -1;
      };
    });
 
    // Variable to store the answer
    int res = 0;
 
    // Variable to store the sum of
    // elements
    int sum = 0;
 
    // Create a set of pairs
    HashSet<Pair> s = new HashSet<Pair>();
 
    // Traverse the vector in reverse order
    for (int i = N - 1; i >= 0; i--) {
 
      // Insert the element along with the
      // index in pair
      s.add(new Pair(v.get(i).second, i));
      sum += v.get(i).second;
 
      // If size of set exceeds K, then
      // delete the first pair in the set
      // and update the sum by excluding
      // the elements value from it
      if (s.size() > K) {
        Pair it = s.iterator().next();
        sum -= it.first;
        s.remove(it);
      }
 
      // Store the maximum of all sum
      // multiplied by the element's
      // power
      res = Math.max(res, sum * v.get(i).first);
    }
 
    // Return res
    return res;
  }
 
  // Driver Code
  public static void main(String args[]) {
    int arr[] = { 11, 10, 7, 6, 9 };
    int powr[] = { 3, 2, 4, 1, 1 };
    int K = 2;
 
    int N = arr.length;
    System.out.println(maximumValue(arr, powr, K, N));
 
  }
}
 
// This code is contributed by gfgking.


Python3




# Python 3 program for the above approach
 
# Function to maximize the value of the
# function by choosing at most K elements
# from the given array
def maximumValue(arr, powr, K, N):
 
    # Vector to store the power of elements
    # along with the elements in pair
    v = [[0 for x in range(2)] for y in range(N)]
 
    # In a pair, the first position contains
    # the power and the second position
    # contains the element
    for i in range(N):
        v[i][0] = powr[i]
        v[i][1] = arr[i]
 
    # Sort the vector according to the
    # power of the elements
    v.sort()
 
    # Variable to store the answer
    res = 0
 
    # Variable to store the sum of
    # elements
    sum = 0
 
    # Create a set of pairs
    s = set([])
 
    # Traverse the vector in reverse order
    for i in range(N - 1, -1, -1):
 
        # Insert the element along with the
        # index in pair
        s.add((v[i][1], i))
        sum += v[i][1]
 
        # If size of set exceeds K, then
        # delete the first pair in the set
        # and update the sum by excluding
        # the elements value from it
        if (len(s) > K):
 
            sum -= list(s)[0][0]
            list(s).remove(list(s)[0])
 
        # Store the maximum of all sum
        # multiplied by the element's
        # power
        res = max(res, sum * v[i][0])
 
    # Return res
    return res
 
# Driver Code
if __name__ == "__main__":
 
    arr = [11, 10, 7, 6, 9]
    powr = [3, 2, 4, 1, 1]
    K = 2
 
    N = len(arr)
    print(maximumValue(arr, powr, K, N))
 
     # This code is contributed by ukasp.


Javascript




<script>
// Javascript program for the above approach
 
// Function to maximize the value of the
// function by choosing at most K elements
// from the given array
function maximumValue(arr, powr, K, N) {
 
  // Vector to store the power of elements
  // along with the elements in pair
  let v = new Array(N).fill(0).map(() => []);
 
  // In a pair, the first position contains
  // the power and the second position
  // contains the element
  for (let i = 0; i < N; i++) {
    v[i][0] = powr[i];
    v[i][1] = arr[i];
  }
 
  // Sort the vector according to the
  // power of the elements
  v.sort();
 
  // Variable to store the answer
  let res = 0;
 
  // Variable to store the sum of
  // elements
  let sum = 0;
 
  // Create a set of pairs
  let s = new Set();
 
  // Traverse the vector in reverse order
  for (let i = N - 1; i >= 0; i--) {
 
    // Insert the element along with the
    // index in pair
    s.add([v[i][1], i]);
    sum += v[i][1];
 
    // If size of set exceeds K, then
    // delete the first pair in the set
    // and update the sum by excluding
    // the elements value from it
    if (s.size > K) {
      let it = [...s][0];
      sum -= it[0];
      s.delete(it);
    }
 
    // Store the maximum of all sum
    // multiplied by the element's
    // power
    res = Math.max(res, sum * v[i][0]);
  }
 
  // Return res
  return res;
}
 
// Driver Code
 
let arr = [11, 10, 7, 6, 9];
let powr = [3, 2, 4, 1, 1];
let K = 2;
 
let N = arr.length;
document.write(maximumValue(arr, powr, K, N))
 
// This code is contributed by saurabh_jaiswal.
</script>


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
using System.Linq;
 
public class GFG
{
    class Pair
    {
        public int first;
        public int second;
 
        public Pair(int first, int second)
        {
            this.first = first;
            this.second = second;
        }
         
        public int Compare(Pair other)
        {
            return this.first > other.first ? 1 : -1;
        }
    }
 
    // Function to maximize the value of the
    // function by choosing at most K elements
    // from the given array
    public static int maximumValue(int[] arr, int[] powr, int K, int N)
    {
        // Vector to store the power of elements
        // along with the elements in pair
        List<Pair> v = new List<Pair>();
        // In a pair, the first position contains
        // the power and the second position
        // contains the element
        for (int i = 0; i < N; i++)
        {
            v.Add(new Pair(powr[i], arr[i]));
        }
        // Sort the vector according to the
        // power of the elements
        v.Sort((x, y) => x.Compare(y));
        // Variable to store the answer
        int res = 0;
        // Variable to store the sum of
        // elements
        int sum = 0;
        // Create a set of pairs
        HashSet<Pair> s = new HashSet<Pair>();
        // Traverse the vector in reverse order
        for (int i = N - 1; i >= 0; i--)
        {
            // Insert the element along with the
            // index in pair
            s.Add(new Pair(v[i].second, i));
            sum += v[i].second;
            // If size of set exceeds K, then
            // delete the first pair in the set
            // and update the sum by excluding
            // the elements value from it
            if (s.Count > K)
            {
                var it = s.First();
                sum -= it.first;
                s.Remove(it);
            }
            // Store the maximum of all sum
            // multiplied by the element's
            // power
            res = Math.Max(res,sum * v[i].first);
        }
        // Return res
        return res;
    }
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = {11, 10, 7, 6, 9};
        int[] powr = {3, 2, 4, 1, 1};
        var K = 2;
        var N = arr.Length;
        Console.WriteLine(maximumValue(arr, powr, K, N));
    }
}


Output

54

Time Complexity: O(NlogN)
Auxiliary Space: O(N)



Last Updated : 24 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads