---
title: "Container With Most Water"
author: "testforvln"
date: "2012-11-04T00:25:37Z"
tags: []
categories: ["编程语言"]
slug: "container-with-most-water"
draft: false
lastmod: "2012-11-04T00:25:37Z"
id: 1715175
url: "https://testforvln.iteye.com/blog/1715175"
---

本来以为是个简单的题目，直接二重循环，结果小测试过了，大测试超时了= = 1万个数据啊，必须优化了

```java

public class Solution {
    public int maxArea(int[] height) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int max = 0;
        int area = 0;
        for (int i = 0; i < height.length - 1; ++i)
            for (int j = i + 1; j < height.length; ++j){
                area = (j-i) * Math.min(height[i], height[j]);
                if (area > max)
                    max = area;
            }
        return max;
    }
}

```


想了一下 如果按照“以第i条线为最短边”来遍历的话，只需要从两边分别开始找到比它长的就行了，因为高度已经定了（第i条边的长度），而宽度自然是离i越远越好

```java

public class Solution {
    public int maxArea(int[] height) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int max = 0;
        int area = 0;
        for (int i = 0; i < height.length; ++i){
            for (int j = 0; j < i; j++)
                if (height[j] >= height[i]){
                    area = height[i] * (i - j);
                    if (area > max)
                        max = area;
                    break;
                }
            for (int j = height.length - 1; j > i; j--)
                if (height[j] >= height[i]){
                    area = height[i] * (j - i);
                    if (area > max)
                        max = area;
                    break;
                }
        }
        return max;
    }
}

```