Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in nums, and that the score is not necessarily an integer.
Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted.
Example 1:
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.
Example 2:
Input: nums = [1,2,3,4,5,6,7], k = 4 Output: 20.50000
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 1041 <= k <= nums.lengthProblem summary: You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray. Note that the partition must use every integer in nums, and that the score is not necessarily an integer. Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[9,1,2,3,9] 3
[1,2,3,4,5,6,7] 4
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #813: Largest Sum of Averages
class Solution {
private Double[][] f;
private int[] s;
private int n;
public double largestSumOfAverages(int[] nums, int k) {
n = nums.length;
s = new int[n + 1];
f = new Double[n][k + 1];
for (int i = 0; i < n; ++i) {
s[i + 1] = s[i] + nums[i];
}
return dfs(0, k);
}
private double dfs(int i, int k) {
if (i == n) {
return 0;
}
if (k == 1) {
return (s[n] - s[i]) * 1.0 / (n - i);
}
if (f[i][k] != null) {
return f[i][k];
}
double ans = 0;
for (int j = i + 1; j < n; ++j) {
ans = Math.max(ans, (s[j] - s[i]) * 1.0 / (j - i) + dfs(j, k - 1));
}
return f[i][k] = ans;
}
}
// Accepted solution for LeetCode #813: Largest Sum of Averages
func largestSumOfAverages(nums []int, k int) float64 {
n := len(nums)
s := make([]int, n+1)
for i, x := range nums {
s[i+1] = s[i] + x
}
f := make([][]float64, n)
for i := range f {
f[i] = make([]float64, k+1)
}
var dfs func(int, int) float64
dfs = func(i, k int) float64 {
if i == n {
return 0
}
if f[i][k] > 0 {
return f[i][k]
}
if k == 1 {
return float64(s[n]-s[i]) / float64(n-i)
}
ans := 0.0
for j := i + 1; j < n; j++ {
ans = math.Max(ans, float64(s[j]-s[i])/float64(j-i)+dfs(j, k-1))
}
f[i][k] = ans
return ans
}
return dfs(0, k)
}
# Accepted solution for LeetCode #813: Largest Sum of Averages
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)
// Accepted solution for LeetCode #813: Largest Sum of Averages
struct Solution;
use std::collections::HashMap;
impl Solution {
fn largest_sum_of_averages(a: Vec<i32>, k: i32) -> f64 {
let n = a.len();
let k = k as usize;
let mut memo: HashMap<(usize, usize), f64> = HashMap::new();
Self::dp(n, k, &mut memo, &a)
}
fn dp(n: usize, k: usize, memo: &mut HashMap<(usize, usize), f64>, a: &[i32]) -> f64 {
if n == 0 {
0.0
} else {
if let Some(&res) = memo.get(&(n, k)) {
return res;
}
let res = if k == 1 {
a[0..n].iter().sum::<i32>() as f64 / n as f64
} else {
let mut last = 0.0;
let mut res: f64 = 0.0;
for i in (0..n).rev() {
last += a[i] as f64;
let avg = last as f64 / (n - i) as f64;
res = res.max(avg + Self::dp(i, k - 1, memo, a));
}
res
};
memo.insert((n, k), res);
res
}
}
}
#[test]
fn test() {
use assert_approx_eq::assert_approx_eq;
let a = vec![9, 1, 2, 3, 9];
let k = 3;
let res = 20.0;
assert_approx_eq!(Solution::largest_sum_of_averages(a, k), res);
}
// Accepted solution for LeetCode #813: Largest Sum of Averages
function largestSumOfAverages(nums: number[], k: number): number {
const n = nums.length;
const s: number[] = Array(n + 1).fill(0);
for (let i = 0; i < n; i++) {
s[i + 1] = s[i] + nums[i];
}
const f: number[][] = Array.from({ length: n }, () => Array(k + 1).fill(0));
const dfs = (i: number, k: number): number => {
if (i === n) {
return 0;
}
if (f[i][k] > 0) {
return f[i][k];
}
if (k === 1) {
return (s[n] - s[i]) / (n - i);
}
for (let j = i + 1; j < n; j++) {
f[i][k] = Math.max(f[i][k], dfs(j, k - 1) + (s[j] - s[i]) / (j - i));
}
return f[i][k];
};
return dfs(0, k);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.