2024. 3. 18. 20:47ㆍTech: Algorithm
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.
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
Constraints:
- n == height.length
- 2 <= n <= 10^5
- 0 <= height[i] <= 10^4
Solution
단순하게는 앞에서부터 보면서 index 두 조합 중 min(idx_1.val, idx_2.val)*(idx_2-idx_1) 의 최댓값을 찾으면 될 것같은데 이러면 O(n^2)이라..당연히 Timit limit exceeded...
idx.val이 크면서 먼 것을 찾아야하는데 그렇다면 idx 앞left에서 부터/뒤right에서부터 곱해보는건?
여기서 중요한 점은 idx.val 이 left/right 중 큰 곳을 그대로 두고 작은쪽을 이동 시켜야한 다는 점 ( 왜냐면, 어차피 작은 쪽을 이동시키는 건 무의미하니까)
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int right= height.size()-1;
int max_water=0;
while(left < right)
{
int water = min(height[left], height[right])*(right-left);
if(water>max_water) max_water = water;
if(height[left]<height[right]){
left++;
}
else{
right--;
}
}
return max_water;
}
};
대신 이렇게 했더니 시간은 73ms정도... 좋은 편은 아니었다
코드를 줄이고 싶다면 아래처럼 활용할 수는 있을듯..
ans = max(ans, (j - i) * min(height[i], height[j]));
height[i] > height[j] ? j-- : i++;
'Tech: Algorithm' 카테고리의 다른 글
[Leetcode] 10. Regular Expression Matching (0) | 2024.03.13 |
---|---|
[Leetcode] 9. Palindrome Number (0) | 2024.03.12 |
[Leetcode] 8. String to Integer (atoi) (0) | 2024.03.12 |
[Leetcode] 7. Reverse Integer (0) | 2024.03.11 |
[Leetcode] 6. Zigzag Conversion (0) | 2024.03.08 |