Leetcode 2656. Maximum Sum With Exactly K Elements
You are given a 0-indexed integer array nums
and an integer k
. Your task is to find the maximum sum you can achieve by selecting exactly k
elements from the array. If it is impossible to select k
elements, return 0
.
The sum should be calculated after adding 1
to each of the selected elements.
nums
contain negative numbers?
nums
can contain negative numbers.nums
be smaller than k
?
0
as it is impossible to select k
elements.nums
or the range of k
?
nums
is smaller than k
. If it is smaller, we return 0
since it’s not possible to select k
elements.k
elements.k
elements from the sorted array after incrementing each by 1.nums.length < k
. If true, return 0
.nums
in descending order.maxSum
to 0
.k
elements of the sorted array and add element + 1
to maxSum
.maxSum
.import java.util.Arrays;
import java.util.Collections;
public class MaximumSumWithKElements {
public int maxSum(int[] nums, int k) {
int n = nums.length;
if (n < k) {
return 0; // Impossible to select k elements
}
// Use boxed integers to allow sorting with Collections.reverseOrder()
Integer[] numsBoxed = Arrays.stream(nums).boxed().toArray(Integer[]::new);
Arrays.sort(numsBoxed, Collections.reverseOrder());
int maxSum = 0;
for (int i = 0; i < k; i++) {
maxSum += numsBoxed[i] + 1; // Add 1 to each selected element
}
return maxSum;
}
public static void main(String[] args) {
MaximumSumWithKElements solution = new MaximumSumWithKElements();
int[] nums = {1, 2, 3, 4, 5};
int k = 3;
System.out.println(solution.maxSum(nums, k)); // Output: 15 (5+1 + 4+1 + 3+1)
}
}
nums
is O(n log n)
, where n
is the length of the array.k
elements takes O(k)
.O(n log n)
, dominated by the sorting step.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?