Container With Most Water

来源:互联网 发布:淘宝客如意投推广店铺 编辑:程序博客网 时间:2024/06/05 08:26

问题:
Given n non-negative integers a1,a2...an where each represents a point at coordinate a1,a2...an 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 themost water

题意:随意找2个木板构成木桶, 容量最大

关键在于:left和right都向中央移动,每次移动left和Right中间高度较小的( 因为反正都是移动一次,宽度肯定缩小1,这时候只能指望高度增加来增加容量,肯定是替换掉高度较小的,才有可能找到更大的容量。)

#include <iostream>using namespace std;int min(int a, int b){    return a > b ? b : a;}int solution(int a[],int n){    int left = 0, right = n - 1;    int vol_max = (right - left)*min(a[right], a[left]);    int vol = 0;    while (left < right) {        if (a[left] < a[right]) left++;        else right--;        vol = min(a[left], a[right])*(right - left);        if (vol_max < vol)  vol_max = vol;    }    return vol_max;}int main(){    int a[5] = { 1,2,3,4,5 };    cout<<solution(a, 5);    return 0;}
原创粉丝点击