Accepted Java solution


  • 0
    A

    Feedback welcome!

    public class Solution {
        public int trap(int[] height) {
            int[] fwd = new int[height.length];
            int prev = 0;
            for (int i = 0; i < fwd.length; i++) {
                if (prev != 0 && height[i] < prev) {
                    fwd[i] = prev;
                }
                prev = Math.max(prev,height[i]);
            }
            prev = 0;
            int sum = 0;
            for (int i = height.length-1; i >= 0; i--) {
                if (prev != 0 && fwd[i] != 0 && height[i] < Math.min(prev,fwd[i])) {
                    sum += Math.min(fwd[i],prev) - height[i];
                }
                prev = Math.max(prev,height[i]);
            }
            
            return sum;
        }
    }

Log in to reply
 

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