Sum of minimum and maximum elements of all subarrays of size “k”

Pattern: Monotonic deque

medium

Slide a window of size k with two monotonic deques of indexes: one with values decreasing (its front is the max) and one increasing (its front is the min). Add front max + front min for every full window.

The problem

Return the sum, over every window of k neighbouring values, of the window's minimum plus its maximum. [2, 5, -1, 7, -3, -1, -2] with k = 4 gives 18. The answer is a long.

Think first

  • How do you get the maximum of every window quickly?
  • Can the same idea give the minimum?
  • When is a window full?

Hints

    Brute force, and why it fails

    Scan each window for its min and max: O(n × k).

    The key insight

    Two monotonic deques run side by side; each front is the answer for its side, and each index enters and leaves each deque once.

    Dry run

    20 
    51 
    -12 
    73 
    -34 
    -15 
    -26 
    sum6

    arr = [2, 5, -1, 7, -3, -1, -2], k = 4. First window [2, 5, -1, 7]: max 7, min -1, add 6.

    Step 1 of 4

    The plan

    for i, v in arr:
        pop from maxQ's back while its value <= v; push i
        pop from minQ's back while its value >= v; push i
        drop either front if it is <= i - k
        if i >= k - 1: sum += arr[maxQ.front] + arr[minQ.front]
    

    Complexity

    Time
    O(n)
    Space
    O(k)

    Each index is added to and removed from each deque at most once.

    Edge cases

    • k = 1: each value counts twice.
    • k = n: one window.
    • Equal values.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public long sumOfMinMax(int[] arr, int k) {
            Deque<Integer> maxQ = new ArrayDeque<>(), minQ = new ArrayDeque<>();   // indexes; values decreasing / increasing
            long sum = 0;
            for (int i = 0; i < arr.length; i++) {
                while (!maxQ.isEmpty() && arr[maxQ.peekLast()] <= arr[i]) maxQ.pollLast();   // can never be a max again
                while (!minQ.isEmpty() && arr[minQ.peekLast()] >= arr[i]) minQ.pollLast();   // can never be a min again
                maxQ.addLast(i);
                minQ.addLast(i);
                if (maxQ.peekFirst() <= i - k) maxQ.pollFirst();   // fell out of the window
                if (minQ.peekFirst() <= i - k) minQ.pollFirst();
                if (i >= k - 1) sum += arr[maxQ.peekFirst()] + arr[minQ.peekFirst()];
            }
            return sum;
        }
    }

    C++

    class Solution {
    public:
        long long sumOfMinMax(vector<int>& arr, int k) {
            deque<int> maxQ, minQ;                          // indexes; values decreasing / increasing
            long long sum = 0;
            for (int i = 0; i < static_cast<int>(arr.size()); i++) {
                while (!maxQ.empty() && arr[maxQ.back()] <= arr[i]) maxQ.pop_back();   // can never be a max again
                while (!minQ.empty() && arr[minQ.back()] >= arr[i]) minQ.pop_back();   // can never be a min again
                maxQ.push_back(i);
                minQ.push_back(i);
                if (maxQ.front() <= i - k) maxQ.pop_front();   // fell out of the window
                if (minQ.front() <= i - k) minQ.pop_front();
                if (i >= k - 1) sum += arr[maxQ.front()] + arr[minQ.front()];
            }
            return sum;
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def sumOfMinMax(self, arr: list[int], k: int) -> int:
            max_q, min_q, total = deque(), deque(), 0   # indexes; values decreasing / increasing
            for i, v in enumerate(arr):
                while max_q and arr[max_q[-1]] <= v:
                    max_q.pop()                     # can never be a max again
                while min_q and arr[min_q[-1]] >= v:
                    min_q.pop()                     # can never be a min again
                max_q.append(i)
                min_q.append(i)
                if max_q[0] <= i - k:
                    max_q.popleft()                 # fell out of the window
                if min_q[0] <= i - k:
                    min_q.popleft()
                if i >= k - 1:
                    total += arr[max_q[0]] + arr[min_q[0]]
            return total

    Common mistakes

    • Storing values, so the fronts cannot be dropped when they leave the window.
    • Using 32-bit sums.

    Similar problems