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 possible sum of exactly k
elements from the array.
You can choose elements more than once and place them into a list, list1
, and the sum of the elements in list1
should be as large as possible.
Example 1:
Input: nums = [1,2,3,4], k = 2
Output: 8
Explanation:
If we add the largest element 4 twice (4 + 4), we get 8 which is the largest possible sum.
Example 2:
Input: nums = [1,2,3], k = 3
Output: 9
Explanation:
If we add the largest element 3 three times (3 + 3 + 3), we get 9 which is the largest possible sum.
list1
.k
and the size of the array?
k
be larger than the size of the array?
k
can be larger, and elements can be reused to match k
.k
elements, where elements can be reused.k
.k
to get the final sum.Here is the C++ code to solve this problem:
#include <iostream>
#include <vector>
#include <algorithm>
int maxSumWithKElements(std::vector<int>& nums, int k) {
// Find the maximum element in the array
int maxElement = *max_element(nums.begin(), nums.end());
// Calculate the maximum sum with exactly k elements
return maxElement * k;
}
int main() {
std::vector<int> nums1 = {1, 2, 3, 4};
int k1 = 2;
std::cout << maxSumWithKElements(nums1, k1) << std::endl; // Output: 8
std::vector<int> nums2 = {1, 2, 3};
int k2 = 3;
std::cout << maxSumWithKElements(nums2, k2) << std::endl; // Output: 9
return 0;
}
n
is the length of the array.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?