- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0011-container-with-most-water.rb
86 lines (66 loc) · 1.94 KB
/
0011-container-with-most-water.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# frozen_string_literal: true
# 11. Container With Most Water
# https://leetcode.com/problems/container-with-most-water/
# Medium
=begin
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
### Constraints:
* n == height.length
* 2 <= n <= 105
* 0 <= height[i] <= 104
=end
# @param {Integer[]} height
# @return {Integer}
defmax_area1(height)
max_area=0
left,right=0,height.size - 1
whileleft < right
min_h=[height[left],height[right]].min
max_area=[max_area,min_h * (right - left)].max
ifheight[left] < height[right]
left += 1
else
right -= 1
end
end
max_area
end
# @param {Integer[]} height
# @return {Integer}
defmax_area2(height)
max_area=0
height.size.timesdo |i|
(i + 1..height.size - 1).eachdo |j|
min_h=[height[i],height[j]].min
max_area=[max_area,min_h * (j - i)].max
end
end
max_area
end
# **************** #
# TEST #
# **************** #
require"test/unit"
classTest_max_area < Test::Unit::TestCase
deftest_
assert_equal49,max_area1([1,8,6,2,5,4,8,3,7])
assert_equal1,max_area1([1,1])
assert_equal49,max_area2([1,8,6,2,5,4,8,3,7])
assert_equal1,max_area2([1,1])
end
end
# ********************#
# Benchmark #
# ********************#
require"benchmark"
height=[1,8,6,2,5,4,8,3,7]
Benchmark.bmdo |x|
x.report("max_area1: "){max_area1(height)}
x.report("max_area2: "){max_area2(height)}
end
# user system total real
# max_area1: 0.000019 0.000004 0.000023 ( 0.000018)
# max_area2: 0.000025 0.000000 0.000025 ( 0.000025)