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

📅  最后修改于: 2021-10-27 09:15:19             🧑  作者: Mango

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

例子:

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


Javascript


输出:

17

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程。