[
array
sort
heap
accumulate
]
BinarySearch 0476 K Maximum Sums
Problem statement
https://binarysearch.com/problems/K-Maximum-Sums/
Solution
Just evaluate all sums and choose the biggest ones.
Complexity
It is O(n^2 log n)
for time and O(n^2)
for space.
Code
class Solution:
def solve(self, nums, k):
acc = [0] + list(accumulate(nums))
n = len(nums)
ans = []
for i in range(n + 1):
for j in range(i + 1, n + 1):
ans += [acc[j] - acc[i]]
return sorted(ans)[-k:]
Remark
Using heaps it is possible to do it in O(n^2 log k)
. Moreover it is possible to make it O(nk log k)
as well.