dev-resources.site
for different kinds of informations.
Container With Most Water
Published at
5/3/2022
Categories
leetcode
array
twopointer
Author
styluso7
Author
8 person written this
styluso7
open
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)
twopointer Article's
12 articles in total
A tΓ©cnica dos dois ponteiros
read article
Find all anagrams in the string[Fixed Window pattern]
read article
125. Valid Palindrome
read article
Pattern 3: Two Pointers
read article
Sliding subarray beauty
read article
Jump Game II
read article
Max consecutive one's III
read article
3Sum Closest
read article
Container With Most Water
currently reading
Diffk Solution - Interviewbit
read article
Count the triplets
read article
Two Sum - Leetcode
read article
Featured ones: