leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit badbb55eba0ccf863d56ded03317f945f250850a
parent 2480c593f614b6a93882311ddfb9bdc885f40c98
Author: Jack Sangdahl <jack@pngu.org>
Date:   Fri,  3 Oct 2025 21:55:54 -0600

11. container with most water

Diffstat:
Acontainer_most_water.c | 29+++++++++++++++++++++++++++++
Acontainer_most_water.py | 32++++++++++++++++++++++++++++++++
2 files changed, 61 insertions(+), 0 deletions(-)

diff --git a/container_most_water.c b/container_most_water.c @@ -0,0 +1,29 @@ +// 11. Container With Most Water +#include "leetcode.h" + +/* + * you are given an integer array 'height' of length 'n'. there are 'n' vertical + * lines drawn such that two endpoints of the i'th line are '(i, 0)' and '(i, + * height[i])'. find two lines that together with the x-axis form a container + * such that the container contains the most water. return the maximum amount of + * water a container can store. notice that you may not slant the container. + */ + +int maxArea(int *height, int heightSize) { + int left = 0, right = heightSize - 1, ans = 0; + while (left < right) { + int curr = fmin(height[left], height[right]) * (right - left); + ans = fmax(ans, curr); + if (height[left] < height[right]) + left++; + else + right--; + } + return ans; +} + +int main() { + int h1[] = {1, 8, 6, 2, 5, 4, 8, 3, 7}, h2[] = {1, 1}; + printf("%d\n", maxArea(h1, ARRAY_SIZE(h1))); // expect: 49 + printf("%d\n", maxArea(h2, ARRAY_SIZE(h2))); // expect: 1 +} diff --git a/container_most_water.py b/container_most_water.py @@ -0,0 +1,32 @@ +# 11. Container With Most Water + +""" +you are given an integer array 'height' of length 'n'. there are 'n' vertical +lines drawn such that two endpoints of the i'th line are '(i, 0)' and '(i, +height[i])'. find two lines that together with the x-axis form a container +such that the container contains the most water. return the maximum amount of +water a container can store. notice that you may not slant the container. +""" + + +class Solution(object): + def maxArea(self, height): + """ + :type height: List[int] + :rtype: int + """ + left, right, ans = 0, len(height) - 1, 0 + while left < right: + curr = min(height[left], height[right]) * (right - left) + ans = max(ans, curr) + if height[left] < height[right]: + left += 1 + else: + right -= 1 + return ans + + +if __name__ == "__main__": + obj = Solution() + print(obj.maxArea(height=[1, 8, 6, 2, 5, 4, 8, 3, 7])) + print(obj.maxArea(height=[1, 1]))