I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1043. Partition Array for Maximum Sum, the solution in this repository is mainly a dynamic programming solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: dynamic programming, two pointers.
The notes already sitting in the source point us in the right direction:
- https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/290863/JavaC%2B%2BPython-DP
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are maxSumAfterPartitioning.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/290863/JavaC%2B%2BPython-DP
02//Runtime: 16 ms, faster than 74.57% of C++ online submissions for Partition Array for Maximum Sum.
03//Memory Usage: 8.8 MB, less than 100.00% of C++ online submissions for Partition Array for Maximum Sum.
04
05class Solution {
06public:
07 int maxSumAfterPartitioning(vector<int>& A, int K) {
08 vector<int> dp(A.size());
09
10 for(int i = 0; i < A.size(); i++){
11 int curmax = 0;
12 //split btw i-k and i-k+1, 0,...,i-k | (i-k+1, ... , i)
13 //(i-k+1, ..., i) will all become curmax
14 //from right to left
15 for(int k = 1; k <= K && i-(k-1) >= 0; k++){
16 curmax = max(curmax, A[i-(k-1)]);
17 //dp[i-k] + (dp[i-(k-1)] + ... + dp[i])
18 //dp[i-(k-1)], ..., dp[i] all become curmax
19 dp[i] = max(dp[i], ((i-k >= 0) ? dp[i-k] : 0) + curmax * k);
20 }
21 cout << dp[i] << endl;
22 }
23
24 return dp[A.size()-1];
25 }
26};
Cost