Home LeetCode - 11. Container With Most Water
Post
Cancel

LeetCode - 11. Container With Most Water

11. Container With Most Water - Medium

문제

Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.

Notice that you may not slant the container.

제한사항

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

입출력 예

example

1
2
3
4
5
Examples 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.
1
2
3
4
Example 2:

Input: height = [1,1]
Output: 1
1
2
3
4
Example 3:

Input: height = [4,3,2,1,4]
Output: 16
1
2
3
4
Example 4:

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

풀이

  • Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
    int maxArea(vector<int>& height) {
        int result = 0;
        int i = 0;
        int j = height.size() - 1;
        
        // 담을수 있는 물의 양의 높이를 결정하는건
        // 두 막대중 낮은 막대의 길이로 결정된다.
        // 즉, 두 막대 사이에 둘중 낮은 막대의 양만큼 물을 채울수 있으므로,
        // 담을수 있는 물의 양은 min * (j - i) 가 된다.
        while (i != j) {
            int min = std::min(height[i], height[j]);
            result = std::max(result, min * (j - i));
            
            // 두 막대중 더 높은 막대일수록 더 많은 물을
            // 담을수 있기 때문에 두 막대중 낮은 길이의 막대의
            // 인덱스를 변경한다.
            if (height[i] == min) {
                ++i;
            } else {
                --j;
            }
        }
        
        return result;
    }
};
This post is licensed under CC BY 4.0 by the author.