- Outer loop - left stick
- Inner loop - right stick
- Record the water volume for each iteration
T = O(N^2) S = O(1)
class Solution {
public int maxArea(int[] height) {
int maxWaterVol = 0;
int n = height.length;
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
int currWaterVol = Math.min(height[i], height[j]) * (j - i);
maxWaterVol = Math.max(maxWaterVol, currWaterVol);
}
}
return maxWaterVol;
}
}
Use Two Pointers
- Initial Left stick will be
0
index & Right stick will ben-1
index - Calculate the water volume (currWaterVolume)between these two sticks (refer diagram - to know how)
- Have a outer variable to store maxWaterVolume for each stick iteration
- If:
LeftStick_height < RightStick_height
: move to the next sticki++
- If:
RightStick_height < LeftStick_height
: move to the next stickj--
- If
LeftStick_height == RightStick_height
: move both sticks++i
,--j
T = O(N) S = O(1) Approach
class Solution {
public int maxArea(int[] height) {
int i = 0;
int j = height.length - 1;
int maxWaterVol = 0;
while(i < j) {
int currWaterVol = (j - i) * Math.min(height[i], height[j]);
maxWaterVol = Math.max(maxWaterVol, currWaterVol);
if(height[i] == height[j]) {
++i;
--j;
} else if(height[i] < height[j]) {
++i;
} else {
--j;
}
}
return maxWaterVol;
}
}