Maximum sum with exactly k elements

May 4, 2023

array-and-hashmap

Problem URL: Maximum sum with exactly k elements

We will pick up the maximum number and add it to the result. Then for each iteration of k, we add 1 to the maximum number and add it to the result. We will return the result.

class Solution:
    def maximizeSum(self, nums: List[int], k: int) -> int:
        max_num = max(nums)
        res = 0
        for _ in range(k):
            res += max_num
            max_num += 1
        return res

Time complexity: O(k)
Space complexity: O(1)