Skip to content

Commit 92b952f

Browse files
committed
leetcode-962 Maximum width ramp sliding window
1 parent 814d4e8 commit 92b952f

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

leetcode/maximum_width_ramp.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,26 @@ def max_width_ramp(nums)
2929
end
3030
end
3131
max_width
32+
end
33+
34+
#Solution 2 (using two pointer with preprocessing)
35+
# @param {Integer[]} nums
36+
# @return {Integer}
37+
def max_width_ramp(nums)
38+
len = nums.length
39+
max_to_the_right = [0]*len
40+
max_to_the_right[-1] = nums[-1]
41+
(len-2).downto(0) do |i|
42+
max = max_to_the_right[i+1]<nums[i] ? nums[i] : max_to_the_right[i+1]
43+
max_to_the_right[i] = max
44+
end
45+
max_width = 0
46+
left=0
47+
for right in 0...len
48+
while max_to_the_right[right]<nums[left]
49+
left+=1
50+
end
51+
max_width = [max_width, right-left].max
52+
end
53+
max_width
3254
end

0 commit comments

Comments
 (0)