11. Container With Most Water

来源:互联网 发布:人类基因组计划 知乎 编辑:程序博客网 时间:2024/06/17 10:20

11. Container With Most Water

 My Submissions
  • Total Accepted: 106402
  • Total Submissions: 295741
  • Difficulty: Medium
  • Contributors: Admin

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.

link: https://leetcode.com/problems/container-with-most-water/


public class Solution {    public int maxArea(int[] height) {         if(height == null || height.length == 0) {            return 0;        }        int max = 0;        int i = 0;        int j = height.length - 1;        while(i < j) {            max = Math.max(max, (j - i) * Math.min(height[i], height[j]));            if(height[i] <= height[j]) {//move i                int k = i + 1;                while (k < j && height[k] <= height[i]) {                    k++;                }                i = k;            } else {//move j                int k = j - 1;                while (k > i && height[k] <= height[j]) {                    k--;                }                j = k;            }        }        return max;    }}


0 0
原创粉丝点击