JAVA Easy Understand Solution L to R and R to L


  • 0
    Y
    public class Solution {
        public int trap(int[] height) {
            int left = 0;
            int right = 1;
            int curW = 0;
            int res = 0;
            while(right < height.length){
                if(height[right] >= height[left]){
                    res += curW;
                    left = right++;
                    curW = 0;
                }else{
                    curW += height[left] - height[right++];
                }
            }
            if(curW > 0){
                curW = 0;
                int limit = left;
                left = --right;
                while(right > limit){
                    if(height[left] >= height[right]){
                        res += curW;
                        right = left--;
                        curW = 0;
                    }else{
                        curW += height[right] - height[left--];
                    }
                }
            }
            return res;
        }
    }

Log in to reply
 

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