详细见:leetcode.com/problems/container-with-most-water/
Java Solution: github
package leetcode;
public class P011_ContainerWithMostWater {
/**
* @author zxwtry
* @email zxwtry@qq.com
* @project OJ
* @package leetcode
* @file P011_ContainerWithMostWater.java
* @type Solution5
* @date 2016年12月8日 下午3:29:46
* @details 86.76% 8ms AC
*/
static class Solution5 {
public int maxArea(int[] h) {
if (h == null || h.length < 2) return 0;
int l = 0, r = h.length - 1, ans = 0, k = 0;
while (l < r) {
ans = Math.max(Math.min(h[l], h[r]) * (r - l), ans);
if (h[l] < h[r]) {
k = l;
while (k < r && h[k] <= h[l]) k ++;
l = k;
} else {
k = r;
while (k > l && h[k] <= h[r]) k --;
r = k;
}
}
return ans;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/container-with-most-water/
13ms 18.14%
*/
#include <stdio.h>
#include <stdlib.h>
int maxArea(int* h, int s) {
int l = 0, r = s - 1, a = 0, k = 0;
while (l < r) {
a = max(a, min(*(h + l), *(h + r)) * (r - l));
if (*(h + l) > *(h + r)) {
do {
r --;
} while (r > l && *(h + r) <= *(h + r + 1));
} else {
do {
l ++;
} while (l < r && *(h + l) <= *(h + l - 1));
}
}
return a;
}
int main() {
int h[] = {0, 5, 2, 3, 4, 1};
int s = 6;
printf("answer is %d\r\n", maxArea(h,s));
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/container-with-most-water/
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年3月27日
@details: Solution: AC 78ms 71.02%
'''
class Solution(object):
def maxArea(self, h):
"""
:type height: List[int]
:rtype: int
"""
l, r = 0, len(h) - 1
a = 0
while l < r:
a = max(a, min(h[l], h[r]) * (r - l))
if h[l] < h[r]:
while True:
l += 1
if l >= r or h[l - 1] < h[l]:
break
else:
while True:
r -= 1
if l >= r or h[r + 1] < h[r]:
break
return a
if __name__ == "__main__":
h = [1, 9, 2, 8, 3, 7, 4, 6]
print(Solution().maxArea(h))