Trapping Rain Water

Solution :-

#include <iostream>
using namespace std;

int main() {
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        int arr[n];
        for(int i=0;i<n;i++){
            cin>>arr[i];
        }
        int left[n];
        int right[n];
        left[0]=arr[0];
        for(int i=1;i<n;i++){
            if(left[i-1]<arr[i]){
                left[i]=arr[i];
            }
            else{
                left[i]=left[i-1];
            }
        }
        right[n-1]=arr[n-1];
        for(int i=n-2;i>=0;i--){
            if(right[i+1]<arr[i]){
                right[i]=arr[i];
            }
            else{
                right[i]=right[i+1];
            }
        }
        int save=0;
        for(int i=0;i<n;i++){
            save+=min(left[i],right[i])-arr[i];
        }
        cout<<save<<endl;
    }
    return 0;
}

Contact us





JDoodle for WordPress
Scroll Up