Challenge: Container With Most Water
Welcome to Day 5 of our 100 Days DSA Challenge! 🚀 Today, we face a captivating challenge involving elevation maps and the art of trapping rainwater. Let’s dive into the intricacies of computing the maximum amount of water that can be trapped.
The Challenge:
Given an array of non-negative integers representing an elevation map, our task is to compute the maximum amount of water that can be trapped after raining. The width of each bar is 1.
Example:
const heights = [1, 8, 6, 2, 5, 4, 8, 3, 7];
// Output: 49
In this example, the most water (49 units) can be trapped between the 2nd and 9th bars. The width of the container is determined by the indices of the two bars, and the height of the container is determined by the shorter of the two bars.
Challenge Yourself:
Before exploring the solution, challenge yourself to think about how you would approach this problem. Can you optimize the code further?
The Solution:
const containerWithMostWater = (arr) => {
let start = 0;
let end = arr.length - 1;
let maxWater = 0;
while (start < end) {
let max = 0;
let width = end - start;
if (arr[start] < arr[end]) {
max = arr[start] * width;
start++;
} else {
max = arr[end] * width;
end--;
}
maxWater = Math.max(maxWater, max);
}
return maxWater;
}
Solution Logic:
- Initialize Pointers and Variables:
- We start with two pointers,
start
at the beginning of the array andend
at the end. maxWater
is the variable to keep track of the maximum water that can be trapped.
- We start with two pointers,
- Iterate Towards the Center:
- We use a
while
loop to iterate until thestart
andend
pointers meet.
- We use a
- Calculate Trapped Water:
- For each iteration, we calculate the potential trapped water by considering the minimum height between the two bars (determined by
arr[start]
andarr[end]
) multiplied by the width (end - start
).
- For each iteration, we calculate the potential trapped water by considering the minimum height between the two bars (determined by
- Move Pointers Based on Height:
- We move the pointer associated with the shorter bar, as trapping more water depends on increasing the height of the shorter bar.
- Update Maximum Trapped Water:
- We update
maxWater
with the maximum value obtained in each iteration.
- We update
- Repeat Until Pointers Meet:
- We repeat these steps until the
start
andend
pointers meet in the center.
- We repeat these steps until the
- Return Maximum Trapped Water:
- The final result is the maximum amount of water that can be trapped.
Conclusion:
Congratulations on completing Day 5 of our DSA Challenge! Trapping water between elevation bars is a captivating problem, and mastering it enhances your algorithmic skills. Stay tuned for tomorrow’s challenge, and keep the coding spirit alive!
Happy coding! 🌟💻
#100DaysDSAChallenge #DataStructures #Algorithms #ProgrammingCommunity #CodeNewbie