My very simple java solution!


  • 1
    L

    It is very easy to understand!

    public class Solution {
        public int trap(int[] height) {
            if(height == null || height.length <= 2) return 0;
            
            int sum = 0, maxhigh = 0;
            int begin = 0, end = height.length-1;
            while(begin <= end){
                if(height[begin] <= maxhigh){
                    sum += maxhigh - height[begin++];
                }
                else if(height[end] <= maxhigh){
                    sum += maxhigh - height[end--];
                }
                else{
                    maxhigh = Math.min(height[begin], height[end]);
                }
            }
            return sum;
        }
    }
    

  • 0

    Why is the maxHigh in the else clause set to

    Math.min(height[begin], height[end])
    

    I thought we are trying to find the local maximum for element in the current index! am I right ?


Log in to reply
 

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