fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int trapWater(vector<int>& heights) {
  5. int heightsSize = heights.size();
  6. int totalWater = 0; // Variable to store the total trapped water
  7.  
  8. for(int i = 0; i < heightsSize; i++) {
  9. // Initialize the maximum heights to left and right
  10. int maximumLeft = heights[0], maximumRight = heights[heightsSize-1];
  11.  
  12. // Find the maximum heights on the left of the current position
  13. for(int j = 0; j <= i; j++) {
  14. maximumLeft = max(maximumLeft, heights[j]);
  15. }
  16.  
  17. // Find the maximum heights on the right of the current position
  18. for(int j = i; j < heightsSize; j++) {
  19. maximumRight = max(maximumRight, heights[j]);
  20. }
  21.  
  22. // Calculate the trapped water at the current position
  23. totalWater += max(0, min(maximumLeft, maximumRight) - heights[i]);
  24. }
  25.  
  26. return totalWater;
  27. }
  28.  
  29. int main() {
  30. int n; cin >> n;
  31. vector<int> heights(n);
  32. for(int& height : heights) cin >> height;
  33. cout << trapWater(heights);
  34.  
  35. return 0;
  36. }
Success #stdin #stdout 0s 5272KB
stdin
12
0 1 0 2 1 0 1 3 2 1 2 1
stdout
6