Post

LeetCode_11_Container With Most Water (Java, C++)

LeetCode_11_Container With Most Water (Java, C++)

11. Container With Most Water

Medium


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

문제 풀이

범위를 좁혀나가면서 최대 넓이 갱신, 투포인터 문제인 것 같다고 생각했다.

코드

Java 코드

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
import java.util.*;
import java.io.*;

class Solution {
    public int maxArea(int[] height) {
        int n = height.length;
        int left = 0;
        int right = n-1;
        int width = right-left;
        int res = 0;
        while(left < right){
            int leftH = height[left];
            int rightH = height[right];
            int minH = Math.min(leftH, rightH);
            int S = width * minH;
            res = Math.max(res, S);

            if(leftH < rightH) left++; 
            else right--;
            width--;
        }
        System.out.println(res);
        return res;
    }
}


C++ 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    int maxArea(vector<int>& height) {
        int n, left, right, width, res;
        n = height.size();
        left = 0;
        right = n-1;
        width = right-left;
        res =0;
        while(left<right){
            int leftH = height[left];
            int rightH = height[right];
            int minH = min(leftH, rightH);
            int S = width * minH;
            res = max(res, S);

            if(leftH < rightH) left++; 
            else right--;
            width--;
        }
        return res;
    }
};

This post is licensed under CC BY 4.0 by the author.