11 - Container With Most Water

 JAVA

  • class Solution {
        public int maxArea(int[] height) {
            int i = 0, j = height.length - 1;
            int ans = 0;
            while (i < j) {
                int t = Math.min(height[i], height[j]) * (j - i);
                ans = Math.max(ans, t);
                if (height[i] < height[j]) {
                    ++i;
                } else {
                    --j;
                }
            }
            return ans;
        }
    }
C++

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

Comments