[LeetCode] 2600. K Items With the Maximum Sum

发布时间 2023-07-06 07:01:08作者: CNoodle

There is a bag that consists of items, each item has a number 10, or -1 written on it.

You are given four non-negative integers numOnesnumZerosnumNegOnes, and k.

The bag initially contains:

  • numOnes items with 1s written on them.
  • numZeroes items with 0s written on them.
  • numNegOnes items with -1s written on them.

We want to pick exactly k items among the available items. Return the maximum possible sum of numbers written on the items.

Example 1:

Input: numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2
Output: 2
Explanation: We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2.
It can be proven that 2 is the maximum possible sum.

Example 2:

Input: numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4
Output: 3
Explanation: We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3.
It can be proven that 3 is the maximum possible sum.

Constraints:

  • 0 <= numOnes, numZeros, numNegOnes <= 50
  • 0 <= k <= numOnes + numZeros + numNegOnes

K 件物品的最大和。

袋子中装有一些物品,每个物品上都标记着数字 1 、0 或 -1 。

给你四个非负整数 numOnes 、numZeros 、numNegOnes 和 k 。

袋子最初包含:

numOnes 件标记为 1 的物品。
numZeroes 件标记为 0 的物品。
numNegOnes 件标记为 -1 的物品。
现计划从这些物品中恰好选出 k 件物品。返回所有可行方案中,物品上所标记数字之和的最大值。 

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/k-items-with-the-maximum-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是贪心。因为题目条件里保证 numOnes + numZeros + numNegOnes,所以我们可以贪心地先考虑 numOnes 的个数,再考虑 numZeros 的个数,最后再考虑 numNegOnes 的个数。

时间O(1)

空间O(1)

Java实现

 1 class Solution {
 2     public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) {
 3         int res = 0;
 4         while (k > 0) {
 5             if (numOnes > 0) {
 6                 res += Math.min(k, numOnes);
 7                 k -= Math.min(k, numOnes);
 8             }
 9             
10             if (numZeros > 0) {
11                 k -= Math.min(k, numZeros);
12             }
13             
14             if (numNegOnes > 0) {
15                 res -= Math.min(k, numNegOnes);
16                 k -= Math.min(k, numNegOnes);
17             }
18         }
19         return res;
20     }
21 }

 

LeetCode 题目总结