LeetCode 11. Container With Most Water

Description

https://leetcode.com/problems/container-with-most-water/

Given n non-negative integers a1a2, …, a, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

Explanation

First, draw an x, y-axis picture to convert text information.

Then generalize ideas from the picture.

The container is a rectangle. So the amount of the water is determined by the width and height. The container’s width is right – left and height is the minimum value between left line height and right line height.

Java Solution

class Solution {
    public int maxArea(int[] height) {
        int maxArea = 0;
        
        if (height == null) {
            return maxArea;
        }
        
        int left = 0;
        int right = height.length - 1;
        
        while (left < right) {
            int area = (right - left) * Math.min(height[left], height[right]);
            maxArea = Math.max(maxArea, area);
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
               
        return maxArea;
    }
}

Python Solution

class Solution:
    def maxArea(self, height: List[int]) -> int:        
        max_area = 0
        
        i = 0
        j = len(height) - 1
        
        while i < j:            
            area_width = j - i
            area_height = min(height[i], height[j])
            
            area = area_width * area_height
            
            max_area = max(max_area, area)
        
            if height[i] < height[j]:                
                i += 1
            else:
                j -= 1
                        
        return max_area
  • Time Complexity: ~N
  • Space Complexity: ~1

Leave a Reply

Your email address will not be published. Required fields are marked *