ETC/Algorithm

[Leetcode] 22. Container With Most Water

Pazery는ENFJ 2022. 1. 27. 21:01
반응형

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

첫 번째 풀이

  • 완전 탐색
class Solution{
    public int maxArea(int[] height){
        int heightLenth = height.length;
        int max = -1;

        for(int i=0;i<heightLenth-1;i++){
            for(int j=i+1;j<heightLenth;j++){
                int tmpHeight = Math.min(height[i], height[j]);
                int tmpWidth = j-i;
                int liter = tmpHeight * tmpWidth;
                if(max < liter){
                    max = liter;
                }
            }
        }
        return max;
    }
}

두 번째 풀이

  • 넓이의 값이 크려면 너비와 높이가 커야한다 → 양쪽 끝에서 시작을 해보자!
class Solution {
    int maxArea(int[] height){
        
    int heightLength = height.length;
    int water = -1;

    int left = 0;
    int right = heightLength - 1;

    while(left < right){
        int w_width = right - left;
        int w_height = Math.min(height[left], height[right]);
        water = Math.max(water, w_width * w_height);

        if(height[left] < height[right]){
            left++;
        } else{
            right--;
        }
    }
    return water;    
    }   
}

반응형