美文网首页
LeetCode每日一题:container with most

LeetCode每日一题:container with most

作者: yoshino | 来源:发表于2017-07-05 16:18 被阅读4次

    问题描述

    Given n non-negative integers a1 , a2 , ..., an , where each represents a point at coordinate (i, ai ). 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.

    问题分析

    这题的意思是,两个点到x轴的垂线和x轴组成一个桶,求这个桶最大容量。
    这题可以用贪心法来做,只要不断找容器,保存其中最大的容量即可。

    代码实现

    public int maxArea(int[] height) {
            int result = 0;
            if (height.length < 2) return 0;
            int left = 0, right = height.length - 1;
            while (left < right) {
                int area = (right - left) * Math.min(height[left], height[right]);
                if (area > result) result = area;
                if (height[left] > height[right]) right--;
                else left++;
            }
            return result;
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:container with most

          本文链接:https://www.haomeiwen.com/subject/ssuqhxtx.html