BackhardStackGoldman SachsAmazon

Centroid Tree Metric Engine 3 Solution

Problem Statement

You are given an integer array nums of length N and an integer k (1 ≤ k ≤ N). For every contiguous subarray (window) of length k, compute the difference between the maximum and the minimum element inside that window. Let D_i denote this difference for the i‑th window (1‑based). Your task is to output the sum S = Σ_{i=1}^{N‑k+1} D_i. The required time complexity is O(N) and the intended solution uses a monotonic queue (deque) to maintain the current window's maximum and minimum values while sliding the window across the array.

Example 1
Input
5 3 1 4 2 7 5
Output
13

Explanation: The three windows of size 3 are: 1) [1,4,2] → max=4, min=1, diff=3 2) [4,2,7] → max=7, min=2, diff=5 3) [2,7,5] → max=7, min=2, diff=5 Sum = 3 + 5 + 5 = 13.

Example 2
Input
6 2 -1 3 -2 8 0 4
Output
31

Explanation: The five windows of size 2 are: 1) [-1,3] → max=3, min=-1, diff=4 2) [3,-2] → max=3, min=-2, diff=5 3) [-2,8] → max=8, min=-2, diff=10 4) [8,0] → max=8, min=0, diff=8 5) [0,4] → max=4, min=0, diff=4 Sum = 4+5+10+8+4 = 31.

Example 3
Input
4 4 5 5 5 5
Output
0

Explanation: Only one window of size 4 exists: [5,5,5,5]. max = min = 5, diff = 0. Hence the total sum is 0.

Constraints

  • 1 <= N <= 2*10^5
  • 1 <= k <= N
  • -10^9 <= nums[i] <= 10^9
  • The sum of N over all test cases does not exceed 2*10^5.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Centroid Tree Metric Engine 3 — Problem Statement & Solution Guide

StackHardMonotonic Queue Sliding Horizon
TimeO(N)
|
SpaceO(k)

Problem Description

You are given an integer array nums of length N and an integer k (1 ≤ k ≤ N). For every contiguous subarray (window) of length k, compute the difference between the maximum and the minimum element inside that window. Let D_i denote this difference for the i‑th window (1‑based). Your task is to output the sum S = Σ_{i=1}^{N‑k+1} D_i. The required time complexity is O(N) and the intended solution uses a monotonic queue (deque) to maintain the current window's maximum and minimum values while sliding the window across the array.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Centroid Tree Metric Engine 3"

hard

WHY DOES IT MATTER?

Sliding‑window monotonic deques turn a seemingly quadratic problem into linear time, a pattern that recurs in many real‑time analytics, signal processing, and streaming scenarios where you need fast aggregates over moving intervals.

OPTIMIZATION CHALLENGE

The breakthrough is recognizing that any element dominated by a newer, more extreme element can be discarded forever, which limits each element to a single push and pop, collapsing the naive O(N·k) bound to O(N).

REAL-WORLD CONNECTION

Think of a network traffic monitor that continuously reports the highest and lowest packet latency over the last 5 seconds. Maintaining two priority queues would be costly; a monotonic deque acts like a rolling “peak detector” that updates instantly as new packets arrive and old ones expire.

When coding, keep the deques storing indices, not values, so you can efficiently check whether the front element has slid out of the current window (index <= i‑k). This tiny detail prevents subtle off‑by‑one bugs.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(k)

Core Theory — Why This Approach?

The problem asks for the sum of range (max‑min) over every contiguous subarray of length k. A naïve solution would recompute the maximum and minimum for each window, costing O(k) per window and O(N·k) overall, which is prohibitive when N is up to 10^6. The optimal paradigm leverages the monotonic deque (or double‑ended queue) to maintain candidates for the maximum and minimum in a sliding window. By storing indices in decreasing order for the max‑deque and increasing order for the min‑deque, the front of each deque always represents the current window’s extreme value. As the window slides one step, we discard indices that fall out of the window and purge elements that are no longer useful, guaranteeing each array element is pushed and popped at most once – yielding linear time.

This approach belongs to the broader class of “sliding window” techniques, where a data structure must support O(1) query of a window property while allowing O(1) amortized updates as the window moves. The monotonic deque is especially powerful for order‑statistics like min, max, or even median approximations, because it encodes the ordering relationship directly, avoiding the overhead of balanced trees or heaps. The key insight is that any element that is smaller (for max) or larger (for min) than a newer element can never become the window’s extreme again, so it can be safely removed, keeping the structure compact and guaranteeing O(N) total work.

Interview Questions on This Problem

Q1How would you compute the sum of max‑min differences for all windows of size k in O(N) time?

Use two monotonic deques: one decreasing for the maximum and one increasing for the minimum. For each index i, push it into both deques while removing elements that violate monotonicity. When i >= k‑1, the front of the max‑deque is the window’s maximum and the front of the min‑deque is the minimum; add their difference to the answer and then evict indices i‑k+1 that are out of the window.

Q2Why can an element be removed from a monotonic deque even if it hasn’t left the window yet?

Because the deque maintains a strict monotonic order; if a newer element is larger (for max) or smaller (for min) than an older one, the older element can never become the extreme again while the newer element remains in the window, so it can be discarded to keep the deque minimal.

Q3What modifications would you make to handle the case where k = 1 or k = N?

When k = 1, each window’s max and min are the element itself, so the sum is zero; the algorithm naturally handles this because both deques will contain the same single index and the difference will be zero. When k = N, the deques will end up holding the global max and min after processing the whole array, and the sum reduces to a single term (global max‑min). No special code is required beyond the standard sliding‑window loop.

Examples

Example 1

Input

5 3
1 4 2 7 5

Output

13

Explanation: The three windows of size 3 are: 1) [1,4,2] → max=4, min=1, diff=3 2) [4,2,7] → max=7, min=2, diff=5 3) [2,7,5] → max=7, min=2, diff=5 Sum = 3 + 5 + 5 = 13.

Example 2

Input

6 2
-1 3 -2 8 0 4

Output

31

Explanation: The five windows of size 2 are: 1) [-1,3] → max=3, min=-1, diff=4 2) [3,-2] → max=3, min=-2, diff=5 3) [-2,8] → max=8, min=-2, diff=10 4) [8,0] → max=8, min=0, diff=8 5) [0,4] → max=4, min=0, diff=4 Sum = 4+5+10+8+4 = 31.

Example 3

Input

4 4
5 5 5 5

Output

0

Explanation: Only one window of size 4 exists: [5,5,5,5]. max = min = 5, diff = 0. Hence the total sum is 0.

Constraints

  • 1 <= N <= 2*10^5
  • 1 <= k <= N
  • -10^9 <= nums[i] <= 10^9
  • The sum of N over all test cases does not exceed 2*10^5.

Optimal Approach & Strategy

Maintain two monotonic deques (max and min) that support O(1) retrieval of the window’s extremes while allowing O(1) amortized updates as the window slides, achieving O(N) total time.

Brute Force Approach

For each window, scan the k elements to find its max and min, compute the difference, and accumulate; this costs O(k) per window, O(N·k) overall.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums) {
   const monotonicQueue = [];
   let sum = 0;
   for (let i = 0; i < nums.length; i++) {
       while (monotonicQueue.length > 0 && nums[monotonicQueue[monotonicQueue.length - 1]] < nums[i]) {
           monotonicQueue.pop();
       }
       monotonicQueue.push(i);
       sum += nums[i];
   }
   return sum;
}

Asked in Top Tech Interviews

Goldman SachsAmazon

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.