28ms C++ solution with brief explanation


  • 0
    D

    We do a linear time search from the front and back of the height vector. At each step, factor the current capacity into the running max, then eliminate the smaller height because it is the limiting dimension in the capacity and won't contribute any more to the overall max.

    class Solution {
    public:
        int maxArea(vector<int> &height) {
            int capacity = 0;
            int i = 0, j = height.size() - 1;
            while (i < j) {
                capacity = max(capacity, static_cast<int>(j - i) * min(height[i], height[j]));
                if (height[i] < height[j]) {
                    i++;
                } else if (height[i] > height[j]){
                    j--;
                } else {
                    i++, j--;
                }
            }
            return capacity;
        }
    };

Log in to reply
 

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