Leetcode 2600. K Items With the Maximum Sum
You are given three integers numOnes
, numZeros
, and numNegOnes
. You are given an array consisting of numOnes
ones, numZeros
zeros, and numNegOnes
negative ones.
You need to pick exactly k
items from this array such that their sum is maximized.
Return the maximized sum.
numOnes
, numZeros
, numNegOnes
, and k
?
numOnes
, numZeros
, numNegOnes
, and k
are non-negative integers (i.e., 0 ≤ numOnes
, numZeros
, numNegOnes
≤ 50 and 0 ≤ k
≤ numOnes
+ numZeros
+ numNegOnes
).k
be zero?
k
is zero, the sum should be zero.The goal is to maximize the sum by leveraging the positive values first.
public class Solution {
public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) {
int sum = 0;
// 1. Pick ones
if (k > 0 && numOnes > 0) {
int pickOnes = Math.min(k, numOnes);
sum += pickOnes;
k -= pickOnes;
}
// 2. Pick zeros (automatically included, no change in sum)
if (k > 0 && numZeros > 0) {
int pickZeros = Math.min(k, numZeros);
// sum does not change with zeros
k -= pickZeros;
}
// 3. Pick negative ones
if (k > 0 && numNegOnes > 0) {
int pickNegOnes = Math.min(k, numNegOnes);
sum -= pickNegOnes;
k -= pickNegOnes;
}
return sum;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.kItemsWithMaximumSum(3, 2, 0, 2)); // Output: 2
System.out.println(sol.kItemsWithMaximumSum(3, 2, 0, 4)); // Output: 3
System.out.println(sol.kItemsWithMaximumSum(3, 2, 5, 8)); // Output: 0
}
}
The time complexity of this solution is O(1) because we are performing a constant number of operations regardless of the input sizes. There are no loops dependent on the size of the inputs.
This guarantees an extremely efficient solution suitable for constraint limits given in the problem statement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?