LeetCode 0962. Maximum Width Ramp Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0962. Maximum Width Ramp

Description

A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i.

Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.

 

Example 1:

Input: nums = [6,0,8,2,1,5]
Output: 4
Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.

Example 2:

Input: nums = [9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.

 

Constraints:

  • 2 <= nums.length <= 5 * 104
  • 0 <= nums[i] <= 5 * 104

Solutions

Solution 1: Monotonic Stack

According to the problem, we can find that the subsequence formed by all possible nums[i] must be monotonically decreasing. Why is that? Let's prove it by contradiction.

Suppose there exist i1<i2 and nums[i1]nums[i2], then actually nums[i2] cannot be a candidate value, because nums[i1] is more to the left and would be a better value. Therefore, the subsequence formed by nums[i] must be monotonically decreasing, and i must start from 0.

We use a monotonically decreasing stack stk (from bottom to top) to store all possible nums[i]. Then we traverse j starting from the right boundary. If we encounter nums[stk.top()]nums[j], it means a ramp is formed at this point. We cyclically pop the top elements from the stack and update ans.

The time complexity is O(n) and the space complexity is O(n), where n represents the length of nums.

PythonJavaC++GoTypeScriptJavaScript
class Solution: def maxWidthRamp(self, nums: List[int]) -> int: stk = [] for i, v in enumerate(nums): if not stk or nums[stk[-1]] > v: stk.append(i) ans = 0 for i in range(len(nums) - 1, -1, -1): while stk and nums[stk[-1]] <= nums[i]: ans = max(ans, i - stk.pop()) if not stk: break return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !