Easy Java code 12 lines


  • 0
    public class Solution {
        public int trap(int[] height) {
            if(height.length == 0) return 0;   
            int sum = 0;
            Stack<Integer> stack = new Stack<Integer>(); // index
            stack.push(0);
            for(int i = 1; i < height.length; i++){
                int curr = height[i];
                while(!stack.isEmpty() && curr > height[stack.peek()]){
                    int h = height[stack.pop()];
                    if(!stack.isEmpty())
                        sum += (Math.min(curr, height[stack.peek()]) - h) * (i - stack.peek() - 1);
                }
                stack.push(i);
            }
            return sum;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.