You are given a 0-indexed integer array nums and an integer k. Your task is to perform the following operation exactlyk 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 exactlyktimes.
Input: nums =[1,2,3,4,5], k =3Output: 18Explanation: We need to choose exactly 3 elements from nums to maximize the sum.For the first iteration, we choose 5. Then sum is5 and nums =[1,2,3,4,6]For the second iteration, we choose 6. Then sum is5+6 and nums =[1,2,3,4,7]For the third iteration, we choose 7. Then sum is5+6+7=18 and nums =[1,2,3,4,8]So, we will return18.It can be proven, that 18is the maximum answer that we can achieve.
Input: nums =[5,5,5], k =2Output: 11Explanation: We need to choose exactly 2 elements from nums to maximize the sum.For the first iteration, we choose 5. Then sum is5 and nums =[5,5,6]For the second iteration, we choose 6. Then sum is5+6=11 and nums =[5,5,7]So, we will return11.It can be proven, that 11is the maximum answer that we can achieve.
To maximize the score, always pick the largest element from the array, increment it, and repeat for k times. This is a classic greedy approach using a max-heap to efficiently get the largest element each time.
classSolution {
public:int maximizeSum(vector<int>& nums, int k) {
priority_queue<int> pq(nums.begin(), nums.end());
int ans =0;
while (k--) {
int m = pq.top(); pq.pop();
ans += m;
pq.push(m +1);
}
return ans;
}
};
import java.util.*;
classSolution {
publicintmaximizeSum(int[] nums, int k) {
PriorityQueue<Integer> pq =new PriorityQueue<>(Collections.reverseOrder());
for (int x : nums) pq.offer(x);
int ans = 0;
for (int i = 0; i < k; ++i) {
int m = pq.poll();
ans += m;
pq.offer(m + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.PriorityQueue
classSolution {
funmaximizeSum(nums: IntArray, k: Int): Int {
val pq = PriorityQueue<Int>(compareByDescending { it })
nums.forEach { pq.add(it) }
var ans = 0 repeat(k) {
val m = pq.poll()
ans += m
pq.add(m + 1)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
import heapq
classSolution:
defmaximizeSum(self, nums: list[int], k: int) -> int:
pq = [-x for x in nums]
heapq.heapify(pq)
ans =0for _ in range(k):
m =-heapq.heappop(pq)
ans += m
heapq.heappush(pq, -(m +1))
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
use std::collections::BinaryHeap;
impl Solution {
pubfnmaximize_sum(nums: Vec<i32>, k: i32) -> i32 {
letmut heap = BinaryHeap::from(nums);
letmut ans =0;
for _ in0..k {
let m = heap.pop().unwrap();
ans += m;
heap.push(m +1);
}
ans
}
}