Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 트리(Tree)
- 백준 18352번
- 스택(Stack)
- 위상 정렬(Topological Sort)
- 백준 1707번
- BFS
- DFS
- 큐(Queue)
- 백준 1948번
- 백준 2261번
- 동적 프로그래밍(Dynamic Programming)
- 분할 정복(Divide and Conquer)
- 그래프(Graph)
- 백준 17608번
- 다익스트라 알고리즘(Dijkstra Algorithm)
- 위상 정렬(Topology Sort)
- 백준 21606번
- 백준 2812번
- 플로이드 워셜 알고리즘(Floyd-Warshall Algorithm)
- 백준 2493번
- 백준 10000번
- 백준 2504번
- BFS(Breadth First Search)
- 백준 9012번
- DFS(Depth First Search)
- 그리디 알고리즘(Greedy Algorithm)
- 알고리즘 개념
- 이분 탐색(Binary Search)
- DFS & BFS
- 이분 그래프(Bipartite Graph)
Archives
- Today
- Total
Always Be Wise
배열 : 빗물 트래핑(리트코드 42번) 본문
728x90
▶ 문제 : https://leetcode.com/problems/trapping-rain-water/
Trapping Rain 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
##### 문제 #####
높이를 입력받아 비 온 후 얼마나 많은 물이 쌓일 수 있는지 계산하라.
##### 입력 #####
height = [0,1,0,2,1,0,1,3,2,1,2,1]
##### 출력 #####
6
▶ 접근 방법
height 리스트에서 가장 큰 값은 3이다.
가장 큰 값까지 각각 좌우 최대 높이에서 현재 높이와 차이가 나는 만큼을 더해준다.
좌우 어느 쪽이든 낮은 쪽은 높은 쪽을 향해서 포인터를 가운데 방향으로 점점 옮긴다.
가장 큰 값인 3 지점에서 좌우 포인터가 서로 만나면 값을 리턴한다.
▶ 풀이 코드
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
def trap(height: list) -> int:
if not height:
return 0
volume = 0
left, right = 0, len(height) - 1
left_max, right_max = height[left], height[right]
while left < right :
left_max, right_max = max(height[left], left_max), max(height[right], right_max)
if left_max <= right_max:
volume += left_max - height[left]
left += 1
else :
volume += right_max - height[right]
right -= 1
return volume
print(trap(height))
'알고리즘 > 리트코드' 카테고리의 다른 글
배열 : 주식을 사고 팔기 가장 좋은 시점(리트코드 121번) (0) | 2022.01.31 |
---|---|
배열 : 세 수의 합(리트코드 15번) (0) | 2022.01.30 |
배열 : 두 수의 합(리트코드 1번) (0) | 2021.12.15 |
문자열 조작 : 가장 긴 팰린드롬 부분 문자열(리트코드 5번) (0) | 2021.12.14 |
문자열 조작 : 그룹 애너그램(리트코드 49번) (0) | 2021.12.14 |
Comments