|
1 | 1 | package s0011_container_with_most_water |
2 | 2 |
|
3 | 3 | class Solution { |
4 | | - fun maxArea(height:IntArray):Int { |
5 | | - var max = 0 |
6 | | - if (height != null && height.size != 0) |
7 | | - { |
8 | | - var left = 0 |
9 | | - var right = height.size - 1 |
10 | | - while (left < right) |
11 | | - { |
12 | | - // next two if conditions are to make sure there are two non-zero containers to |
13 | | - // hold water. If not move next to find one |
14 | | - if (height[left] == 0) |
15 | | - { |
16 | | - left++ |
17 | | - continue |
| 4 | + fun maxArea(height: IntArray): Int { |
| 5 | + var max = 0 |
| 6 | + if (height.isNotEmpty()) { |
| 7 | + var left = 0 |
| 8 | + var right = height.size - 1 |
| 9 | + while (left < right) { |
| 10 | + // next two if conditions are to make sure there are two non-zero containers to |
| 11 | + // hold water. If not move next to find one |
| 12 | + if (height[left] == 0) { |
| 13 | + left++ |
| 14 | + continue |
| 15 | + } |
| 16 | + if (height[right] == 0) { |
| 17 | + right-- |
| 18 | + continue |
| 19 | + } |
| 20 | + // if control came here that means left and right containers are non zero and |
| 21 | + // can hold water. Get the count of containers and multiple by lower container |
| 22 | + if (height[left] < height[right]) { |
| 23 | + max = Math.max(max, (right - left) * height[left]) |
| 24 | + left++ |
| 25 | + } else { |
| 26 | + max = Math.max(max, (right - left) * height[right]) |
| 27 | + right-- |
| 28 | + } |
| 29 | + } |
18 | 30 | } |
19 | | - if (height[right] == 0) |
20 | | - { |
21 | | - right-- |
22 | | - continue |
23 | | - } |
24 | | - // if control came here that means left and right containers are non zero and |
25 | | - // can hold water. Get the count of containers and multiple by lower container |
26 | | - if (height[left] < height[right]) |
27 | | - { |
28 | | - max = Math.max(max, (right - left) * height[left]) |
29 | | - left++ |
30 | | - } |
31 | | - else |
32 | | - { |
33 | | - max = Math.max(max, (right - left) * height[right]) |
34 | | - right-- |
35 | | - } |
36 | | - } |
| 31 | + return max |
37 | 32 | } |
38 | | - return max |
39 | | - } |
40 | 33 | } |
0 commit comments