[LeetCode] Largest Sum of Averages

813. Largest Sum of Averages

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
double dp[111][111];
double helper(vector<long long>& A, int pos, int k) {
if(pos + 1 == A.size()) return 0;
if(k == 1) return 1.0 * (A.back() - A[pos]) / (A.size() - pos -1);
if(dp[pos][k] > 0) return dp[pos][k];
double& res = dp[pos][k];
for(int i = pos + 1; i < A.size(); i++) {
res = max(res, 1.0 * (A[i] - A[pos]) / (i - pos) + helper(A, i, k - 1));
}
return res;
}
public:
double largestSumOfAverages(vector<int>& nums, int k) {
memset(dp, 0, sizeof dp);
vector<long long> psum{0};
for(auto& n : nums) psum.push_back(psum.back() + n);
return helper(psum, 0, k);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/31/PS/LeetCode/largest-sum-of-averages/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.