본문 바로가기
LeetCode

[LeetCode] 11. Container With Most Water

by JungSeung 2023. 10. 18.
728x90

https://leetcode.com/

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the i^th 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:

출처 : https://leetcode.com/problems/container-with-most-water/description/

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 <= 10^5
  • 0 <= height[i] <= 10^4

 

Code :

/*
	1. 초기에 최대 용량을 나타내는 변수 max를 0으로 설정합니다.
	2. 두 개의 포인터 start와 last를 사용하여 배열의 양 끝을 가리킵니다.
	3. last와 start의 차이가 0보다 큰 동안 반복합니다.
	4. 현재의 최소 높이를 찾고, 이를 기준으로 컨테이너의 용량을 계산합니다.
	5. 더 작은 높이를 가진 포인터를 이동시킵니다.
	6. 계산된 용량이 기존의 최대 용량보다 크다면, 최대 용량을 갱신합니다.
*/
var maxArea = function(height) {
    let max = 0;
    let start = 0;
    let last = height.length - 1;
    
    while (last - start > 0) {
        const standard = height[last] > height[start] ? height[start] : height[last];
        const gap = (last - start) * standard;
              
        height[last] > height[start] ? start++ : last--;
        max = max < gap ? gap : max;
    }
    return max;
};

 

Solutions Code :

/*
	1. 주어진 배열의 길이를 n에 할당하고, 두 포인터 left와 right를 초기화합니다.
	2. 초기 최대 용량을 나타내는 변수 max_area를 0으로 설정합니다.
	3. left가 right보다 작은 동안 반복합니다.
	4. 현재의 최소 높이를 찾고, 이를 기준으로 컨테이너의 용량을 계산합니다.
	5. 계산된 용량이 기존의 최대 용량보다 크다면, 최대 용량을 갱신합니다.
	6. 왼쪽 높이가 오른쪽 높이보다 작은 경우 left를 증가시키고, 그렇지 않은 경우에는 right를 감소시킵니다.
*/
var maxArea = function(height) {
    let n = height.length;
    let left = 0, right = n - 1;
    let max_area = 0;
    while (left < right) {
        let area = Math.min(height[left], height[right]) * (right - left);
        max_area = Math.max(max_area, area);
        if (height[left] < height[right]) {
            left++;
        } else {
            right--;
        }
    }
    return max_area;
}

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 13. Roman to Integer  (2) 2023.10.19
[LeetCode] 12. Integer to Roman  (0) 2023.10.19
[LeetCode] 10. Regular Expression Matching  (0) 2023.10.18
[LeetCode] 9. Palindrome Number  (0) 2023.10.17
[LeetCode] 8. String to Integer (atoi)  (2) 2023.10.16