# LeetCode: Container With Most Water Solution

## Approach

The point here is to prove why when

h[i] < h[j]
we move
i
to the right

By contradiction, if we move

j
to the left instead:

• horizontal length will reduce whatever
• if
h[j-1] < h[i]
-> area will be
h[j-1] * horizontal length
-> smaller than previous
• if
h[j-1] > h[i]
-> area will be
h[i] * horizontal length
-> smaller than previous

So there is no way moving

j
to the left will produce larger area

## Implementation

`.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[]} height3 * @return {number}4 */5var maxArea = function (height) {6  let i = 07  let j = height.length - 18  let max = -Infinity9  while (i != j) {10    max = Math.max(max, Math.min(height[i], height[j]) * Math.abs(i - j))11    if (height[i] > height[j]) {12      j--13    } else {14      i++15    }16  }17  return max18}`

leetcode

array

two pointers

## Next Post

LeetCode: Arithmetic Slices

Feb 18, 2021

Search Posts