Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- typedef long long ll;
- typedef unsigned long long ull;
- typedef long double ld;
- #define vi vector<int>
- #define vll vector<long long>
- #define pb push_back
- #define vpll vector<pair<ll, ll>>
- #define vpi vector<pair<int, int>>
- #define p_b pop_back
- #define FOR(a, b) for(int i = a; i <= b; i++)
- #define tests() int t; cin >> t; while(t--)
- #define input(a, n) for(int i = 0; i < n; i++){int x; cin >> x; a.pb(x);}
- #define MOD (ull)1000000007
- using namespace std;
- ll trappingWater(int arr[], int n){
- int i = 0, k = 0;
- ll sum = 0;
- bool f = true;
- while(i < n){
- int j = i;
- //check for values in the array after i which are less than or equal to arr[i]
- while(arr[j] <= arr[i] && j < n){
- j++;
- }
- /*if the loop reaches the end of the array then it means that the last element of the array
- is less than arr[i], hence the we should calculate in the reverse order upto i to find the sum,
- if its not the case then simply calculate the differences with arr[i] and we will get the total volume*/
- if(j == n){
- f = false;
- k = i;
- break;
- } else{
- int tmp = j;
- j--; //decremented due to fact that arr[j] is greater than arr[i]
- while(j >= i){
- sum += arr[i]-arr[j];
- j--;
- }
- i = tmp;
- }
- }
- if(!f){
- /*if the first case is satisfied in the earlier loop then find the differences from the back of the array*/
- i = n-1;
- while(i >= k){
- int j = i;
- while(arr[j] <= arr[i] && j >= k){
- sum += arr[i]-arr[j];
- j--;
- }
- i = j;
- }
- }
- return sum;
- }
- int main(){
- ios_base::sync_with_stdio(false);
- cin.tie(NULL);
- int n;
- cin >> n;
- int arr[n];
- for(int i = 0; i < n; i++){
- cin >> arr[i];
- }
- cout << trappingWater(arr, n);
- return 0;
- }
Add Comment
Please, Sign In to add comment