forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LargestSumOfAverages.java
65 lines (53 loc) · 2.02 KB
/
LargestSumOfAverages.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package dynamic_programming;
/**
* Created by gouthamvidyapradhan on 04/05/2018.
* 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.
Solution: O(N x N x K): Calculate average for each sub-array starting from the right.
*/
public class LargestSumOfAverages {
public static void main(String[] args) {
int[] A = {9,1,2,3,9};
System.out.println(new LargestSumOfAverages().largestSumOfAverages(A, 3));
}
public double largestSumOfAverages(int[] A, int K) {
double[][] dp = new double[K][A.length];
for(int i = dp[0].length - 1; i >= 0; i --){
dp[0][i] = A[i];
if(i + 1 < dp[0].length){
dp[0][i] += dp[0][i + 1];
}
}
for(int i = dp[0].length - 1, j = 1; i >= 0; i --, j++){
dp[0][i] = dp[0][i] / j;
}
for(int i = dp[0].length - 1; i >= 0; i --){
for(int j = 1; j < dp.length; j ++){
double sum = 0.0D;
for(int k = i, c = 1; k < dp[0].length; k ++, c++){
sum += A[k];
if(k + 1 < dp[0].length){
double avg = sum / c;
avg += dp[j - 1][k + 1];
dp[j][i] = Math.max(dp[j][i], avg);
}
}
}
}
return dp[K-1][0];
}
}