998. Static Range Max

Medium3.5 points estimatedArrayDivide and Conquer3 hints

A lighthouse crew records the wave height measured each hour; nums[i] is the height at hour i. Captains keep asking for the tallest wave during a window of hours, and the log never changes.

Each query is a pair [a, b]. The window runs between the hours a mod n and b mod n, both inclusive, where n is the length of nums; if the first of these is larger than the second, swap them. Return an array with the maximum height of every window, in query order. After preprocessing, each query should be answered in O(1) time.

Example 1

Input:
nums = [12,-4,30,7,7,-9,21,15]queries = [[1,4],[6,0],[5,5],[9,16]]
Output:
[30,30,-9,12]
Explanation:

Hours 1..4 peak at 30; the pair (6, 0) is swapped to 0..6 which also peaks at 30; hour 5 alone is -9; and (9, 16) reduces to hours 1 and 0, i.e. the window 0..1, with maximum 12.

Example 2

Input:
nums = [-8,-3,-12,-5], queries = [[0,3],[2,2],[3,2]]
Output:
[-3,-12,-5]
Explanation:

With every reading negative the answers are the least negative values: -3 for the whole log, -12 for hour 2 alone and -5 for hours 2..3.

Constraints

1 ≤ nums.length ≤ 2 * 105

-99 ≤ nums[i] ≤ 999

1 ≤ queries.length ≤ 1400, and 0 ≤ a, b ≤ 109 in every query

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n log n + q)
Space
O(n log n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…