📌  相关文章
📜  在给定条件下查找具有最大总和的子集

📅  最后修改于: 2021-05-17 23:05:57             🧑  作者: Mango

给定n个项目的values []labels []以及正整数限制,我们需要选择这些项目的子集,使得子集中同类型标签的数量应为<=限制和值在所有可能的子集选择中最大。

例子:

Input: values[] = [5, 3, 7, 1, 2],
       labels[] = [5, 7, 7, 7, 6],
       limit = 2
Output: 17
Explanation:
You can select first, second, third 
and Fifth values.
So, there is 1 value of the label 5 -> {5},
    2 value of the label 7 -> {3, 7} ,
    1 value of the label 6 -> {2}.
Final subset = {5, 3, 7, 2}
Sum  = 5 + 3 + 7 + 2 = 17.

Input: values[] = [9, 8, 7, 6, 5],
       labels[] = [5, 7, 7, 7, 6],
       limit = 2
Output: 29

方法:想法是使用Multimap和Hashmap解决此问题。

  • 我们将所有值和相应的标签成对存储在Multimap中。
  • 在Multimap中,{values,labels}对按升序排序。因此,我们将反向遍历Multimap以获得降序对。
  • 现在,我们将在答案中添加值,并将每个标签的出现次数存储在Hashmap中,以检查出现次数是否小于或等于限制。

下面是上述方法的实现:

C++
// C++ program to Find subset with
// maximum sum under given condition.
#include 
using namespace std;
 
// Function to return the maximum
// sum of the subset
int MaxSumSubset(vector& values,
                 vector& labels,
                 int n, int limit)
{
    int res = 0;
    multimap s;
    unordered_map map;
 
    if (n == 0)
    {
        return 0;
    }
 
    // Pushing the pair into
    // the multimap
    for (int i = 0; i < n; i++)
    {
        s.insert({ values[i],
                  labels[i] });
    }
 
    // Traversing the multimap
    // in reverse
    for (auto it = s.rbegin();
         it != s.rend() && n > 0; it++)
    {
            cout<<(it->first)<<" "<second<second] <= limit)
        {
            res += it->first;
          //cout<<"res = "< values = { 5, 3, 7, 1, 2 };
    vector labels = { 5, 7, 7, 7, 6 };
     
    int n = sizeof(values) / sizeof(values[0]);
    int limit = 2;
     
    cout << MaxSumSubset(values, labels,
                         n, limit);
    return 0;
}


Python3
# Python3 program to Find subset with
# maximum sum under given condition.
from collections import defaultdict
 
# Function to return the maximum
# sum of the subset
def MaxSumSubset(values, labels,
                 n, limit):
                      
    res = 0
    s = {}
    map = defaultdict(int)
 
    if (n == 0):
        return 0
 
    # Pushing the pair into
    # the multimap
    for i in range(n):
        s[values[i]] = labels[i]
 
    # Traversing the multimap
    # in reverse
    #s = reversed(sorted(s.keys()))
    for it in sorted(s.keys(), reverse = True):
        if n > 0:
            if (map[s[it]] < limit):
                res += it
                #print("res = ",res)
 
                map[s[it]] += 1
 
        n -= 1
 
    return res
 
# Driver code
if __name__ == "__main__":
 
    values = [5, 3, 7, 1, 2]
    labels = [5, 7, 7, 7, 6]
 
    n = len(values)
    limit = 2
 
    print(MaxSumSubset(values, labels,
                       n, limit))
 
# This code is contributed by ukasp


输出:
17

时间复杂度: O(N),其中N是数组的长度。