AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Friday 13 January 2023

DSA problem solution: Trapping Rain Water



Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]

Output: 6

Example 2:

Input: height = [4,2,0,3,2,5]

Output: 9

Solution:

public class Solution {
    public int Trap(int[] height) {
        int[] leftheight = new int[height.Length];
        int[] rightheight = new int[height.Length];        
        int maxleftheight=0;
        int maxrightheight=0;
        int trappedwater =0; 

        for(int i=0;i<height.Length;i++)
        {
            if(i>0)
            {
               if(height[i-1]>maxleftheight)
               {
                  maxleftheight = height[i-1];       
               }
            }

            leftheight[i] = maxleftheight;
        }

         for(int i=height.Length-1;i>=0;i--)
         {
            if(i<(height.Length-1))
            {
               if(height[i+1]>maxrightheight)
               {
                  maxrightheight = height[i+1];       
               }
            }
            rightheight[i] = maxrightheight;           
         }

        for(int i=0;i<height.Length;i++)
        {
          int minlevel = Math.Min(rightheight[i],leftheight[i]);
          Console.WriteLine("Index:"+i+ " Left:"+leftheight[i]+" Right:"+rightheight[i]);
          if(minlevel>height[i]){
              trappedwater+= (minlevel-height[i]);
          }
        }
        
        return trappedwater;
    }
}

0 comments :

Post a Comment

  • Popular Posts
  • Comments