fork download
  1. class TrapRainWater {
  2.  
  3. public static void main(String[] args) {
  4. int[] bars = {0, 1, 0, 2, 1, 0 , 1, 3, 2, 1, 2, 1 };
  5. System.out.println(trap(bars));
  6. }
  7.  
  8. // Brute Force Approach
  9. static int trapWaterUsingBrute(int[] bars) {
  10. int len = bars.length;
  11. int trappedWater = 0;
  12. for (int i = 1; i < len - 1; i++) {
  13. int lmax = 0, rmax = 0;
  14.  
  15. for (int j = i - 1; j >= 0; j--)
  16. lmax = Math.max(lmax, bars[j]);
  17.  
  18. for (int j = i + 1; j < len; j++)
  19. rmax = Math.max(rmax, bars[j]);
  20.  
  21. trappedWater += Math.max(0, Math.min(lmax, rmax) - bars[i]);
  22. }
  23. return trappedWater;
  24. }
  25. }
Success #stdin #stdout 0.05s 2184192KB
stdin
Standard input is empty
stdout
11