Created
October 4, 2025 17:01
-
-
Save tatsuyax25/738a2a6f29547f3afdbf06bf90b57c0c to your computer and use it in GitHub Desktop.
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container con
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
| /** | |
| * @param {number[]} height | |
| * @return {number} | |
| */ | |
| var maxArea = function(height) { | |
| // Initialize two pointers: one at the start, one at the end of the array | |
| let left = 0; | |
| let right = height.length - 1; | |
| // Variable to keep track of the maximum area found so far | |
| let maxArea = 0; | |
| // Loop until the two pointers meet | |
| while (left < right) { | |
| // Calculate the width between the two lines | |
| let width = right - left; | |
| // Calculate the height of the container (limited by the shorter line) | |
| let containerHeight = Math.min(height[left], height[right]); | |
| // Calculate the area and update maxArea if it's larger than the current max | |
| let currentArea = width * containerHeight; | |
| maxArea = Math.max(maxArea, currentArea); | |
| // Move the pointer pointing to the shorter line inward | |
| // This is because moving the taller line won't help increase the area | |
| if (height[left] < height[right]) { | |
| left++; // Try to find a taller line on the left | |
| } else { | |
| right--; // Try to find a taller line on the right | |
| } | |
| } | |
| // Return the maximum area found | |
| return maxArea; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment