Friday, October 26, 2018

How will you trap rain water?

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



Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Input: [3, 0, 0, 2, 0, 4]
Output: 10

#include<stdio.h>
calculate(int a[], int n)
{
 int f = a[0];
 int fi = 0;
 int sum = 0;
 for(int i=0; i<n; i++) {
  int next = getNextGENumber(a, a[i], i, n);
  if(next != -1) {
   for(int j=i+1; j<next; j++) {
    sum += (a[i]-a[j]);
   }
   i = next - 1;
  } 
 }
 return sum;
}

int getNextGENumber(int a[], int value, int start, int n)
{
 for(int i=start+1; i<n; i++) {
  if(value <= a[i]) {
   return i;
  }
 }
 return -1;
}

main()
{
 int n;
 int a[1000];
 printf("Enter number of blocks: ");
 scanf("%d", &n);
 printf("Enter the blocks\n");
 for(int i=0; i<n && i<1000; i++) {
  scanf("%d", a+i);
 }
 printf("%d\n", calculate(a, n));
}



No comments:

Post a Comment