C Program to implement the solution of RainWater Trapping Problem - LeetCode

 


// Program by Akash Tripathi (@proakash256) 
 
// Given an Array of the height of buildings.
// Find how much units of water can be trapped
// in between those buildings.

#include <stdio.h>
#include <math.h>
int main()
{
    int n;
    printf("Enter the number of elements : ");
    scanf("%d", &n);
    int ar[n];
    printf("\nEnter the elements :\n");
    for (int i = 0i < ni = i + 1)
        scanf("%d", &ar[i]);

    // Making Auxillary Arrays (Left and Right)
    int left[n];
    left[0] = ar[0];
    for(int i = 1i < ni = i + 1)
    {
        if(left[i - 1] > ar[i])
            left[i] = left[i - 1];
        else
            left[i] = ar[i];
    }
    int right[n];
    right[n - 1] = ar[n - 1];
    for(int i = (n - 2); i >= 0i = i - 1)
    {
        if(right[i + 1] > ar[i])
            right[i] = right[i + 1];
        else
            right[i] = ar[i];
    }
    int water = 0;
    for(int i = 0i < ni = i + 1)
    {
        if(left[i] < right[i])
        {
            water += (left[i] - ar[i]);
        }
        else
        {
            water += (right[i] - ar[i]);
        }
    }
    printf("Water trapped is %d Units." , water);
    return 0;
}

Comments