Skip to content

Commit 7cb770c

Browse files
committed
Add solution #813
1 parent 0aac37e commit 7cb770c

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,7 @@
621621
810|[Chalkboard XOR Game](./0810-chalkboard-xor-game.js)|Hard|
622622
811|[Subdomain Visit Count](./0811-subdomain-visit-count.js)|Medium|
623623
812|[Largest Triangle Area](./0812-largest-triangle-area.js)|Easy|
624+
813|[Largest Sum of Averages](./0813-largest-sum-of-averages.js)|Medium|
624625
819|[Most Common Word](./0819-most-common-word.js)|Easy|
625626
821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy|
626627
824|[Goat Latin](./0824-goat-latin.js)|Easy|

Diff for: solutions/0813-largest-sum-of-averages.js

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 813. Largest Sum of Averages
3+
* https://leetcode.com/problems/largest-sum-of-averages/
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer array nums and an integer k. You can partition the array into at most
7+
* k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each
8+
* subarray.
9+
*
10+
* Note that the partition must use every integer in nums, and that the score is not necessarily
11+
* an integer.
12+
*
13+
* Return the maximum score you can achieve of all the possible partitions. Answers within 10-6
14+
* of the actual answer will be accepted.
15+
*/
16+
17+
/**
18+
* @param {number[]} nums
19+
* @param {number} k
20+
* @return {number}
21+
*/
22+
var largestSumOfAverages = function(nums, k) {
23+
const prefixSum = new Array(nums.length + 1).fill(0);
24+
for (let i = 0; i < nums.length; i++) {
25+
prefixSum[i + 1] = prefixSum[i] + nums[i];
26+
}
27+
28+
const dp = new Array(nums.length).fill(0).map(() => new Array(k + 1).fill(0));
29+
30+
for (let i = 0; i < nums.length; i++) {
31+
dp[i][1] = calculateAverage(i, nums.length - 1);
32+
}
33+
34+
for (let partitions = 2; partitions <= k; partitions++) {
35+
for (let start = 0; start < nums.length - partitions + 1; start++) {
36+
for (let end = start; end < nums.length - partitions + 1; end++) {
37+
dp[start][partitions] = Math.max(
38+
dp[start][partitions],
39+
calculateAverage(start, end) + dp[end + 1][partitions - 1]
40+
);
41+
}
42+
}
43+
}
44+
45+
return dp[0][k];
46+
47+
function calculateAverage(i, j) {
48+
return (prefixSum[j + 1] - prefixSum[i]) / (j - i + 1);
49+
}
50+
};

0 commit comments

Comments
 (0)