fork download
  1. #include <stdio.h>
  2.  
  3. int main(void) {
  4. int ar[10000];
  5. int n=0;
  6. //input all values
  7. while(scanf("%d",&ar[n++])==1);
  8. int l=0,h=n-1,ans=0,LMax=0,RMax=0;
  9. //l is the left index
  10. // h is the right index
  11. //LMax is the maximum of all the heights up to and including that point and
  12. //RMax is the maximum of heights from that point onward
  13. while(l<h){
  14. //find out the smaller one out of left and right index
  15. if(ar[l]<ar[h]){
  16. if(ar[l]>LMax){
  17. LMax=ar[l];
  18. }
  19. else{
  20. //The smaller of LMax and RMax minus the height at that point is the water amount.
  21. ans+=(LMax-ar[l]);
  22. }
  23. l++;
  24. }
  25. else{
  26. //symetrically opposite code for the right side
  27. if(ar[h]>RMax){
  28. RMax=ar[h];
  29. }
  30. else{
  31. ans+=(RMax-ar[h]);
  32. }
  33. h--;
  34. }
  35. }
  36. printf("%d\n",ans);
  37. return 0;
  38. }
Success #stdin #stdout 0s 4532KB
stdin
4 2 4 1 5 3 16 6 17 19 4 13 5 3 10 10 13 6 2 1 5 15 13 19 16 9 13 1 7 18 20 13 9 7 2 10 8 18 4 7 5 8 10 13 7 18 19 2 19 8 10 10 17 6 6 20 20 11 10 11 13 9 7 1 10 5 12 16 10 7 15 13 12 10 1 1 4 2 16 10 20 17 11 19 19 20 9 10 17 9 18 8 10 18 8 19 16 17 3 1
stdout
791