Maximal Range That Each Element Is Maximum in It - Problem

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 subarray nums[l..r], such that the maximum element in that subarray is equal to nums[i].

Return the array ans.

Note that a subarray is a contiguous part of the array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,7,3,6,5]
Output: [1,5,1,3,1]
💡 Note: For nums[0]=1: maximum subarray is [1] with length 1. For nums[1]=7: maximum subarray is [1,7,3,6,5] with length 5. For nums[2]=3: maximum subarray is [3] with length 1. For nums[3]=6: maximum subarray is [3,6,5] with length 3. For nums[4]=5: maximum subarray is [5] with length 1.
Example 2 — Increasing Array
$ Input: nums = [1,2,3,4,5]
Output: [1,2,3,4,5]
💡 Note: In an increasing array, each element can be maximum for all subarrays starting from index 0 up to its position. So nums[i] has maximum range of i+1.
Example 3 — Single Element
$ Input: nums = [10]
Output: [1]
💡 Note: With only one element, it can be maximum only in the subarray containing itself, which has length 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106
  • All elements in nums are distinct

Visualization

Tap to expand
Maximal Range - Element Maximum Subarray INPUT Array nums (0-indexed): 1 i=0 7 i=1 3 i=2 6 i=3 5 i=4 Find max subarray length where each element is the maximum in that subarray. Example: nums[1]=7 7 is max in entire array Range: [0,4], Length: 5 nums = [1,7,3,6,5] ALGORITHM STEPS 1 Monotonic Stack Use stack to track elements in decreasing order 2 Find Left Boundary Scan left to find first element greater than curr 3 Find Right Boundary Scan right to find first element greater than curr 4 Calculate Range ans[i] = right - left - 1 Stack Processing for i=3 (val=6): Left bound: i=1 (7 greater than 6) Right bound: end (no greater elem) Range: [2,4], ans[3] = 4-1-1 = 2 Time: O(n), Space: O(n) FINAL RESULT Output Array ans: 1 i=0 5 i=1 1 i=2 2 i=3 1 i=4 Breakdown: nums[0]=1: Only itself (1) nums[1]=7: Max of all (5) nums[2]=3: Only itself (1) nums[3]=6: [3,6] or [6,5] (2) nums[4]=5: Only itself (1) OK - Verified ans = [1,5,1,2,1] Key Insight: Use monotonic stack to efficiently find the nearest greater element on both left and right sides. The range where element is maximum extends from (left_greater + 1) to (right_greater - 1). TutorialsPoint - Maximal Range That Each Element Is Maximum in It | Optimal Solution
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
29.1K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen