코딩테스트 풀이/JAVA
[LeetCode/Medium] 11. Container With Most Water
무지맘
2023. 7. 6. 00:58
1. Input
1) int[] height
- height[i] == i번째 위치의 벽의 높이
- 벽의 간격과 두께는 모두 1이다.
2. Output
1) 두 벽을 골라 물을 채울 때 가장 많이 채울 수 있는 물의 양을 반환
3. Constraint
1) n == height.length
2) 2 <= n <= 10^5
3) 0 <= height[i] <= 10^4
4. Example
Input: height = [1,8,6,2,5,4,8,3,7] -> Output: 49(=7*7)
설명: 빨간 벽을 골랐을 때가 가장 물이 많이 담긴다.
5. Code
class Solution {
public int maxArea(int[] height) {
int left = 0, right = height.length-1, max = 0;
while(left<right){
int v = (right-left)*Math.min(height[left],height[right]);
if(v>max) max = v;
if(height[left]<height[right]) left++;
else right--;
}
return max;
}
}
- 83%, 62%