Vukan Vuckovic
Figma
WordPress
Elementor
HTML
CSS
Node.js
JavaScript
TypeScript
PHP
NPM
React
React Native
Expo
Next.js
Tailwind CSS
GSAP
Three.js
Appwrite
Figma
WordPress
Elementor
HTML
CSS
Node.js
JavaScript
TypeScript
PHP
NPM
React
React Native
Expo
Next.js
Tailwind CSS
GSAP
Three.js
Appwrite
Figma
HTML
TypeScript
CSS
Tailwind CSS
React
Next.js
GSAP
Figma
HTML
TypeScript
CSS
Tailwind CSS
React
Next.js
GSAP
HTML
TypeScript
CSS
Tailwind CSS
React Native
Expo
GSAP
Appwrite
HTML
TypeScript
CSS
Tailwind CSS
React
Next.js
GSAP
Appwrite
1function trap(height: number[]): number {
2 let left = 0;
3 let right = height.length - 1;
4 let leftMax = 0;
5 let rightMax = 0;
6 let waterTrapped = 0;
7
8 while (left <= right) {
9 if (height[left] <= height[right]) {
10 if (height[left] >= leftMax) {
11 leftMax = height[left]; // Update left max
12 } else {
13 waterTrapped += leftMax - height[left]; // Calculate trapped water
14 }
15 left++;
16 } else {
17 if (height[right] >= rightMax) {
18 rightMax = height[right]; // Update right max
19 } else {
20 waterTrapped += rightMax - height[right]; // Calculate trapped water
21 }
22 right--;
23 }
24 }
25
26 return waterTrapped;
27 }
28
29 // Example usage
30 const height1 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];
31 console.log(trap(height1)); // Output: 6
32
33 const height2 = [4, 2, 0, 3, 2, 5];
34 console.log(trap(height2)); // Output: 9