
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Largest Values from Labels in Python
Suppose we have a set of items: the i-th item has value values[i] and label labels[i]. Then, we will take a subset S of these items, such that −
- |S| <= num_wanted
- For every label L, the number of items present in S with label L is <= use_limit.
We have to find the largest possible sum of the subset S.
For example, if the input is like values = [5,4,3,2,1] and labels are [1,1,2,2,3], num_wanted = 3, use_limit = 1, then the output will be 9. This is because the subset chosen in the first, third and fifth item.
To solve this, we will follow these steps −
- make one array v
- for i in range 0 to length of values
- insert [values[i], labels[i]] into v
- sort the v array
- ans := 0, use := empty map, and i := 0
- while num_wanted and i < length of v
- if v[i, 1] is not present in use map
- decrease num_wanted by 1
- ans := ans + v[i, 0]
- use[v[i, 1]] := 1
- else use[v[i, 1]] < use_limit
- decrease num_wanted by 1
- ans := ans + v[i, 0]
- increase use[v[i, 1]] by 1
- increase i by 1
- if v[i, 1] is not present in use map
- return ans
Let us see the following implementation to get better understanding −
Example
class Solution(object): def largestValsFromLabels(self, values, labels, num_wanted, use_limit): v = [] for i in range(len(values)): v.append([values[i],labels[i]]) v = sorted(v,key = lambda v:v[0],reverse=True) ans = 0 use = {} i = 0 while num_wanted and i < len(v): if v[i][1] not in use: num_wanted -=1 ans+=v[i][0] use[v[i][1]] = 1 elif use[v[i][1]]<use_limit: num_wanted -=1 ans+=v[i][0] use[v[i][1]]+=1 i+=1 return ans ob = Solution() print(ob.largestValsFromLabels([5,4,3,2,1],[1,1,2,2,3],3,1))
Input
[5,4,3,2,1] [1,1,2,2,3] 3 1
Output
9
Advertisements