Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
classSolution: defmaxArea(self, height: List[int]) -> int: left, right = 0, len(height) - 1 result = 0 while left < right: now = min(height[left], height[right])*(right-left) result = max(result, now) if height[left] <= height[right]: left += 1 else: right -= 1 return result
解决方案2(Java)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution{ publicintmaxArea(int[] height){ int result = 0, l = 0, r = height.length - 1; while (l < r) { result = Math.max(result, Math.min(height[l], height[r]) * (r-l)); if (height[l] < height[r]) { l++; } else { r--; } } return result; } }
解决方案3(Javascript)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/** * @param {number[]}height * @return {number} */ var maxArea = function(height) { var result = 0; var l = 0; var r = height.length - 1; while (l <= r) { result = Math.max(result, Math.min(height[l], height[r]) * (r-l)); if (height[l] < height[r]) { l++; } else { r--; } } return result; };
impl Solution { pub fn max_area(height: Vec<i32>) -> i32 { let (mut l, mut r) = (0_usize, (height.len() - 1)); let mut result: i32 = (r - l) as i32 * Solution::min(height[l], height[r]); let mut current: i32 = 0; while l < r { if height[l] < height[r] { l += 1; } else { r -= 1; } current = (r - l) as i32 * Solution::min(height[l], height[r]); if current > result { result = current } } result }
#[inline(always)] fn min(i: i32, j: i32) -> i32 { if i > j { j } else { i } } }