Leetcode - Container With Most Water
Problem,#
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.
Solution,#
Two Pointer λ‘ μ½κ² ν μ μλ€. μ§ν©μ 첫 λ²μ§Έ μμμ λ§μ§λ§ μμλ₯Ό κΈ°μ€μΌλ‘ μ‘κ³ , λ μμ μͺ½μ΄ μΈμ λ κΈ°μ€μ΄ λλ€.
class Solution {
public int maxArea(int[] height) {
int left = 0, right = height.length - 1, max = 0;
while(left < right) {
int val = Math.min(height[left], height[right]) * (right - left);
if (val > max) {
max = val;
}
if (height[left] > height[right]) {
--right;
} else {
++left;
}
}
return max;
}
}
Read other posts
COMMENTS