[LeetCode] 1090. Largest Values From Labels
使用 Java 爬取 LeetCode 题目内容以及提交的AC代码
Description
We have a set of items: the i
-th item has value values[i]
and label labels[i]
.
Then, we choose a subset S
of these items, such that:
|S| <= num_wanted
- For every label
L
, the number of items inS
with labelL
is<= use_limit
.
Return the largest possible sum of the subset S
.
Example 1:
Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1
Output: 9
Explanation: The subset chosen is the first, third, and fifth item.
Example 2:
Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2
Output: 12
Explanation: The subset chosen is the first, second, and third item.
Example 3:
Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1
Output: 16
Explanation: The subset chosen is the first and fourth item.
Example 4:
Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2
Output: 24
Explanation: The subset chosen is the first, second, and fourth item.
Note:
1 <= values.length == labels.length <= 20000
0 <= values[i], labels[i] <= 20000
1 <= num_wanted, use_limit <= values.length
思路
题意:选取一个子集,子集中元素的总个数不大于 num_wanted,对于 label 值相同的元素,选取的个数不能大于 use_limit(如use_limit = 2,label值为 1 的元素有4个,最多选两个),这样的子集要求其 value 总和最大
题解:贪心,按照元素的value值排序,数值大的先选
static const auto io_sync_off = []() { // turn off sync std::ios::sync_with_stdio(false); // untie in/out streams std::cin.tie(nullptr); return nullptr; }(); struct Node { int value, label; bool operator < (const Node &node)const{ return value > node.value; } }; class Solution { public: int largestValsFromLabels(vector<int> &values, vector<int> &labels, int num_wanted, int use_limit) { int size = values.size(); Node node[size + 5]; int sum = 0; map<int, int>mp; map<int, int>::iterator it; for (int i = 0; i < size; i++) { node[i].value = values[i]; node[i].label = labels[i]; } sort(node, node + size); for (int i = 0; i < size && num_wanted; i++) { if (mp.find(node[i].label) != mp.end()) { if (mp[node[i].label] < use_limit) { sum += node[i].value; mp[node[i].label]++; num_wanted--; } } else { mp[node[i].label] = 1; sum += node[i].value; num_wanted--; } } return sum; } };
┆ 凉 ┆ 暖 ┆ 降 ┆ 等 ┆ 幸 ┆ 我 ┆ 我 ┆ 里 ┆ 将 ┆ ┆ 可 ┆ 有 ┆ 谦 ┆ 戮 ┆ 那 ┆ ┆ 大 ┆ ┆ 始 ┆ 然 ┆
┆ 薄 ┆ 一 ┆ 临 ┆ 你 ┆ 的 ┆ 还 ┆ 没 ┆ ┆ 来 ┆ ┆ 是 ┆ 来 ┆ 逊 ┆ 没 ┆ 些 ┆ ┆ 雁 ┆ ┆ 终 ┆ 而 ┆
┆ ┆ 暖 ┆ ┆ 如 ┆ 地 ┆ 站 ┆ 有 ┆ ┆ 也 ┆ ┆ 我 ┆ ┆ 的 ┆ 有 ┆ 精 ┆ ┆ 也 ┆ ┆ 没 ┆ 你 ┆
┆ ┆ 这 ┆ ┆ 试 ┆ 方 ┆ 在 ┆ 逃 ┆ ┆ 会 ┆ ┆ 在 ┆ ┆ 清 ┆ 来 ┆ 准 ┆ ┆ 没 ┆ ┆ 有 ┆ 没 ┆
┆ ┆ 生 ┆ ┆ 探 ┆ ┆ 最 ┆ 避 ┆ ┆ 在 ┆ ┆ 这 ┆ ┆ 晨 ┆ ┆ 的 ┆ ┆ 有 ┆ ┆ 来 ┆ 有 ┆
┆ ┆ 之 ┆ ┆ 般 ┆ ┆ 不 ┆ ┆ ┆ 这 ┆ ┆ 里 ┆ ┆ 没 ┆ ┆ 杀 ┆ ┆ 来 ┆ ┆ ┆ 来 ┆