• + 1 comment

    My code is working, but can anyone please explain to me in a simple way what this problem has to do with stacks?

    long largestRectangle(vector<int> h) 
    {
        if (h.size() == 0)
            return 0;
        else if (h.size() == 1)
            return long(h[0]);
            
        int h_min = *min_element(h.begin() , h.end());
        long area_h_min = long(h_min) * long(h.size());
        
        vector<int> h_short;
        vector<int> possible_ans;
        possible_ans.push_back(area_h_min);
        
        for (int i = 0 ; i < h.size() ; i++)
        {
            if (  h[i] > h_min )
            {
                h_short.push_back(h[i]);
            }   
            else if (h[i] == h_min)
            {
                possible_ans.push_back(largestRectangle(h_short));
                h_short.clear();
            }
        }
        possible_ans.push_back(largestRectangle(h_short));
        h_short.clear();
        
        return *max_element(possible_ans.begin() , possible_ans.end());
    
    }