fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5. // created a function of vector of integers 'height' and it returns the amout of water trapped
  6. int trap(vector<int> & height){
  7. if(height.empty())
  8. return 0;
  9.  
  10. // created 2 pointers : 'left', 'right'
  11. // initializing the left and left so that we can track left and right pointers
  12. int left = 0, right = height.size() - 1;
  13. //also initialized max_left, max_right and the amout of water trapped
  14. int max_left = 0, max_right = 0;
  15. int water_trapped = 0;
  16.  
  17. //now while loop will run until the left pointer is less than or equal to the right pointer
  18. while (left <= right) {
  19. if (height[left] <= height[right]) {
  20. //left side height is greater than max_left
  21. if (height[left] > max_left)
  22. // update it to the current height
  23. max_left = height[left];
  24. else
  25. // we are calculating the water trapped
  26. water_trapped += max_left - height[left];
  27. left++;
  28. } else {
  29. // same thing as we did above we are again doing it if we are processing from the right hand side
  30. if (height[right] > max_right)
  31. max_right = height[right];
  32. else
  33. water_trapped += max_right - height[right];
  34. right--;
  35. }
  36. }
  37. return water_trapped;
  38. }
  39.  
  40. int main(){
  41. // in the main func we are simply passing the values
  42. vector<int> height = {3,1,2,4,0,2,1,3};
  43. // after initializing we passed to the trap func and printing the output using cout func
  44. cout << trap(height) << "\n";
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
9