Algorithm 🧑🏻💻/Leetcode
[Leetcode,c++] Container With Most Water
dkswnkk
2021. 11. 14. 18:08
문제
Container With Most Water - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
코드
class Solution {
public:
int maxArea(vector<int>& height) {
int start = 0;
int end = height.size()-1;
int ans = -1;
while(start<=end){
int x = end-start;
int y = min(height[start],height[end]);
ans = max(ans,x*y);
if(height[start]<height[end]) start++;
else end--;
}
return ans;
}
};
풀이
투 포인터를 활용하여 시간 복잡도 O(N)로 해결한 풀이입니다.
배열의 처음과 끝을 비교하는데 둘중 작은 쪽을 다음 인덱스로 넘기는 방식으로 구현했습니다.