-
Notifications
You must be signed in to change notification settings - Fork 0
/
10_container-with-most-water.cpp
61 lines (54 loc) · 1.37 KB
/
10_container-with-most-water.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// DATE: 28-July-2023
/* PROGRAM: 10_Array - Container With Most Water
https://leetcode.com/problems/container-with-most-water/
*/
// @ankitsamaddar @July_2023
#include <iostream>
#include <vector>
using namespace std;
// BRUTE FORCE O(n^2)
/*
class Solution {
public:
int maxArea(vector<int>& height) {
int res =0;
for (int l = 0 ;l < height.size();l++){
for(int r=l+1;r<height.size();r++){
// area = length(r_index - l_index) * breadth(min of )
int area = (r - l)*min(height[l],height[r]);
res = max(res,area);
}
}
return res;
}
};
*/
// LINEAR O(n)
class Solution {
public:
int maxArea(vector<int>& height) {
long long maxArea = 0;
int left = 0, right = height.size() - 1;
while (left < right) {
int length = right - left;
int breadth = min(height[left], height[right]);
// calculate area and store the max area
long long area = length * breadth;
maxArea = max(area, maxArea);
// move left towards right if left is smaller than right
if (height[left] < height[right])
left++;
else
right--; // move right toward left
}
return maxArea;
}
};
int main() {
int nums[] = {1, 8, 6, 2, 5, 4, 8, 3, 7};
vector<int> v(nums, nums + sizeof(nums) / sizeof(int));
Solution sol;
int res = sol.maxArea(v);
cout << res << endl;
return 0;
}