Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #813: Largest Sum of Averages

In this guide, we solve Leetcode #813 Largest Sum of Averages in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Array, Dynamic Programming, Prefix Sum

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

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. We could have also partitioned nums into [9, 1], [2], [3, 9], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.

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

The time complexity is O(n2×k)O(n^2 \times k)O(n2×k), and the space complexity is O(n×k)O(n \times k)O(n×k). The space complexity is O(n×k)O(n \times k)O(n×k).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy