Skip to content

Commit

Permalink
Add container-with-most-water solution
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeehay28 committed Jan 12, 2025
1 parent 4d19c46 commit 7287a87
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions container-with-most-water/Jeehay28.js
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;
};

0 comments on commit 7287a87

Please sign in to comment.