Leetcode 2600. K Items With the Maximum Sum
You are given three integers numOnes, numZeros, and numNegOnes. You are tasked with constructing an array that consists of exactly:
numOnes instances of 1numZeros instances of 0numNegOnes instances of -1You also have an integer k. The array constructed should be of length numOnes + numZeros + numNegOnes.
Your task is to find the maximum possible sum of any subarray of length k.
k be larger than the total length of the array?
k will be less than or equal to the sum of numOnes, numZeros, and numNegOnes.k be zero?
k will be at least 1 according to the problem constraints.numOnes, numZeros, and numNegOnes guaranteed to be non-negative?
To maximize the sum of a subarray of length k, we need to include as many 1s as possible since 1 is the highest value in the given elements. Our strategy would be:
1s as possible up to k.k is larger than numOnes, then use zero 0s until enough if there are remaining positions.1s and 0s, use -1s to fill the rest.This strategy ensures that the maximum sum is achieved.
The solution involves simple arithmetic operations based on the values of k, numOnes, numZeros, and numNegOnes, making the time complexity O(1).
class Solution {
public:
int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) {
// Use as many 1's as possible
if (k <= numOnes) {
return k; // since all k elements will be 1's
}
// Use all 1's and then check next
k -= numOnes;
int sum = numOnes; // all used 1's contribute to the sum
// Use 0's, they do not affect the sum
if (k <= numZeros) {
return sum; // remaining elements are 0's
}
// Use all 0's and then check next
k -= numZeros;
// Use -1's, each -1 decreases the sum
sum -= k; // remaining elements are all -1's
return sum;
}
};
This code will correctly produce the maximum sum of a subarray of length k by following the steps outlined in the strategy above.
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?