Problem solution · C++

Maximum and Minimum Sums of at Most Size K Subarrays

Maximum and Minimum Sums of at Most Size K Subarrays: a C++ solution using stack-based processing. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Stack-based processing
Source
walkccc LeetCode Solutions
Length
48 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

Stack-based processing

For Maximum and Minimum Sums of at Most Size K Subarrays, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.

  1. Define what every stack entry represents.
  2. Pop entries once the current item resolves or invalidates them.
  3. Push the current item with only the information later steps need.

Code notes

  • 48 lines of C++ from the credited upstream file 3430.cpp.
  • The implementation visibly relies on sequence storage.
  • 3 loop blocks detected.

Complexity

If each item is pushed and popped at most once, the stack work is linear.

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 codeMaximum and Minimum Sums of at Most Size K Subarrays · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  // Similar to 2104. Sum of Subarray Ranges  long long minMaxSubarraySum(const vector<int>& nums, int k) {    const auto [prevGt, nextGt] = getPrevNext(nums, less<>());    const auto [prevLt, nextLt] = getPrevNext(nums, greater<>());    return subarraySum(nums, prevGt, nextGt, k) +           subarraySum(nums, prevLt, nextLt, k);  }  private:  // Returns the sum of all subarrays with a size <= k, The `prev` and `next`  // arrays are used to store the indices of the nearest numbers that are  // smaller or larger than the current number, respectively.  long subarraySum(const vector<int>& nums, const vector<int>& prev,                   const vector<int>& next, int k) {    long res = 0;    for (int i = 0; i < nums.size(); ++i) {      const int l = min(i - prev[i], k);      const int r = min(next[i] - i, k);      const int extra = max(0, l + r - 1 - k);      res += nums[i] * static_cast<long>(l * r - extra * (extra + 1) / 2);    }    return res;  }   // Returns `prev` and `next`, that store the indices of the nearest numbers  // that are smaller or larger than the current number depending on `op`.  pair<vector<int>, vector<int>> getPrevNext(      const vector<int>& nums, const function<bool(int, int)>& op) {    const int n = nums.size();    vector<int> prev(n, -1);    vector<int> next(n, n);    stack<int> stack;    for (int i = 0; i < n; ++i) {      while (!stack.empty() && op(nums[stack.top()], nums[i])) {        const int index = stack.top();        stack.pop();        next[index] = i;      }      if (!stack.empty())        prev[i] = stack.top();      stack.push(i);    }    return {prev, next};  }}; 

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 ↗