Share my O(n) solution


  • 0
    X
    class Solution {
    public:
        int trap(int A[], int n) {
            int low = 0, high = n-1;
            int bar = 0, rain = 0;
    
            while (low < high) {
                    const int newbar = min(A[low], A[high]);
                    if (newbar > bar) {
                            rain += (newbar-bar) * (high-low);
                            bar = newbar; 
                    }
    
                    if (A[low] < A[high]) {
                            rain -= min(bar, A[low]);
                            ++low;
                    }
                    else {
                            rain -= min(bar, A[high]);
                            --high;
                    }
            }
    
            return rain;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.