#2656
Easy Algorithms Maximum sum with exactly k elements
Array Greedy
80.5% acceptance
Feb 25, 2026
430
52
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn maximize_sum(nums: Vec<i32>, k: i32) -> i32 {
let m = *nums.iter().max().unwrap();
// Pick m, m+1, ..., m+k-1
// Sum = k*m + k*(k-1)/2
k * m + k * (k - 1) / 2
}
}