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.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- 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.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 4 long long minMaxSubarraySum(const vector<int>& nums, int k) {5 const auto [prevGt, nextGt] = getPrevNext(nums, less<>());6 const auto [prevLt, nextLt] = getPrevNext(nums, greater<>());7 return subarraySum(nums, prevGt, nextGt, k) +8 subarraySum(nums, prevLt, nextLt, k);9 }10 11 private:12 13 14 15 long subarraySum(const vector<int>& nums, const vector<int>& prev,16 const vector<int>& next, int k) {17 long res = 0;18 for (int i = 0; i < nums.size(); ++i) {19 const int l = min(i - prev[i], k);20 const int r = min(next[i] - i, k);21 const int extra = max(0, l + r - 1 - k);22 res += nums[i] * static_cast<long>(l * r - extra * (extra + 1) / 2);23 }24 return res;25 }26 27 28 29 pair<vector<int>, vector<int>> getPrevNext(30 const vector<int>& nums, const function<bool(int, int)>& op) {31 const int n = nums.size();32 vector<int> prev(n, -1);33 vector<int> next(n, n);34 stack<int> stack;35 for (int i = 0; i < n; ++i) {36 while (!stack.empty() && op(nums[stack.top()], nums[i])) {37 const int index = stack.top();38 stack.pop();39 next[index] = i;40 }41 if (!stack.empty())42 prev[i] = stack.top();43 stack.push(i);44 }45 return {prev, next};46 }47};48