fork download
  1. //trapped rainwater problem with Stack
  2.  
  3. import java.io.*;
  4. import java.util.*;
  5.  
  6. class Main {
  7. public static void main(String[] args)throws IOException {
  8. int n=Integer.parseInt(br.readLine());
  9. int[] arr=new int[n];
  10. for(int i=0;i<n;i++){
  11. arr[i]=Integer.parseInt(br.readLine());
  12. }
  13. int total=0;
  14. Stack<Integer> st=new Stack<>();
  15. for(int i=0;i<n;i++){
  16.  
  17. while(!st.isEmpty()&&arr[st.peek()]<arr[i]){
  18. int pop_height=arr[st.pop()];
  19. if(st.isEmpty()) break;
  20. int distance=i-st.peek()-1;
  21. int height=Math.min(arr[st.peek()],arr[i]);
  22. int water=(height-pop_height)*distance;
  23. total+=water;
  24.  
  25. }
  26. st.push(i);
  27. }
  28. System.out.println(total);
  29. }
  30. }
Success #stdin #stdout 0.11s 55008KB
stdin
7
3
0
1
0
4
0
2
stdout
10