Imagine you're analyzing performance data for an online system, where each element in an array represents a metric value. You need to understand the range of performance (both peaks and valleys) across all possible monitoring windows.
Given an integer array nums and a positive integer k, your task is to find the sum of maximum and minimum elements from all possible subarrays that contain at most k elements.
For example, with nums = [1, 3, 2] and k = 2:
- Subarrays of size 1:
[1],[3],[2]โ contribute1+1=2,3+3=6,2+2=4 - Subarrays of size 2:
[1,3],[3,2]โ contribute3+1=4,3+2=5 - Total sum:
2 + 6 + 4 + 4 + 5 = 21
Goal: Return the total sum of (maximum + minimum) for all valid subarrays efficiently.
Input & Output
Visualization
Time & Space Complexity
Each element is pushed and popped from stack at most once, and contribution calculation is O(1) per element
Space needed for monotonic stacks and auxiliary arrays
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 106
- 1 โค k โค nums.length
- All elements are positive integers