Skip to content

Commit d470e21

Browse files
authored
Merge pull request #536 from Anupam-Panwar/containerWithMostWater
Added containerWithMostWater.cpp
2 parents 202f647 + a000b03 commit d470e21

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Arrays/containerWithMostWater.cpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n
3+
vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0).
4+
Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
5+
6+
Notice that you may not slant the container.
7+
8+
9+
Input: height = [1,8,6,2,5,4,8,3,7]
10+
Output: 49
11+
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7].
12+
In this case, the max area of water the container can contain is 49.
13+
14+
Constraints:
15+
n == height.length
16+
2 <= n <= 105
17+
0 <= height[i] <= 104
18+
19+
*/
20+
21+
/*
22+
Time Complexity: O(N), where N is the size of the array
23+
Space Complexity: O(1), Constant Space
24+
*/
25+
26+
#include <bits/stdc++.h>
27+
using namespace std;
28+
29+
int maxArea(vector<int> &height)
30+
{
31+
int n = height.size();
32+
int i = 0; // one pointer to the start of the array
33+
int j = n - 1; // one poninter to the end of the array
34+
int mx = min(height[i], height[j]) * (j - i); // contains the max value of maximum water that can be stored
35+
while (i < j)
36+
{
37+
if (height[i] < height[j]) // Checking condition if height pointed by i is less than that pointed by j if yes => incrementing i and updating value of mx
38+
{
39+
i++;
40+
mx = max(mx, (min(height[i], height[j]) * (j - i)));
41+
}
42+
else // otherwise => decrementing j and updating value of mx
43+
{
44+
j--;
45+
mx = max(mx, (min(height[i], height[j]) * (j - i)));
46+
}
47+
}
48+
return mx;
49+
}
50+
51+
int main() // driver function
52+
{
53+
vector<int> heights = {1,8,6,2,5,4,8,3,7};
54+
int ans = maxArea(heights);
55+
cout<<ans;
56+
return 0;
57+
}

0 commit comments

Comments
 (0)