Created
May 8, 2022 20:46
-
-
Save RakshithNM/87a785232f09f7629e5316b00a7f79e1 to your computer and use it in GitHub Desktop.
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
/* Container With Most Water | |
* | |
* @param {number[]} height | |
* @return {number} | |
* | |
* Input: height = [1,8,6,2,5,4,8,3,7] | |
* Output: 49 | |
* Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. | |
*/ | |
const maxArea = function(height) { | |
let left = 0; | |
let right = height.length - 1; | |
let area = (right - 0) * Math.min(height[0], height[right]); | |
while(left < right) { | |
let runningArea = (right - left) * Math.min(height[left], height[right]); | |
if(height[left] > height[right]) { | |
right--; | |
} | |
else { | |
left++; | |
} | |
area = Math.max(area, runningArea); | |
} | |
return area; | |
}; | |
const height = [2, 3, 4, 5, 18, 17, 6]; | |
//const height = [2, 3, 10, 5, 7, 8, 9]; | |
console.log(maxArea(height)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment