果果1020

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

 1 public class Solution {
 2     public int maxArea(int[] height) {
 3         if (height == null || height.length < 2) {
 4             return 0;
 5         }
 6         
 7         int l = 0;
 8         int r = height.length - 1;
 9         int max = 0;
10         while (l < r)
11         {
12             int area = 0;
13             if (height[l] > height[r]) {
14                 area = height[r] * (r - l);
15                 r--;
16             } else {
17                 area = height[l] * (r - l);
18                 l++;
19             }
20             if (area > max) {
21                 max = area;
22             }
23         }
24         
25         return max;
26     }
27 }

 

posted on 2017-01-02 17:32  果果1020  阅读(98)  评论(0)    收藏  举报