📌  相关文章
📜  通过从给定值和幂数组中选择最多 K 个元素来最大化总和和最小幂的乘积

📅  最后修改于: 2022-05-13 01:56:09.908000             🧑  作者: Mango

通过从给定值和幂数组中选择最多 K 个元素来最大化总和和最小幂的乘积

给定两个大小为N的数组arr[]powr[]以及一个整数K 。每个元素arr[i]都有其各自的幂powr[i] 。任务是通过从数组中选择最多 K个元素来最大化给定函数的值。函数定义为:

例子:

方法:想法是将每个第i个元素视为最小幂,为此,将元素按幂的降序排序,因此第一个元素将被认为具有最高的幂。所有时间都试图维护一个大小最多为K的元素列表。这个列表将最多包含K个元素,其中最大的一个,不包括当前的第 i 个元素。如果已经有一个大小为K的列表,则删除长度最小的元素,因此 size 变为K - 1 ,然后将当前元素包含到列表中, size 变为K ,并更新res最大为 1 。最后,返回res就是答案。

  • 初始化大小为N的对v[]的向量以存储元素及其幂。
  • 使用变量i遍历范围[0, N)并执行以下任务:
    • 将值power[i]arr[i]分配为数组v[] 的第一个和第二个值。
  • 按升序对数组v[]进行排序。
  • 将变量ressum初始化为0以存储结果和总和。
  • 初始化一组对s[]
  • 使用变量i遍历范围[N-1, 0]并执行以下任务:
    • 将对{v[i].second, i}插入集合s[]。
    • v[i].second的值添加到变量sum。
    • 如果s.size()大于K ,则执行以下任务:
      • 将变量it初始化为集合s[] 的第一个元素。
      • 从变量sum 中减少it.first的值。
      • 从集合s[] 中删除变量it
    • res的值设置为ressum*v[i].first 的最大值。
  • 执行上述步骤后,打印res的值作为答案。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
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 > 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 > 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 v = new ArrayList();
 
    // 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() {
      @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 s = new HashSet();
 
    // 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


输出
54

时间复杂度: O(NlogN)
辅助空间: O(N)