본문으로 바로가기

Description

각 배열에 주어진 높이와 거리에서 가장 넓은 면적으로 계산되는 위치를 반환하는 문제입니다.

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.

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: 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 2:

Input: height = [1,1]
Output: 1

Constraints:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

Solution 1. Two Pointers

public int maxArea(int[] height) {
        
    int maxArea = 0;
    int left = 0;
    int right = height.length-1;

    while(left<right){
        int minHeight = Math.min(height[left],height[right]);
        int distance = right-left;
        //더 작은곳의 포인터를 한칸 옮김
        if(height[left]<height[right]){
            left++;
        }else{
            right--;
        }
        maxArea = Math.max(maxArea,minHeight*distance);
    }
    return maxArea;
}

가장 길이가 긴 양끝에 포인터를 두고 현재 위치에서의 넓이를 계산한뒤 둘중에 높이가 작은 곳의 포인터를 한쪽 옮겨서 최대값을 계산해 나갑니다.

Reference

 

Container With Most Water - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com