We partition a row of numbers A
into at most K
adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?
Note that our partition must use every number in A, and that scores are not necessarily integers.
Example: Input: A = [9,1,2,3,9] K = 3 Output: 20 Explanation: The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned A into [9, 1], [2], [3, 9], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
Note:
1 <= A.length <= 100
.1 <= A[i] <= 10000
.1 <= K <= A.length
.- Answers within
10^-6
of the correct answer will be accepted as correct.
题意:
给出一个数组和数字k,将这个数组最多分成k部分,是的每部分的平均数之和最大,求最大值。
思路:
还真的挺难的。。。首先设置数组dp[i,k]表示从i到N拆分k部分,那么dp[i,k]=max(dp[i,k]],dp[j,k-1]+average(i,j)),其中average(i,j)表示从i到j这些数的平均数。对于求average(i,j),可以设置一个数组P[i]表示从i到N这些数的和,就可以方便的求,降低时间复杂度。至于如何降低空间复杂度的,还看不太懂。。。。
代码:
class Solution {
public double largestSumOfAverages(int[] A, int K) {
int n=A.length;
double []p=new double[n+1];
double []dp=new double[n];
for(int i=0;i<n;i++)
p[i+1]=p[i]+A[i];
for(int i=0;i<n;i++)
dp[i]=(p[n]-p[i])/(n-i);
for(int i=0;i<K-1;i++)
{
for(int j=0;j<n;j++)
{
for(int t=j+1;t<n;t++)
dp[j]=Math.max(dp[j],dp[t]+(p[t]-p[j])/(t-j));
}
}
return dp[0];
}
}