3) CONTAINER WITH MOST WATER
https://leetcode.com/problems/container-with-most-water/
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.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example 2:
Input: height = [1,1] Output: 1
Constraints:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104
SOLUTION USING TYPESCRIPT
const height = [8, 2, 4, 5, 1, 1];
const maxArea = (height: number[]) => {
let i = 0;
let j = height.length - 1;
let width = 0;
let minHeight = 0;
let area = 0;
let maxArea = 0;
while (i <= j) {
width = j - i;
if (height[i] > height[j]) {
minHeight = height[j];
area = width * minHeight;
if (area > maxArea) {
maxArea = area;
}
j--;
} else {
minHeight = height[i];
area = width * minHeight;
if (area > maxArea) {
maxArea = area;
}
i++;
}
}
return maxArea;
};
console.log(maxArea(height));
Submission Detail
60 / 60 test cases passed. | Status: Accepted |
Runtime: 109 ms Memory Usage: 51.5 MB | Submitted: 3 months ago |
4) TRAPPING RAIN WATER
https://leetcode.com/problems/trapping-rain-water/
Given n
non-negative integers representing an elevation map where the width of each bar is 1
, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:
Input: height = [4,2,0,3,2,5] Output: 9
Constraints:
n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
SOLUTION USING TYPESCRIPT
const height = [4, 0, 1, 5, 0, 0, 1];
const trap = (height: number[]) => {
let leftmax = 0;
let rightmax = 0;
let waterLoggedUnit = 0;
let i = 0;
let j = height.length - 1;
while (i < j) {
if (height[i] < height[j]) {
if (height[i] > leftmax) {
leftmax = height[i];
i++;
} else {
waterLoggedUnit += leftmax - height[i];
i++;
}
} else {
if (height[j] > rightmax) {
rightmax = height[j];
j--;
} else {
waterLoggedUnit += rightmax - height[j];
j--;
}
}
}
return waterLoggedUnit;
};
console.log(trap(height));
Submission Detail
321 / 321 test cases passed. | Status: Accepted |
Runtime: 102 ms Memory Usage: 46.2 MB | Submitted: 3 months ago |