Created
May 8, 2024 14:53
-
-
Save lsem/430794b01821e272789a2f26eeb0c8d2 to your computer and use it in GitHub Desktop.
container_with_most_water.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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