Wednesday, 16 December 2015

#LeetCode# Trapping Rain Water C++/C solution

#LeetCode#  Trapping Rain Water. C/C++ solution

class Solution {

public:

    int fun(vector<int>& height,int i,int j,int mx){

        int ans=0;

        if((mx+1)!=i){

                if(height[mx]==height[i]){             //if left and right bars are equal

                    ans=(height[mx]-height[mx+1])*(i-j-1);   //calculate the area

                    int h=(height[mx]-height[mx+1]);

                    for(j=mx+1;j<i;j++){

                     height[j]=height[j]+h;  //update the heights of each bar in between for upcomming calculations

                    }

                }

                else if(height[mx]<height[i]){  //if left bar is less than right bar

                     ans=(height[mx]-height[mx+1])*(i-j-1); //calculate area

                     int h=(height[mx]-height[mx+1]);

                    for(j=mx+1;j<i;j++)

                     height[j]=height[j]+h;  //update the heights

                }

                else{

                    ans=(height[i]-height[i-1])*(i-j-1); //if left bar is greater than right bar

                    int h=(height[i]-height[i-1]);

                    for(j=mx+1;j<i;j++)

                     height[j]=height[j]+h;  //do the same as above

                }

        }

        return ans;

    }

    int trap(vector<int>& height) {

        int n=height.size(),i,j;

        if(n==0 || n==1 || n==2)

         return 0;

        i=0;

        int ans=0;

        while(height[i]==0)

         i++;

        for(i=i+1;i<n;i++){

            if(height[i]<=height[i-1]){  //if adjacent bars have equal heights no water can be stored so check for next

                continue;

            }

            else

            {

                j=i-1;

                int mx=j;

                while(j>=0){

                    if(height[j]>=height[i])  //if left bar has height equal to right bar

                     {

                         mx=j;

                         ans+=fun(height,i,j,mx); //calculate area and update height

                         break;

                     }

                     else if(height[j]>height[j+1])  //do the same if left has greater height

                     {

                          mx=j;

                          ans+=fun(height,i,j,mx);

                     } //if left bar has less area then no water can be stored

                     j--;

                }

            }

        }

        return ans;

    }

};

No comments:

Post a Comment