EasyNo. 2656

Maximum Sum With Exactly K Elements — LeetCode 2656 Python Solution

Pattern
Greedy
Topics
Greedy, Array
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

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

Complexity

Time
O(n log n)
Space · auxiliary
O(1) to O(n)

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

Related problems
No.ProblemDifficulty
0011Container With Most WaterMedium
0134Gas StationMedium
0135CandyHard
0179Largest NumberMedium
0324Wiggle Sort IIMedium
0330Patching ArrayHard

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.

Free to download. Check it runs on your machine, then pick a plan.