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.
Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: arr = [1,15,7,9,2,5,10], k = 3 Output: 84 Explanation: arr becomes [15,15,15,9,10,10,10]
Example 2:
Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4 Output: 83
Example 3:
Input: arr = [1], k = 1 Output: 1
Constraints:
1 <= arr.length <= 5000 <= arr[i] <= 1091 <= k <= arr.lengthThis 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.
This C program uses a dynamic programming approach with an array dp to compute the maximum sum achievable by partitioning the input array. The dp array keeps track of maximum possible sums where the loop iteratively calculates maximum sums by trying all possible partitions from 1 to k and updating dp based on the largest found values for each segment.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n * k) since for each index, we consider up to k previous elements.
Space Complexity: O(n) for 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.
In this C solution, a recursive function named helper is used to evaluate possible partitions lazily. The use of memoization, through an integer array memo, optimizes this by caching previously calculated subproblem results. This active arrangement ensures computative processes reuse stored values during recursion.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n * k), due to exponential recursive divisions curtailed by memoization.
Space Complexity: O(n) for memoization storage.
| Approach | Complexity |
|---|---|
| Dynamic Programming with One-Dimensional Array | Time Complexity: O(n * k) since for each index, we consider up to |
| Recursive Approach with Memoization | Time Complexity: O(n * k), due to exponential recursive divisions curtailed by memoization. |
LeetCode was HARD until I Learned these 15 Patterns • Ashish Pratap Singh • 1,002,155 views views
Watch 9 more video solutions →Practice Partition Array for Maximum Sum with our built-in code editor and test cases.
Practice on FleetCode