Game Tech Blog

11. Container With Most Water 본문

Algorithm/LeetCode

11. Container With Most Water

jonghow 2023. 7. 24. 01:32
반응형

[문제]

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.

 

[TC]

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

[접근]

접근은 투포인터 형태로 접근, 인덱스는 Start, End 에 세팅한 후, Start 에서는 오른쪽으로, End 에서는 왼쪽으로 밀어가면서 인덱스를 이동시키고, 각 인덱스 위치에 있을때 value 로 사각형의 넓이를 연산 후, 가장 큰 경우 output 도출

 

핵심은 가장 큰 value 를 기준으로 인덱스를 왼쪽으로 댕길지, 오른쪽으로 밀지 판단하여 로직을 작성

 

[코드] - C++

class Solution {
public:
    int maxArea(vector<int>& height) {

        int output = 0;

        int l = 0;
        int r = height.size() - 1;

        while (l < (height.size()) )
        {
            int heightValue = min(height[l], height[r]);
            int calc = (abs(r - l)) * heightValue;

            if (output < calc)
                output = calc;

            if (height[l] > height[r])
                --r;
            else
                ++l;
        }

        return output;
    }
};

 

[결과]

 

[시도]

 

[후기]

맨 초기 방식은 start , end 를 양쪽 끝 인덱스에 세팅하고, 무조건 모든 케이스를 순회하는 방향으로 작성했는데 당연히 TimeLimit 이 떠버렸다. 이후에 힌트를 보고 사각형에서 가장 1순위로 크게 잡을 수 있는 Value 를 기준으로 인덱스를 조정하여 최적화를 시킨 결과 어셉이떴다.

 

원리랄것도 없지만 문제 이해가 가장 중요한 문제였다.

반응형

'Algorithm > LeetCode' 카테고리의 다른 글

283. Move Zeroes  (0) 2023.07.25
1679. Max Number of K-Sum Pairs  (0) 2023.07.25
392. Is Subsequence  (0) 2023.07.20
443. String Compression  (0) 2023.07.18
334. Increasing Triplet Subsequence  (2) 2023.07.17
Comments