#813

Largest Sum of Averages

Medium
ArrayDynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n² * k)
Space
O(1)
O(n * k)
💡

Intuition

Time O(n² * k)Space O(n * k)

The optimal solution uses dynamic programming to efficiently calculate the maximum score. We keep track of the best scores for each possible number of partitions and use previously computed results to build up to the final answer.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP array where dp[i][j] represents the maximum score using the first i elements with j partitions.
  2. 2Step 2: Use a prefix sum array to quickly calculate the average of any subarray.
  3. 3Step 3: Iterate through the array and update the DP table based on previous results.
solution.py14 lines
1# Full working Python code
2def largestSumOfAverages(nums, k):
3    n = len(nums)
4    prefix_sum = [0] * (n + 1)
5    for i in range(n):
6        prefix_sum[i + 1] = prefix_sum[i] + nums[i]
7    dp = [[0] * (k + 1) for _ in range(n + 1)]
8    for i in range(1, n + 1):
9        dp[i][1] = prefix_sum[i] / i
10    for j in range(2, k + 1):
11        for i in range(1, n + 1):
12            for m in range(1, i + 1):
13                dp[i][j] = max(dp[i][j], dp[m][j - 1] + (prefix_sum[i] - prefix_sum[m]) / (i - m))
14    return dp[n][k]

Complexity note: The time complexity is O(n² * k) because we iterate through the array and for each element, we check all previous partitions, which results in a nested loop structure.

  • 1Dynamic programming can significantly reduce the time complexity compared to brute force.
  • 2Using prefix sums allows for efficient average calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.