Skip to content

Commit e8ccbdd

Browse files
Solution Leetcode and Explaination Every single line
1 parent e3ab03b commit e8ccbdd

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
✅ Java Code (Optimal Two-Pointer Approach)
2+
3+
class Solution {
4+
public int maxArea(int[] height) {
5+
int max = 0;
6+
int left = 0, right = height.length - 1;
7+
8+
while (left < right) {
9+
int h = Math.min(height[left], height[right]);
10+
int w = right - left;
11+
max = Math.max(max, h * w);
12+
13+
// Move pointer which has smaller height
14+
if (height[left] < height[right]) {
15+
left++;
16+
} else {
17+
right--;
18+
}
19+
}
20+
21+
return max;
22+
}
23+
}
24+
25+
26+
📘 Explanation (Line-by-Line)
27+
28+
int max = 0;
29+
🔹 Ab tak ka maximum area store karne ke liye variable.
30+
31+
int left = 0, right = height.length - 1;
32+
🔹 2 pointer technique: Ek array ke start par (left) aur ek end par (right).
33+
34+
while (left < right) {
35+
🔹 Jab tak left aur right pointers ek dusre ko cross nahi karte.
36+
37+
int h = Math.min(height[left], height[right]);
38+
🔹 Dono boundaries me se chhoti height lete hain (kyunki water wahin tak bharega).
39+
40+
int w = right - left;
41+
🔹 Width nikaali → right aur left ke beech ka distance.
42+
43+
max = Math.max(max, h * w);
44+
🔹 Max area update kiya (height × width).
45+
46+
if (height[left] < height[right]) {
47+
left++;
48+
🔹 Chhoti boundary ko move karo (chance zyada area ka badhne ka hai).
49+
} else {
50+
right--;
51+
🔹 Right side chhoti hai toh usse move karo.
52+
}
53+
}
54+
55+
return max;
56+
🔹 Sabse bada area return kar do.
57+
58+
🧠 Example Input:
59+
Input: height = [1,8,6,2,5,4,8,3,7]
60+
Output: 49
61+
Explanation: Water is stored between index 1 and 8 → min(8, 7) × (8 - 1) = 49
62+
🚀 Time & Space Complexity:
63+
64+
Time: O(n)
65+
66+
Space: O(1)
67+
68+
🔗 Need more help or Java tricks?
69+
https://www.linkedin.com/in/saurabh884095/
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public int maxArea(int[] height) {
3+
int max = 0;
4+
int left = 0, right = height.length - 1;
5+
6+
while (left < right) {
7+
int h = Math.min(height[left], height[right]);
8+
int w = right - left;
9+
max = Math.max(max, h * w);
10+
11+
// Move pointer which has smaller height
12+
if (height[left] < height[right]) {
13+
left++;
14+
} else {
15+
right--;
16+
}
17+
}
18+
19+
return max;
20+
}
21+
}

0 commit comments

Comments
 (0)