Maximal Range That Each Element Is Maximum in It Problem
#2832
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2832.
You are given a 0-indexed array nums of distinct integers.
Let us define a 0-indexed array ans of the same length as nums in the following way:
ans[i]is the maximum length of a subarraynums[l..r], such that the maximum element in that subarray is equal tonums[i].
Return the array ans.
Note that a subarray is a contiguous part of the array.
Example 1:
Input: nums = [1,5,4,3,6]
Output: [1,4,2,1,5]
Explanation: For nums[0] the longest subarray in which 1 is the maximum is nums[0..0] so ans[0] = 1.
For nums[1] the longest subarray in which 5 is the maximum is nums[0..3] so ans[1] = 4.
For nums[2] the longest subarray in which 4 is the maximum is nums[2..3] so ans[2] = 2.
For nums[3] the longest subarray in which 3 is the maximum is nums[3..3] so ans[3] = 1.
For nums[4] the longest subarray in which 6 is the maximum is nums[0..4] so ans[4] = 5.
Example 2:
Input: nums = [1,2,3,4,5]
Output: [1,2,3,4,5]
Explanation: For nums[i] the longest subarray in which it's the maximum is nums[0..i] so ans[i] = i + 1.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5- All elements in
numsare distinct.
Solution
Approach: Monotonic Stack
For each element, use a monotonic stack to find the nearest index on the left and on the right holding a larger value. The longest range in which nums[i] is the maximum has length right[i] - left[i] - 1.
Complexity: time O(n), space O(n).
class Solution:
def maximumLengthOfRanges(self, nums: List[int]) -> List[int]:
n = len(nums)
left = [-1] * n
right = [n] * n
stk = []
for i, x in enumerate(nums):
while stk and nums[stk[-1]] <= x:
stk.pop()
if stk:
left[i] = stk[-1]
stk.append(i)
stk = []
for i in range(n - 1, -1, -1):
while stk and nums[stk[-1]] <= nums[i]:
stk.pop()
if stk:
right[i] = stk[-1]
stk.append(i)
return [r - l - 1 for l, r in zip(left, right)]