Skip to content

831. Largest Sum Of Averages

Difficulty: Medium

LeetCode Problem View on GitHub


831. Largest Sum of Averages

Medium


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 <= 100
  • 1 <= nums[i] <= 104
  • 1 <= k <= nums.length

Solution

class Solution {
    private double dp[][];
    public double largestSumOfAverages(int[] nums, int k) {
        int n = nums.length;
        dp = new double[n + 1][k + 1];
        for (double current[] : dp) Arrays.fill(current, Double.MIN_VALUE / 10.0);
        return solve(0, k, nums);
    }
    private double solve(int ind, int k, int arr[]) {
        if (ind == arr.length) return 0;
        if (dp[ind][k] != Double.MIN_VALUE / 10.0) return dp[ind][k];
        double sum = 0;
        if (k == 1) {
            for (int i = ind; i < arr.length; i++) sum += arr[i];
            return dp[ind][k] = sum / (arr.length - ind);
        }
        double maxi = 0.0, count = 0.0;
        for (int i = ind; i < arr.length; i++) {
            sum += arr[i];
            count++;
            double current = sum / count;
            maxi = Math.max(maxi, current + solve(i + 1, k - 1, arr));
        }
        return dp[ind][k] = maxi;
    }
}

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here