classSolution://Shortest barrel deftrap(self, height): """ :type height: List[int] :rtype: int """ res, hei_len = 0, len(height) for i in range(1, hei_len-1): max_left, max_right = 0, 0 for l in range(i+1): max_left = max(max_left, height[l]) for r in range(i, hei_len): max_right = max(max_right, height[r]) res += min(max_left, max_right) - height[i] return res
classSolution{ publicinttrap(int[] height){ if (height.length == 0 || height.length == 1) { return0; } int maxHeight = Integer.MIN_VALUE; int index = 0; for (int i = 0; i < height.length; i++) { if (height[i] > maxHeight) { maxHeight = height[i]; index = i; } }
int result = 0, currentMax = Integer.MIN_VALUE;
for (int i = 0; i < index; i++) { if (currentMax >= height[i]) { result += currentMax - height[i]; } else { currentMax = height[i]; } } currentMax = Integer.MIN_VALUE; for (int i = height.length - 1; i > index; i--) { if (currentMax >= height[i]) { result += currentMax - height[i]; } else { currentMax = height[i]; } } return result; }