Maximum and Minimum Sums of at Most Size K Subarrays Problem
Description
LeetCode Problem 3430.
You are given an integer array nums and a positive integer k. Return the sum of the maximum and minimum elements of all subarrays with at most k elements.
Example 1:
Input: nums = [1,2,3], k = 2
Output: 20
Explanation:
The subarrays of nums with at most 2 elements are:
Subarray Minimum Maximum Sum
[1] 1 1 2
[2] 2 2 4
[3] 3 3 6
[1, 2] 1 2 3
[2, 3] 2 3 5
Final Total 20
The output would be 20.
Example 2:
Input: nums = [1,-3,1], k = 2
Output: -6
Explanation:
The subarrays of nums with at most 2 elements are:
Subarray Minimum Maximum Sum
[1] 1 1 2
[-3] -3 -3 -6
[1] 1 1 2
[1, -3] -3 1 -2
[-3, 1] -3 1 -2
Final Total -6
The output would be -6.
Constraints:
1 <= nums.length <= 800001 <= k <= nums.length-10^6 <= nums[i] <= 10^6
Solution
Approach: Monotonic Stacks
Process the array from left to right. For each end index i, the valid subarrays are those starting in [max(0, i - k + 1), i]. The answer is the sum, over every i, of (the sum of the maximums) plus (the sum of the minimums) of those subarrays.
Keep two deques, one for maximums and one for minimums. Each entry is [index, value, count]: count is the number of current start positions for which value is the maximum (or minimum). We also keep the running sums maxSum and minSum over all start positions of the current end.
When the window start moves forward by one (i >= k), the start that leaves the window was served by the front entry. We subtract that entry's value from the running sum, lower its count by one, and drop the entry if its index is now outside the window.
Then add nums[i]. For the maximum stack, pop every entry with a value <= nums[i]: nums[i] becomes the maximum for all the starts they covered, so we add their counts to the new entry and add (nums[i] - value) * count to maxSum. The new subarray [i, i] adds nums[i]. The minimum stack does the same with >=. After each step, add maxSum + minSum to the answer.
Complexity: O(n) time and O(n) space, since each element enters and leaves each deque once.
from collections import deque
class Solution:
def minMaxSubarraySum(self, nums: List[int], k: int) -> int:
subarrays_max_min_sum = 0
max_stack: deque[List[int]] = deque([]) # Format: [idx, num, shares].
subarrays_max_sum = 0
min_stack: deque[List[int]] = deque([]) # Format: [idx, num, shares].
subarrays_min_sum = 0
for end_idx, num in enumerate(nums):
start_idx = max(0, end_idx - k + 1)
# Window start idx slides by 1: must update stacks' info.
if start_idx > 0:
max_stack[0][2] -= 1 # Decrement stack's front num shares.
subarrays_max_sum -= max_stack[0][1]
if max_stack[0][0] < start_idx: # Front num out of window.
max_stack.popleft()
min_stack[0][2] -= 1 # Decrement stack's front num shares.
subarrays_min_sum -= min_stack[0][1]
if min_stack[0][0] < start_idx: # Front num out of window.
min_stack.popleft()
max_shares = 1 # Base case.
subarrays_max_sum += num
while max_stack and max_stack[-1][1] <= num:
_, prev_num, prev_shares = max_stack.pop()
max_shares += prev_shares # Max shares transition.
# Reflect transition in max sum.
subarrays_max_sum += (num - prev_num) * prev_shares
max_stack.append([end_idx, num, max_shares])
min_shares = 1 # Base case.
subarrays_min_sum += num
while min_stack and min_stack[-1][1] >= num:
_, prev_num, prev_shares = min_stack.pop()
min_shares += prev_shares # Min shares transition.
# Reflect transition in min sum.
subarrays_min_sum += (num - prev_num) * prev_shares
min_stack.append([end_idx, num, min_shares])
subarrays_max_min_sum += subarrays_max_sum + subarrays_min_sum
return subarrays_max_min_sum