[LeetCode] Maximum Sum With Exactly K Elements

2656. Maximum Sum With Exactly K Elements

You are given a 0-indexed integer array nums and an integer k. Your task is to perform the following operation exactly k times in order to maximize your score:

  1. Select an element m from nums.
  2. Remove the selected element m from the array.
  3. Add a new element with a value of m + 1 to the array.
  4. Increase your score by m.

Return the maximum score you can achieve after performing the operation exactly k times.

1
2
3
4
5
6
7
8
class Solution {
public:
int maximizeSum(vector<int>& nums, int k) {
int ma = *max_element(begin(nums), end(nums));
return k * (ma + ma + k - 1) / 2;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/29/PS/LeetCode/maximum-sum-with-exactly-k-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.