Accepted use only one stack in cpp


  • 1
    H
    class Solution {
    public:
        int trap(vector<int>& height) {
            if (height.size()<3) return 0;
        	int res = 0;
        	stack<int>s;
        	int start = 0;
        	for (; start<height.size() - 2; ++start){
        		if (height[start]>height[start + 1])
        			break;
        	}
        	for (int i = start; i<height.size(); ++i){
        		if (s.empty() || height[s.top()] >=height[i]) s.push(i);
        		else{
        			while (!s.empty() && height[s.top()]<height[i]){
        				int idx = s.top();
        				s.pop();
        				if (s.empty())break;
        				int h = min(height[s.top()], height[i]) - height[idx];
        				int w = i - s.top() - 1;
        				res += h*w;
        			}
        			s.push(i);
        		}
        
        	}
        	return res;
        }
    };

Log in to reply
 

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