fork download
  1. // C++ implementation of the approach
  2.  
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // Function to return the maximum
  7. // water that can be stored
  8. int maxWater(int arr[], int n)
  9. {
  10. // To store the maximum water
  11. // that can be stored
  12. int res = 0;
  13.  
  14. // For every element of the array
  15. for (int i = 1; i < n - 1; i++) {
  16.  
  17. // Find the maximum element on its left
  18. int left = arr[i];
  19. for (int j = 0; j < i; j++)
  20. left = max(left, arr[j]);
  21.  
  22. // Find the maximum element on its right
  23. int right = arr[i];
  24. for (int j = i + 1; j < n; j++)
  25. right = max(right, arr[j]);
  26.  
  27. // Update the maximum water
  28. res = res + (min(left, right) - arr[i]);
  29. }
  30.  
  31. return res;
  32. }
  33.  
  34. // Driver code
  35. int main()
  36. {
  37. int arr[] = {0,1,0,2,1,0,1,3,2,1,2,1};
  38. int n = sizeof(arr) / sizeof(arr[0]);
  39.  
  40. cout << maxWater(arr, n);
  41.  
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
6