zoukankan      html  css  js  c++  java
  • 【LeettCode】14.Container With Most Water

    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 (i,ai) 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.

    最基础的方法 O(n2),会超时,跟最大直方图略像,但是不一样,最大直方图是至少包括一个完整的柱子,本题是有两个line决定一个面积。

    public class Solution {
        public int maxArea(int[] height) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
                
    	         Stack<Integer> stack = new Stack<Integer>();
            int i = 0;
            int j = height.length-1;
            int maxArea = 0;
            while(i < j){
                if(height[i]<height[j]){
                    maxArea = Math.max(maxArea,height[i]*(j-i));
                    i++;
                }else if(height[i]>height[j]){
                    maxArea = Math.max(maxArea,height[j]*(j-i));
                    j--;
                }else{
                    maxArea = Math.max(maxArea,height[i]*(j-i));
                    i++;
                    j--;
                }
            }
            return maxArea;
        }
    }
    

      

  • 相关阅读:
    BZOJ3512 DZY Loves Math IV
    HDU5608 function
    数论
    动态点分治
    tarjan
    插头DP
    斯坦纳树
    css中的display(显示)和visibility(可见性)
    简单的数据整理, 递归算法
    java链接数据库构建sql语句的时候容易记混的地方
  • 原文地址:https://www.cnblogs.com/guozhiguoli/p/3389599.html
Copyright © 2011-2022 走看看