Skip to content

Commit 63aed9d

Browse files
authored
Update 1043-partition-array-for-maximum-sum.js
1 parent 62f6696 commit 63aed9d

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

1043-partition-array-for-maximum-sum.js

+26
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,29 @@ const maxSumAfterPartitioning = function(A, K) {
1515
}
1616
return dp[N - 1];
1717
};
18+
19+
// another
20+
21+
/**
22+
* @param {number[]} arr
23+
* @param {number} k
24+
* @return {number}
25+
*/
26+
const maxSumAfterPartitioning = function(arr, k) {
27+
const n = arr.length, memo = Array(n + 1)
28+
memo[0] = 0
29+
return dp(n)
30+
31+
function dp(i) {
32+
if(i === 0) return 0
33+
if(memo[i] != null) return memo[i]
34+
35+
let sum = 0, max = 0, res = 0
36+
for(let j = i; j > 0 && i - j < k; j--) {
37+
max = Math.max(max, arr[j - 1])
38+
sum = (i - j + 1) * max
39+
res = Math.max(res, dp(j - 1) + sum)
40+
}
41+
return memo[i] = res
42+
}
43+
};

0 commit comments

Comments
 (0)