# 08. 빗물 트래핑

[**문제링크**](https://leetcode.com/problems/trapping-rain-water)

## 문제 분석

기둥 사이에 물이 차기 위해서는 양옆이 높아야된다는 조건이 있다. 이 조건을 생각하면 의외로 쉽게 문제를 해결할 수 있다.&#x20;

투포인터 기법을 사용해서 왼쪽, 오른쪽 포인터를 만든다. 그리고 양 옆의 최대값을 비교하면서 포인터를 움직이면 된다.

오른쪽의 최대값이 왼쪽보다 크다면, 왼쪽은 오른쪽으로 이동하면서 물의 양을 셀 수가 있는데 이게 가능한 이유는 오른쪽 기둥의 높이는 언제나 왼쪽보다 높다는게 보장이 되기 때문에 기둥 사이에 공간이 마련될 수 있기 때문이다.     &#x20;

## 해결

{% tabs %}
{% tab title="JavaScript" %}

```javascript
var trap = function(height) {
    let left = 0;
    let right = height.length - 1;
    let lMax = height[left];
    let rMax = height[right];
    vol = 0;
    while (left < right) {
        lMax = Math.max(lMax, height[left])
        rMax = Math.max(rMax, height[right])
        if (lMax <= rMax) {
            vol += lMax - height[left]
            left += 1;
        } else {
            vol += rMax - height[right]
            right -= 1;
        }
    }
    return vol
};
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://simian114.gitbook.io/blog/undefined/undefined-1/08..md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
