Share my simple java solution


  • 2
    P
    public int trap(int[] height) {
            int start = 0, end = height.length - 1;
            int startMax = 0, endMax = 0;
            int res = 0;
            while (start < end) {
                startMax = Math.max(height[start], startMax);
                endMax = Math.max(height[end], endMax);
                if (startMax < endMax) {
                    res += (startMax - height[start++]);
                } else {
                    res += (endMax - height[end--]);
                }
            }
            return res;
        }
    

  • 0
    J

    Simple and wonderful. I love this solution. Thanks @proron .


Log in to reply
 

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