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.
최대로 채울 수 있는 물의 양을 구하기
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
Example 3:
Input: height = [4,3,2,1,4] Output: 16
Example 4:
Input: height = [1,2,1] Output: 2
Constraints:
- 2 <= height.length <= 3 * 104
- 0 <= height[i] <= 3 * 104
풀이:
- 백준의 나무 문제와 유사하게 생겼다. 어렵지 않게 투포인터로 푸는 것으로 예측할 수 있다.
- 두 막대기 중 작은 막대기에 따라 물의 양이 정해지므로 현재 위치에서 더 작은 막대기를 바꾼다.
class Solution {
public:
int maxArea(vector<int>& height) {
int start = 0, end = height.size()-1;
int minLen = 30000 + 1;
int maxWid = 0;
while(start<end){
minLen = min(height[start], height[end]);
maxWid = max(maxWid, minLen * (end-start));
if(height[start] < height[end]){
start++;
}else{
end--;
}
}
return maxWid;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 17] Letter Combinations of a Phone Number (0) | 2020.10.14 |
---|---|
[leetcode 15] 3Sum (0) | 2020.10.14 |
[leetcode 5] Longest Palindromic Substring (0) | 2020.10.13 |
[leetcode 3] Longest Substring Without Repeating Characters (0) | 2020.10.13 |
[leetcode 2] Add Two Numbers (0) | 2020.10.13 |
댓글