Problem solution · C++

Sum of K Subarrays With Length at Least M

Sum of K Subarrays With Length at Least M: a C++ solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Dynamic programming
Source
walkccc LeetCode Solutions
Length
37 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Sum of K Subarrays With Length at Least M, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 37 lines of C++ from the credited upstream file 3473-2.cpp.
  • The implementation visibly relies on sequence storage, cached states.
  • 2 loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeSum of K Subarrays With Length at Least M · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  int maxSum(vector<int>& nums, int k, int m) {    constexpr int kInf = 20000000;    const int n = nums.size();    vector<int> prefix(n + 1);    // dp[i][ongoing][r] := the maximum sum of nums[i..n - 1], with `ongoing`    // indicating if a subarray is currently being extended (1) or not (0), and    // `r` segments left to choose    vector<vector<vector<int>>> dp(        n + 1, vector<vector<int>>(2, vector<int>(k + 1, -kInf)));     partial_sum(nums.begin(), nums.end(), prefix.begin() + 1);     // Base case: At the end of the array, if no segments are left, score is 0.    dp[n][0][0] = dp[n][1][0] = 0;     for (int i = n - 1; i >= 0; --i)      for (int rem = 0; rem <= k; ++rem) {        // When no subarray is ongoing:        // 1. Skip nums[i].        dp[i][0][rem] = dp[i + 1][0][rem];        // 2. Start a new segment of length m (only if rem > 0 and there're        // enough elements)        if (rem > 0 && i + m <= n)          dp[i][0][rem] = max(dp[i][0][rem], dp[i + m][1][rem - 1] +                                                 (prefix[i + m] - prefix[i]));        // When a subarray is ongoing:        // 1. End the current subarray (transition to state 0, same index i)        // 2. Extend the current subarray by picking nums[i] and move to i + 1        dp[i][1][rem] = max(dp[i][0][rem], dp[i + 1][1][rem] + nums[i]);      }     return dp[0][0][k];  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗