Created
July 24, 2022 00:35
-
-
Save cazlu8/84ed80824c7088740c7e44bffd9fe4ec to your computer and use it in GitHub Desktop.
Container With Most Water
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var maxArea = function(height) { | |
let pointer1, pointer2; | |
let sum = 0; | |
let length = height.length | |
let calculate = (pointer1, pointer2) => { | |
if(height[pointer1] === 0 || height[pointer2] === 0) | |
return 0 | |
return Math.min(height[pointer1], height[pointer2]) * Math.abs(pointer2 - pointer1) || 1; | |
} | |
const end = length - 1; | |
let lastIndex = 0; | |
for(let i = 0; i < length; i++) { | |
pointer1 = lastIndex | |
pointer2 = end - i; | |
if(pointer1 >= pointer2) | |
return sum; | |
while (pointer1 < pointer2) { | |
if(end > pointer2 && height[pointer2 + 1] >= height[pointer2]) | |
break; | |
calculation = calculate(pointer1, pointer2) | |
if(height[pointer1] === height[pointer2]) { | |
if(calculation > sum) | |
sum = calculation | |
lastIndex = pointer1; | |
break; | |
} else if(calculation > sum) { | |
sum = calculation | |
lastIndex = pointer1; | |
} else if(height[pointer1 - 1] >= height[pointer2]) | |
break; | |
pointer1++; | |
} | |
} | |
return sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment