DEV Community

Seth
Seth

Posted on

Max Water Container

Let's observe the logic behind the chart we're seeing.
Image description

The area, and the answer, is 49.

We got that number because we looked at the distance between the two indices and then multiplied it by the minimum value of both indices.

Let's look at the first part, the width, since finding an area is width times height.

result = (j-i)*min(height[j], height[i])
         ______
           7

 height = [1,8,6,2,5,4,8,3,7]
             _             _
             1             8

   8-1 = 7
Enter fullscreen mode Exit fullscreen mode

Now let's look at the second part. The height.

result = (j-i)*min(height[j], height[i])
                ___________________
                   7

 height = [1,8,6,2,5,4,8,3,7]
             _             _
             8             7

  min(7, 8) = 7
Enter fullscreen mode Exit fullscreen mode

And let's do the last step just for kicks, multiplying them together, then we'll jump into code.

result = (j - i)*min(height[j], height[i])
          ___________________  _________________________
              7             *             7
           **= 49**

Enter fullscreen mode Exit fullscreen mode

And that is how we will get our answer.

The first thing we want is to declare variables. i is at the left, and j is at the right.

Then we will want them to move left and right.


function maxWater (array) {
 let i = 0
 let j = array.length - 1
 let area = 0

}
Enter fullscreen mode Exit fullscreen mode

Now let start iterating through the array, and we will do so with a while loop until the two pointers meet each other.


function maxWater (array) {
 let i = 0
 let j = array.length - 1
 let area = 0

 while (i < j) {
   const temp = (j - i).Math.min(array[j], array[i])

 }

}

Enter fullscreen mode Exit fullscreen mode

Then we update the area and move the i and j. It's not helpful to move the larger number in this case, so we only move the lower number.


function maxWater (array) {
 let i = 0
 let j = array.length - 1
 let area = 0

 while (i < j) {
   const temp = (j - i).Math.min(array[j], array[i])
   area = Math.max(temp, area)
   if (array[i] > array[j]) {
    array[j]-=1
   } 
     else {
   array[i]+=1
  }
 }
 return area
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)