#3430

Maximum and Minimum Sums of at Most Size K Subarrays

Hard
ArrayMathStackMonotonic StackMonotonic StackSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a monotonic stack to efficiently calculate the contribution of each element as the maximum and minimum in all valid subarrays. This reduces the time complexity significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use two monotonic stacks to find the next and previous greater and smaller elements for each element in the array.
  2. 2Step 2: For each element, calculate how many subarrays it contributes as the maximum and minimum based on the indices found in the stacks.
  3. 3Step 3: Multiply the contribution by the element's value and accumulate the results.
solution.py44 lines
1# Full working Python code
2
3def max_min_sum(nums, k):
4    n = len(nums)
5    total_sum = 0
6    max_contrib = 0
7    min_contrib = 0
8
9    # Monotonic stacks for max
10    max_stack = []
11    for i in range(n):
12        while max_stack and nums[max_stack[-1]] < nums[i]:
13            j = max_stack.pop()
14            left = j - (max_stack[-1] if max_stack else -1)
15            right = i - j
16            max_contrib += nums[j] * left * right
17        max_stack.append(i)
18
19    while max_stack:
20        j = max_stack.pop()
21        left = j - (max_stack[-1] if max_stack else -1)
22        right = n - j
23        max_contrib += nums[j] * left * right
24
25    # Monotonic stacks for min
26    min_stack = []
27    for i in range(n):
28        while min_stack and nums[min_stack[-1]] > nums[i]:
29            j = min_stack.pop()
30            left = j - (min_stack[-1] if min_stack else -1)
31            right = i - j
32            min_contrib += nums[j] * left * right
33        min_stack.append(i)
34
35    while min_stack:
36        j = min_stack.pop()
37        left = j - (min_stack[-1] if min_stack else -1)
38        right = n - j
39        min_contrib += nums[j] * left * right
40
41    return max_contrib - min_contrib
42
43# Example usage
44print(max_min_sum([1, 2, 3], 2))  # Output: 20

Complexity note: The time complexity is O(n) because each element is pushed and popped from the stack at most once. The space complexity is O(n) due to the stacks used to store indices.

  • 1Using monotonic stacks helps efficiently calculate contributions of elements as maximums and minimums.
  • 2Understanding the contribution of each element in terms of its position and neighboring elements is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.