입력
0 1 0 2 1 0 1 3 2 1 2 1
출력
6
물을 포함한 모든 박스의 크기에서 물이 아닌 박스의 크기를 뺀다.
height = list(map(int,input().split()))
reversed_list = height[::-1]
max_height = max(height)
block = 0
for i in range(1, max_height+1):
left = height.index(i)
right = len(height) - reversed_list.index(i) - 1
block += right - left + 1
print(block-sum(height))
Time Complexity: O(n^2)
가장 높은 기둥을 기준으로 좌측과 우측 두 부분으로 나누고, 양쪽에서 가장 높은 기둥으로 각각 접근하며 물의 부피를 세어 나간다.
height = list(map(int,input().split()))
left, right = 0, len(height)-1
left_max, right_max = height[left], height[right]
volume = 0
top_index = height.index(max(height))
while left < top_index:
if height[left] > left_max:
left_max = height[left]
else:
volume += left_max - height[left]
left += 1
while top_index < right:
if height[right] > right_max:
right_max = height[right]
else:
volume += right_max - height[right]
right -= 1
print(volume)
Time Complexcity: O(n)