[LeetCode] 11. Container With Most Water (Java)

2023. 1. 4. 07:08알고리즘/LeetCode

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

class Solution {
    public int maxArea(int[] height) {
        int max = 0;
        int temp = 0;
        
        for(int i=0;i<height.length;i++){
            for(int j=i+1;j<height.length;j++){
                temp = (j-i)*Math.min(height[i],height[j]);
                max = Math.max(temp,max);
            }
        }
        
        return max;
    }
}

첫번째로는 이중for문을 사용하여 가장 직관적인 방법을 사용했다. 풀이에는 문제가 없었지만 이중for문으로 인하여 계산 시간이 오래걸려서 매우 긴 문제에 대해서는 오류가 발생하였다.

 

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

두번째로는 반복문을 하나만 사용하여 시간복잡도를 줄였다. 양쪽 가장 끝에서 시작하여 수가 더 작은 방향에서 반대쪽으로 이동하도록 하였다.

ex) [3, 5, 6, 4, 1] 이라면 

1. 3과 1이 나타내는 면적을 구하기

2. 3과 4가 나타내는 면적을 구하기

3. 5와 4가 나타내는 면적을 구하기 ... 양쪽 면적이 같다면 동시에 이동하기