Maximum Sum With Exactly K Elements — LeetCode 2656 Python Solution
- Problem
- #2656
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
class Solution:
def maximizeSum(self, nums: List[int], k: int) -> int:
x = max(nums)
return k * x + k * (k - 1) // 2Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(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.