Skip to problem
←

Maximum of Window Minimums

Hard 0 attempts

You're given an integer array of size n. For every window size w from 1 up to n, look at all contiguous subarrays of that length, take the minimum value within each one, and then report the largest of those minimums. Do this for every window size and return the full set of results.

Return an array in increasing window-size order: index w - 1 holds the answer for windows of length w. Windows are contiguous and may overlap.

For [2,1,2], size-1 windows have minima 2,1,2, so the first answer is 2. Both size-2 windows have minimum 1, and the full array also has minimum 1. Return [2,1,1].

Function contract

Implement maximumOfMinimumsOfEveryWindowSizeInAGivenArray(arr). Receive a nonempty integer array; values may be negative.

Output: Return an array of length arr.length. Entry w - 1 is the maximum minimum among all contiguous windows of length w, for w from 1 through arr.length.

Example 1

Input
arr = [10,20,30,50,10,70,30]
Output
[70,30,20,10,10,10,10]

Example 2

Input
arr = [-1,-2,-3]
Output
[-1,-2,-3]
Constraints
  • 1 <= arr.length <= 10^5
  • -10^9 <= arr[i] <= 10^9

Approach: Stack-based with Next/Prev Smaller

For each element, compute the range where it is the minimum using next-smaller and prev-smaller stacks. That element is a candidate for the answer at that range length; take the maximum across candidates. Both boundaries are strictly smaller, so equal values do not prematurely shorten a span.

Propagate answers from larger sizes to smaller sizes: a window with minimum v contains a shorter window with minimum at least v. This fills missing sizes and ensures the answers are non-increasing. Initialize with -Infinity so negative arrays are handled correctly.

javascript
function maximumOfMinimumsOfEveryWindowSizeInAGivenArray(arr) {
  const n = arr.length;
  const left = new Array(n), right = new Array(n), stack = [];
  for (let i = 0; i < n; i++) {
    while (stack.length && arr[stack[stack.length-1]] >= arr[i]) stack.pop();
    left[i] = stack.length ? stack[stack.length-1] : -1;
    stack.push(i);
  }
  stack.length = 0;
  for (let i = n-1; i >= 0; i--) {
    while (stack.length && arr[stack[stack.length-1]] >= arr[i]) stack.pop();
    right[i] = stack.length ? stack[stack.length-1] : n;
    stack.push(i);
  }
  const result = new Array(n + 1).fill(-Infinity);
  for (let i = 0; i < n; i++) {
    const len = right[i] - left[i] - 1;
    result[len] = Math.max(result[len], arr[i]);
  }
  for (let i = n-1; i >= 1; i--) result[i] = Math.max(result[i], result[i+1]);
  return result.slice(1);
}

Time Complexity: O(n)

Space Complexity: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript