-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add container-with-most-water solution
- Loading branch information
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/** | ||
* @param {number[]} height | ||
* @return {number} | ||
*/ | ||
|
||
// Time Complexity: O(n) | ||
// Space Complexity: O(1) | ||
var maxArea = function (height) { | ||
let start = 0; | ||
let end = height.length - 1; | ||
let maxArea = 0; | ||
|
||
while (start < end) { | ||
const area = (end - start) * Math.min(height[start], height[end]); | ||
maxArea = Math.max(area, maxArea); | ||
|
||
// The shorter height limits the area. | ||
// By moving the pointer associated with the shorter height, | ||
// the algorithm maximizes the chance of finding a taller line that can increase the area. | ||
// This is the essence of the two-pointer strategy for the container problem. | ||
if (height[start] < height[end]) { | ||
start += 1; | ||
} else { | ||
end -= 1; | ||
} | ||
} | ||
return maxArea; | ||
}; | ||
|