Skip to content

Commit e5f6a6a

Browse files
committed
feat: compelete No.1043
1 parent 73899e5 commit e5f6a6a

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# 1043. Partition Array for Maximum Sum
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Array, Dynamic Programming.
5+
- Similar Questions: Subsequence of Size K With the Largest Even Sum.
6+
7+
## Problem
8+
9+
Given an integer array ```arr```, partition the array into (contiguous) subarrays of length **at most** ```k```. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
10+
11+
Return **the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a **32-bit** integer.**
12+
13+
 
14+
Example 1:
15+
16+
```
17+
Input: arr = [1,15,7,9,2,5,10], k = 3
18+
Output: 84
19+
Explanation: arr becomes [15,15,15,9,10,10,10]
20+
```
21+
22+
Example 2:
23+
24+
```
25+
Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
26+
Output: 83
27+
```
28+
29+
Example 3:
30+
31+
```
32+
Input: arr = [1], k = 1
33+
Output: 1
34+
```
35+
36+
 
37+
**Constraints:**
38+
39+
40+
41+
- ```1 <= arr.length <= 500```
42+
43+
- ```0 <= arr[i] <= 109```
44+
45+
- ```1 <= k <= arr.length```
46+
47+
48+
49+
## Solution
50+
51+
```javascript
52+
/**
53+
* @param {number[]} arr
54+
* @param {number} k
55+
* @return {number}
56+
*/
57+
var maxSumAfterPartitioning = function(arr, k) {
58+
var dp = Array(arr.length).fill(0);
59+
for (var i = 0; i < arr.length; i++) {
60+
var maxValue = 0;
61+
for (var j = 1; j <= k && j - 1 <= i; j++) {
62+
maxValue = Math.max(maxValue, arr[i - j + 1]);
63+
dp[i] = Math.max(dp[i], ( dp[i - j + 1] + maxValue * j);
64+
}
65+
}
66+
return dp[arr.length];
67+
};
68+
```
69+
70+
**Explain:**
71+
72+
`dp[i + 1]` represents array `[0 ... i]` 's maxSumAfterPartitioning. (dp[0] = 0 means nothing, it just helps calculate.)
73+
74+
```
75+
dp[i] = max(
76+
dp[i - 1] + max(arr[i]) * 1,
77+
dp[i - 2] + max(arr[i], arr[i - 1]) * 2,
78+
...
79+
dp[i - k] + max(arr[i], arr[i - 1], ..., arr[i - k]) * k
80+
)
81+
```
82+
83+
`dp[arr.length - 1]` would be the answer in the end of the iteration.
84+
85+
**Complexity:**
86+
87+
* Time complexity : O(n).
88+
* Space complexity : O(n).

0 commit comments

Comments
 (0)