Skip to content

Commit 814d4e8

Browse files
committed
leetcode-962 Maximum width ramp
1 parent 8241ba7 commit 814d4e8

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,8 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
320320
## [LeetCode](https://leetcode.com/problems)
321321
1. [Insert Delete GetRandom in O(1)](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/leetcode/insert_delete_get_random_o1.rb)
322322
2. [Binary Tree Level order Traversal](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/leetcode/binary_tree_level_order_traversal.rb)
323+
3. [Maximum Width Ramp (Leetcode-962)](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/leetcode/maximum_width_ramp.rb)
324+
323325

324326
<a name="grind-75"/>
325327

leetcode/maximum_width_ramp.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
=begin
2+
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.
3+
Given an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.
4+
Example 1:
5+
Input: nums = [6,0,8,2,1,5]
6+
Output: 4
7+
Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.
8+
Example 2:
9+
Input: nums = [9,8,1,0,1,9,4,0,4,1]
10+
Output: 7
11+
Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.
12+
13+
#Problem(962): https://leetcode.com/problems/maximum-width-ramp/description/
14+
=end
15+
16+
# Solution 1 (Using monotonic stack)
17+
# @param {Integer[]} nums
18+
# @return {Integer}
19+
def max_width_ramp(nums)
20+
decreasing_stack = [0]
21+
for i in 1...nums.length
22+
decreasing_stack.append(i) if nums[decreasing_stack[-1]]>nums[i]
23+
end
24+
25+
max_width = 0
26+
(nums.length-1).downto(0) do |j|
27+
until decreasing_stack.empty? || nums[decreasing_stack[-1]]>nums[j]
28+
max_width = [max_width, j-decreasing_stack.pop].max
29+
end
30+
end
31+
max_width
32+
end

0 commit comments

Comments
 (0)