C# solution: left & right shrink, sealevel increases


  • 0
    B
    public class Solution 
    {
        public int Trap(int[] height) 
        {
            var left = 0;
            var right = height.Length - 1;
    
            var result = 0;
    
            var seaLevel = 0;
    
            while(left < right)
            {
                var leftHeight = height[left];
                var rightHeight = height[right];
    
                if (leftHeight < seaLevel)
                {
                    result += seaLevel - leftHeight;
                }
    
                if (rightHeight < seaLevel)
                {
                    result += seaLevel - rightHeight;
                }
    
                seaLevel = Math.Max(seaLevel, Math.Min(leftHeight, rightHeight));
    
                if (leftHeight < rightHeight)
                {
                    left++;
                }
                else
                {
                    right--;
                }
            }
    
            return result;
        }
    }
    

Log in to reply
 

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