- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 50 lines of Python from the credited upstream file 3430.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 3 def minMaxSubarraySum(self, nums: list[int], k: int) -> int:4 prevGt, nextGt = self._getPrevNext(nums, operator.lt)5 prevLt, nextLt = self._getPrevNext(nums, operator.gt)6 return (self._subarraySum(nums, prevGt, nextGt, k) +7 self._subarraySum(nums, prevLt, nextLt, k))8 9 def _subarraySum(10 self,11 nums: list[int],12 prev: list[int],13 next: list[int],14 k: int15 ) -> int:16 """17 Returns the sum of all subarrays with a size <= k, The `prev` and `next`18 arrays are used to store the indices of the nearest numbers that are19 smaller or larger than the current number, respectively.20 """21 res = 022 for i, num in enumerate(nums):23 l = min(i - prev[i], k)24 r = min(next[i] - i, k)25 extra = max(0, l + r - 1 - k)26 res += num * (l * r - extra * (extra + 1) 2)27 return res28 29 def _getPrevNext(30 self,31 nums: list[int],32 op: callable33 ) -> tuple[list[int], list[int]]:34 """35 Returns `prev` and `next`, that store the indices of the nearest numbers36 that are smaller or larger than the current number depending on `op`.37 """38 n = len(nums)39 prev = [-1] * n40 next = [n] * n41 stack = []42 for i, num in enumerate(nums):43 while stack and op(nums[stack[-1]], num):44 index = stack.pop()45 next[index] = i46 if stack:47 prev[i] = stack[-1]48 stack.append(i)49 return prev, next50