Largest Sum of Averages — LeetCode 813 Python Solution
MediumArrayDynamic ProgrammingPrefix Sum
- Problem
- #813
- Pattern
- Prefix Sum
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays.
Example
- Input
- nums = [9,1,2,3,9], k = 3
- Output
- 20.00000
- Explanation
- The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
Python solution
Python
class Solution:
def largestSumOfAverages(self, nums: List[int], k: int) -> float:
@cache
def dfs(i: int, k: int) -> float:
if i == n:
return 0
if k == 1:
return (s[n] - s[i]) / (n - i)
ans = 0
for j in range(i + 1, n):
ans = max(ans, (s[j] - s[i]) / (j - i) + dfs(j, k - 1))
return ans
n = len(nums)
s = list(accumulate(nums, initial=0))
return dfs(0, k)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2 \times k) |
| Space | O(n \times k) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 813. Largest Sum of Averages is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 813. Largest Sum of Averages?
- LeetCode 813. Largest Sum of Averages is rated Medium on LeetCode.
- What is the time complexity of LeetCode 813. Largest Sum of Averages?
- The Python solution on this page runs in O(n^2 \times k).
- What is the space complexity of LeetCode 813. Largest Sum of Averages?
- The Python solution on this page uses O(n \times k) auxiliary space.
- What topics does LeetCode 813. Largest Sum of Averages cover?
- LeetCode 813. Largest Sum of Averages is tagged Array, Dynamic Programming and Prefix Sum on LeetCode.