MediumNo. 0813
Largest Sum of Averages — LeetCode 813 Python Solution
- Pattern
- Prefix Sum
- Topics
- Array, Dynamic Programming, 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
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
- Time
- O(n2 × k)
- Space · auxiliary
- O(n × k)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0689 | Maximum Sum of 3 Non-Overlapping Subarrays | Hard |
| 1000 | Minimum Cost to Merge Stones | Hard |
| 1140 | Stone Game II | Medium |
| 1444 | Number of Ways of Cutting a Pizza | Hard |
| 1524 | Number of Sub-arrays With Odd Sum | Medium |
| 1687 | Delivering Boxes from Storage to Ports | Hard |
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(n2 × k).
- What is the space complexity of LeetCode 813. Largest Sum of Averages?
The Python solution on this page uses O(n × 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.