Пример #1
0
    int trap(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n <= 2)
            return 0;
        
        vector<int> leftMax(n, 0);
        vector<int> rightMax(n, 0);
        
        leftMax[0] = A[0];
        rightMax[n-1] = A[n-1];

        for(int i = 1; i < n-1; i++)
        {
            leftMax[i] = max(leftMax[i-1], A[i]);
            rightMax[n-1-i] = max(rightMax[n-1-i+1], A[n-1-i]);
        }
        
        int ret = 0;
        for(int i = 1; i< n-1; i++)
        {
            ret += (leftMax[i] > rightMax[i]?rightMax[i]:leftMax[i])-A[i];
        }
        return ret;
    }
Пример #2
0
			int trap(vector<int>& height)
			{
				int len = height.size();
				if (len == 0) { return 0; }

				vector<int> leftMax(len, 0);
				vector<int> rightMax(len, 0);
				int maxL = 0;
				int maxR = 0;
				for (int i = 0; i < len; i++)
				{
					leftMax[i] = maxL;
					maxL = max(maxL, height[i]);

					rightMax[len - 1 - i] = maxR;
					maxR = max(maxR, height[len - 1 - i]);
				}

				int result = 0;
				for (int i = 0; i < len; i++)
				{
					result += max(min(leftMax[i], rightMax[i]) - height[i], 0);
				}
				return result;
			}