forked from keineahnung2345/leetcode-cpp-practices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
11. Container With Most Water.cpp
77 lines (69 loc) · 2.21 KB
/
11. 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//WA
class Solution {
public:
int maxArea(vector<int>& height) {
int N = height.size();
int left = 0, right = N-1;
int ans = 0;
bool leftTurn = true;
while(left < right){
int lh = height[left], rh = height[right];
// cout << left << " " << right << endl;
ans = max(ans, min(lh, rh) * (right-left));
if(leftTurn){
//move left so heigh[left] is larger than old lh
do{
left++;
// cout << "left: " << left << endl;
}while(left < N && height[left] <= lh);
}else{
//move right so height[right] is larger than old rh
do{
right--;
// cout << "right: " << right << endl;
}while(right >= 0 && height[right] <= rh);
}
leftTurn = !leftTurn;
}
return ans;
}
};
//Approach 1: Brute Force
//TLE
//time: O(n^2), space: O(1)
class Solution {
public:
int maxArea(vector<int>& height) {
int N = height.size();
int ans = 0;
for(int i = 0; i < N-1; i++){
for(int j = i+1; j < N; j++){
ans = max(ans, min(height[i], height[j]) * (j-i));
}
}
return ans;
}
};
//Approach 2: Two Pointer Approach
//Runtime: 16 ms, faster than 96.00% of C++ online submissions for Container With Most Water.
//Memory Usage: 9 MB, less than 100.00% of C++ online submissions for Container With Most Water.
//time: O(n), space: O(1)
class Solution {
public:
int maxArea(vector<int>& height) {
int N = height.size();
int left = 0, right = N-1, ans = 0;
while(left < right){
ans = max(ans, min(height[left], height[right]) * (right-left));
//move the pointer pointing to lower bar forward,
//because if we move the pointer pointing to higher bar forward,
//the area can only be shrinked
if(height[left] < height[right]){
left++;
}else{
right--;
}
}
return ans;
}
};