Explanation to this problem and solution

  • 0

    I think the main issue with this problem is the lack of an image. I initially thought this to be like the rain water trapping problem. Nonetheless, the editorial helped me understand and it turned out to be a fairly simple problem. The idea is to find two lines that could trap the maximum water by computing the area. Unlike trapped rainwater problem, it will use lines. For example, 1,1 in this problem will create an area of 1 but it will be 0 for rainwater trapping problem as it won't trap any water. Here is my solution after understanding the editorial:

     public int maxArea(int[] height)
        int maxArea = 0;
        int i = 0;
        int j = height.length - 1;
        while (i < j)
          maxArea =
              Math.max(maxArea, Math.min(height[i], height[j]) * (j - i));
          int newi = height[i] <= height[j] ? i + 1 : i;
          int newj = height[i] <= height[j] ? j : j - 1;
          i = newi;
          j = newj;
        return maxArea;

Log in to reply

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