Maximum Sum With Exactly K Elements — LeetCode 2656 Python Solution

EasyGreedyArray
Problem
#2656
Pattern
Greedy
Reading time
2 min

The 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.

Example

Input
nums = [1,2,3,4,5], k = 3
Output
18
Explanation
We need to choose exactly 3 elements from nums to maximize the sum.

Python solution

Python
class Solution:
    def maximizeSum(self, nums: List[int], k: int) -> int:
        x = max(nums)
        return k * x + k * (k - 1) // 2

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2656. Maximum Sum With Exactly K Elements is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2656. Maximum Sum With Exactly K Elements?
LeetCode 2656. Maximum Sum With Exactly K Elements is rated Easy on LeetCode.
What topics does LeetCode 2656. Maximum Sum With Exactly K Elements cover?
LeetCode 2656. Maximum Sum With Exactly K Elements is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview