Problem P22. [算法课贪婪]盛最多的水

维持左右两个指针,可以知道,当左边比右边低的时候,移动右边的指针往左边靠近,即便指针指向一个更高的高度,能装的水也只会减少,因为底边减小,但是木桶原理,最低高度不变,所以这时候应该移动左边的指针寻找高于右边的高度。

#include<iostream>
#include<bits/stdc++.h>
#include<cstdio>
#include<string>

using namespace std;
vector<int> height;
int main()
{
    while(1){
        int h;
        int ret = scanf("%d", &h);
        if (ret == EOF){
            break;
        }
        height.push_back(h);
    }
    int left = 0, right = height.size()-1;
    int maxVolume = 0;
    while(right>left){
        int curVolume = min(height[left], height[right])*(right-left);
        maxVolume = max(curVolume, maxVolume);
        if (height[left]>height[right]){
            right--;
        }else {
            left++;
        }
    }
    cout << maxVolume;
    return 0;
}

posted @   白缺  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示