Leetcode 贪心 container with most water

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Container With Most Water

  Total Accepted: 15241  Total Submissions: 48936 My Submissions

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.



题意:二维坐标系里有 n 个点 (i, ai), ai >= 0,从 (i, ai)到(i, 0)划竖线,共有 n 条竖线。
找出两条竖线,使得它们构成的矩形的面积最大,矩形的高取决于最短的竖线。
思路:贪心
从首尾两个下标head 和trail 处开始扫描,用一个变量 maxArea 保持当前最大的矩形面积。
如果head 指向的竖线短于 trail 的,则右移 head
否则左移 trail
计算面积,更新 maxArea
复杂度:时间O(n),空间O(1)


int maxArea(vector<int> &height){
	if(height.size() < 2) return 0;
	int maxArea = min(height.front(), height.back()) * ( height.size() - 1);
	for(int head = 0, trail = height.size() - 1; head < trail; ){
		if(height[head] < height[trail]) head++;
		else trail--;
		int newArea = min(height[head], height[trail]) * (trail - head);
		maxArea = max(maxArea, newArea);
	}
	return maxArea;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值