Skip to content

Commit 75aa6de

Browse files
committed
Add solution #1043
1 parent 773ae55 commit 75aa6de

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,116 LeetCode solutions in JavaScript
1+
# 1,117 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -850,6 +850,7 @@
850850
1040|[Moving Stones Until Consecutive II](./solutions/1040-moving-stones-until-consecutive-ii.js)|Medium|
851851
1041|[Robot Bounded In Circle](./solutions/1041-robot-bounded-in-circle.js)|Medium|
852852
1042|[Flower Planting With No Adjacent](./solutions/1042-flower-planting-with-no-adjacent.js)|Medium|
853+
1043|[Partition Array for Maximum Sum](./solutions/1043-partition-array-for-maximum-sum.js)|Medium|
853854
1047|[Remove All Adjacent Duplicates In String](./solutions/1047-remove-all-adjacent-duplicates-in-string.js)|Easy|
854855
1051|[Height Checker](./solutions/1051-height-checker.js)|Easy|
855856
1071|[Greatest Common Divisor of Strings](./solutions/1071-greatest-common-divisor-of-strings.js)|Easy|
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 1043. Partition Array for Maximum Sum
3+
* https://leetcode.com/problems/partition-array-for-maximum-sum/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array arr, partition the array into (contiguous) subarrays of length at most k.
7+
* After partitioning, each subarray has their values changed to become the maximum value of that
8+
* subarray.
9+
*
10+
* Return the largest sum of the given array after partitioning. Test cases are generated so that
11+
* the answer fits in a 32-bit integer.
12+
*/
13+
14+
/**
15+
* @param {number[]} arr
16+
* @param {number} k
17+
* @return {number}
18+
*/
19+
var maxSumAfterPartitioning = function(arr, k) {
20+
const dp = new Array(arr.length + 1).fill(0);
21+
22+
for (let i = 1; i <= arr.length; i++) {
23+
let maxVal = 0;
24+
for (let j = 1; j <= Math.min(k, i); j++) {
25+
maxVal = Math.max(maxVal, arr[i - j]);
26+
dp[i] = Math.max(dp[i], dp[i - j] + maxVal * j);
27+
}
28+
}
29+
30+
return dp[arr.length];
31+
};

0 commit comments

Comments
 (0)