dev-resources.site
for different kinds of informations.
Container With Most Water
Published at
5/3/2022
Categories
leetcode
array
twopointer
Author
Stylus07
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 contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Problem statement taken from: https://leetcode.com/problems/container-with-most-water/
Brute Force Approach
var maxArea = function (heights) {
let maxArea = 0;
for (let p1 = 0; p1 < heights.length; p1++) {
for (let p2 = p1 + 1; p2 < heights.length; p2++) {
const length = Math.min(heights[p1], heights[p2]);
const width = p2 - p1;
const area = length * width;
maxArea = Math.max(area, maxArea);
}
}
return maxArea;
}
Time Complexity : O(n^2)
Space Complexity : O(1)
Optimized Approach
let maxArea = 0, p1 = 0, p2 = heights.length - 1;
while (p1 < p2) {
const height = Math.min(heights[p1], heights[p2]);
const width = p2 - p1;
const area = height * width;
maxArea = Math.max(maxArea, area);
if (heights[p1] <= heights[p2]) {
p1++;
} else {
p2--;
}
}
return maxArea;
Time Complexity : O(n)
Space Complexity : O(1)
Articles
10 articles in total
Container With Most Water
currently reading
Logger Rate Limiter
read article
Longest Consecutive Sequence
read article
Encode and Decode Strings
read article
Group Anagrams
read article
Valid Anagram
read article
Contains Duplicate
read article
Peak Index in a Mountain Array
read article
Intersection of Three Sorted Arrays
read article
Change the document title on react application
read article
Featured ones: