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,2,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 2. 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 Problem Overview17365012347 is maximum in entire array (length 5)6 is maximum in [3,6,5] (length 2)For each element, find longest subarray where it is maximum15121Output: [1,5,1,2,1]
Understanding the Visualization
1
Input Array
Array of distinct integers nums = [1,7,3,6,5]
2
Find Boundaries
For each element, find where larger elements block its range
3
Calculate Ranges
Maximum range = right_bound - left_bound - 1
Key Takeaway
🎯 Key Insight: Each element's maximum range is bounded by the nearest larger elements on both sides
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