LeetCode每日一题:container with most

2017-07-05  本文已影响4人  yoshino

问题描述

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;
    }
上一篇下一篇

猜你喜欢

热点阅读