Skip to content

Commit 9364817

Browse files
committed
Time: 14 ms (72.68%), Space: 7.9 MB (58.39%) - LeetHub
1 parent 8510836 commit 9364817

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution {
2+
public:
3+
double go_part(int idx, int n, int k, vector<int>& nums, vector<vector<double>>& cache) {
4+
if(idx >= n)
5+
return 0;
6+
7+
if(cache[idx][k] != -1.0)
8+
return cache[idx][k];
9+
10+
if(k == 0) {
11+
int sum = 0;
12+
int cnt = 0;
13+
14+
for(int i = idx; i < n; i++) {
15+
sum += nums[i];
16+
cnt++;
17+
}
18+
19+
double ans = (double)sum/cnt;
20+
return ans;
21+
}
22+
23+
24+
25+
double mx = 0.0;
26+
double cum = 0;
27+
int cnt = 0;
28+
double avg = 0.0;
29+
30+
for(int i = idx; i < n; i++) {
31+
cum += nums[i];
32+
cnt++;
33+
avg = (double) cum / cnt;
34+
mx = max(mx, avg + go_part(i + 1, n, k - 1, nums, cache));
35+
}
36+
37+
return cache[idx][k] = mx;
38+
}
39+
40+
double largestSumOfAverages(vector<int>& nums, int k) {
41+
int n = nums.size();
42+
vector<vector<double>> cache(n, vector<double>(k, -1.0));
43+
double ans = go_part(0, n, k-1, nums, cache);
44+
return ans;
45+
}
46+
};

0 commit comments

Comments
 (0)