Skip to content

2656. Maximum Sum With Exactly K Elements 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
class Solution {
 public:
  int maximizeSum(vector<int>& nums, int k) {
    // If x = max(nums), ans = x + (x + 1) + .. + (x + k - 1).
    const int x = ranges::max(nums);
    return x * k + k * (k - 1) / 2;
  }
};
1
2
3
4
5
6
7
class Solution {
  public int maximizeSum(int[] nums, int k) {
    // If x = max(nums), ans = x + (x + 1) + .. + (x + k - 1).
    final int x = Arrays.stream(nums).max().getAsInt();
    return x * k + k * (k - 1) / 2;
  }
}
1
2
3
class Solution:
  def maximizeSum(self, nums: list[int], k: int) -> int:
    return max(nums) * k + k * (k - 1) // 2