This approach uses dynamic programming with a one-dimensional array to find the solution. We use an array dp
where dp[i]
stores the maximum sum we can get for the array arr
from the 0th index to the ith index. For each position, we try to partition the last k
elements and update the dp array accordingly, keeping track of the maximum value observed in those elements to account for possible transformations.
Time Complexity: O(n * k) since for each index, we consider up to k
previous elements.
Space Complexity: O(n) for the dp array.
1def maxSumAfterPartitioning(arr, k):
2 n = len(arr)
3 dp = [0] * (n + 1)
4 for i in range(1, n + 1):
5 maxElem, maxSum = 0, 0
6 for j in range(1, min(k, i) + 1):
7 maxElem = max(maxElem, arr[i-j])
8 maxSum = max(maxSum, dp[i-j] + maxElem * j)
9 dp[i] = maxSum
10 return dp[n]
11
12arr = [1, 15, 7, 9, 2, 5, 10]
13k = 3
14print(maxSumAfterPartitioning(arr, k))
This Python function operates using a dynamic programming approach encapsulated in a list named dp
. It records the maximum sum feasible by iteratively determining the best partitions up to length k
. During each iteration, potential partitions are evaluated, and the maximum combination is persisted in the dp
array.
In this approach, a recursive function is used to solve the problem, combined with memoization to store previously computed results. The idea is to break the problem into subproblems by recursively partitioning the array from each position and recalculating sums. Alongside recursion, memoization saves time by avoiding recomputation of results for elements already processed.
Time Complexity: O(n * k), due to exponential recursive divisions curtailed by memoization.
Space Complexity: O(n) for memoization storage.
1function maxSumAfterPartitioning(arr, k) {
2 function helper(i) {
3 if (i >= arr.length) return 0;
4 if (memo[i] !== -1) return memo[i];
5 let maxElem = 0, maxSum = 0;
6 for (let j = i; j < Math.min(arr.length, i + k); j++) {
7 maxElem = Math.max(maxElem, arr[j]);
8 maxSum = Math.max(maxSum, maxElem * (j - i + 1) + helper(j + 1));
9 }
10 memo[i] = maxSum;
11 return maxSum;
12 }
13 const memo = new Array(arr.length).fill(-1);
14 return helper(0);
15}
16
17const arr = [1, 15, 7, 9, 2, 5, 10];
18const k = 3;
19console.log(maxSumAfterPartitioning(arr, k));
This JavaScript function applies recursion combined with memoization to address the partitioning problem. Through sequential recursive evaluations, maximum sums are determined, remembering past results using the array memo
to prevent repetitive calculations and enforce efficiency.