Maximum Sum With Exactly K Elements
Given an array nums
, we have to repeat an operation k
times where we:
 Select the largest element
m
fromnums
.  Remove the selected element
m
.  Add a new element with value
m + 1
.  Increase our score by
m
.
After repeating this operation k
times, we need to return the maximum score. To maximize the score, we should always select the largest element from the array in each step.
Steps
 Initialize Score: Initialize the score as 0.
 Repeat Operation k Times: Repeat the following steps
k
times: a. Find the maximum elementm
in the array. b. Addm
to the score. c. Removem
from the array and addm + 1
to the array.  Return the Score: Return the final score.
Code


Example
For nums = [1,2,3,4,5]
, k = 3
, the steps would be:
 Iteration 1: Choose
5
, Score is5
, nums =[1,2,3,4,6]
 Iteration 2: Choose
6
, Score is11
, nums =[1,2,3,4,7]
 Iteration 3: Choose
7
, Score is18
, nums =[1,2,3,4,8]
So the result is 18
.
Complexity
The solution’s time complexity is O(k * n)
, where n
is the length of the array, and space complexity is O(1)
as we are not using any additional space other than input. It respects the given constraints, so it will work for the provided input limits.