Maximum Sum With Exactly K Elements - Problem

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:

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

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

Input & Output

Example 1 — Basic Case
$ Input: nums = [5,2,1], k = 3
Output: 18
💡 Note: Operation 1: Select 5 (max), score = 5, array becomes [6,2,1]. Operation 2: Select 6 (max), score = 11, array becomes [7,2,1]. Operation 3: Select 7 (max), score = 18. Total score = 5 + 6 + 7 = 18.
Example 2 — Single Element
$ Input: nums = [10], k = 2
Output: 21
💡 Note: Operation 1: Select 10, score = 10, array becomes [11]. Operation 2: Select 11, score = 21. Total score = 10 + 11 = 21.
Example 3 — Larger Array
$ Input: nums = [1,2,3,4,5], k = 4
Output: 26
💡 Note: Always select maximum: 5 + 6 + 7 + 8 = 26. The other elements don't matter since we keep incrementing the maximum.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100
  • 1 ≤ k ≤ 100

Visualization

Tap to expand
Maximum Sum With Exactly K Elements INPUT nums array: 5 index 0 2 index 1 1 index 2 k = 3 Input Values: nums = [5, 2, 1] k = 3 operations Max element: 5 Goal: Maximize score ALGORITHM STEPS 1 Find Maximum max(nums) = 5 2 Operation 1 Pick 5, score += 5 3 Operation 2 Pick 6, score += 6 4 Operation 3 Pick 7, score += 7 Running Calculation: Op 1: 5 --> add 6, score = 5 Op 2: 6 --> add 7, score = 11 Op 3: 7 --> add 8, score = 18 Total: 5 + 6 + 7 = 18 FINAL RESULT Maximum Score 18 Selected Elements: 5 + 6 + 7 Output Verification: Output: 18 Sum of arithmetic sequence starting from max element OK Key Insight: Greedy approach: Always pick the maximum element. After picking m, it becomes m+1, so keep picking it! The answer is an arithmetic series: max + (max+1) + (max+2) + ... for k terms. Formula: k * max + k*(k-1)/2 = 3*5 + 3*2/2 = 15 + 3 = 18 TutorialsPoint - Maximum Sum With Exactly K Elements | Greedy Optimization
Asked in
Google 25 Amazon 18
23.1K Views
Medium Frequency
~10 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen