Skip to content

Instantly share code, notes, and snippets.

@lsem
Created May 8, 2024 14:53
Show Gist options
  • Save lsem/430794b01821e272789a2f26eeb0c8d2 to your computer and use it in GitHub Desktop.
Save lsem/430794b01821e272789a2f26eeb0c8d2 to your computer and use it in GitHub Desktop.
container_with_most_water.cpp
class Solution {
public:
int maxArea(const vector<int>& height) {
size_t left = 0;
size_t right = height.size()-1;
int max_a = 0;
while (left < right) {
int h = std::min(height[left], height[right]);
int w = right - left;
int a = h * w;
if (a > max_a) {
max_a = a;
}
// always select smaller size.
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return max_a;
}
int maxArea_naive(vector<int>& height) {
int max_i = 0, max_j = 0;
int max_a = 0;
for (int i = 0; i < height.size(); ++i) {
for (int j = i + 1; j < height.size(); ++j) {
int h = std::min(height[i], height[j]);
int w = j - i;
auto a = h * w;
if (a > max_a) {
max_a = a;
max_i = i;
max_j = j;
}
}
}
return max_a;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment