Container With Most Water
来源:互联网 发布:git mac客户端 编辑:程序博客网 时间:2024/05/01 04:39
一、问题描述
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.
二、思路
本题难点在于理解题目。在二维坐标系中,求(i,0)(j,0)组成的线段乘以高度h组成的图形面积最大,是一道动态规划题目,我们可以采用双层for求解,但是那样显然不是最优的,我们采用两个指针,一前一后找到最大值存起来,如果当前的权值小于h,那么没必要计算,直接跳过,最后返回最大值。
三、代码
class Solution {public: int maxArea(vector<int>& height) { int water = 0; int i = 0, j = height.size() - 1; while(i < j){ int h = min(height[i],height[j]); water = max(water,(j - i) * h); while(height[i] <= h && i < j) i++; while(height[j] <= h && i < j) j--; } return water; }};
1 0
- Container With Most Water
- Container with most water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Container With Most Water
- Caffe学习笔记(二)——AlexNet模型
- todo ssh框架
- [Swift]不使用storyboard创建视图
- 百度UEditor编辑器ueditor.setContent总是报错
- javaee
- Container With Most Water
- 微信公众号01: ase实现access_token的存储和被动刷新
- node.js实现简单的网络爬虫程序
- Hust oj 2118 Friend number(递推)
- ueditor1_4_3-utf8-jsp 配置实现上传图片的功能遇到的问题,改变图片上传请求地址
- Hibernata的特点
- jdk安装
- todo 基本设计模式
- jQuery 从零开始学习 (六) 工具函数