容器盛水问题

容器盛水问题

题目描述

给定一个整形数组arr,已知其中所有的值都是非负的,将这个数组看作一个容器,请返回容器能装多少水。

具体请参考样例解释

输入描述:

第一行一个整数N,表示数组长度。

接下来一行N个数表示数组内的数。

输出描述:

输出一个整数表示能装多少水。

示例1
输入
6
3 1 2 5 2 4
输出
5
说明

在这里插入图片描述

示例2
输入
5
4 5 1 3 2
输出
2
备注:

1 ⩽ N ⩽ 1 0 6 1 \leqslant N \leqslant 10^6 1N106
1 ⩽ a r r i ⩽ 1 0 9 1 \leqslant arr_i \leqslant 10^9 1arri109


题解:

此题可以从两个角度进行思考,竖着和横着考虑:

解法一(竖着):

这种解法就是考虑每个位置上能放几格水,比如示例1中位置1,左侧最大值为3,右侧最大值为5,所以其能放2格水。这种解法在每个位置i上方能放的水的数量为:max{ min{ i 左侧的最大值,i右侧的最大值} - arr[i], 0},使用双指针即可。

解法一代码:
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

typedef long long LL;

int main(void) {
    int n;
    scanf("%d", &n);
    if ( n < 3 ) return 0 * puts("0");
    vector<int> a(n);
    for ( int i = 0; i < n; ++i )
        scanf("%d", &a[i]);
    int lmax = a[0], rmax = a[n - 1];
    int l = 1, r = n - 2;
    LL ret = 0;
    while ( l <= r ) {
        if ( lmax < rmax ) {
            ret += max( 0, lmax - a[l] );
            lmax = max( lmax, a[l++] );
        } else {
            ret += max( 0, rmax - a[r] );
            rmax = max( rmax, a[r--] );
        }
    }
    return 0 * printf("%lld\n", ret);
}
解法二(横着):

考虑每个位置一个格子往左往右能延伸到什么地方,对长度进行累加即可。此时可以使用单调栈。

解法二代码:
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

typedef long long LL;

int main(void) {
    int n;
    scanf("%d", &n);
    if ( n < 3 ) return 0 * puts("0");
    vector<int> a(n);
    vector<int> stk;
    LL ret = 0;
    for ( int i = 0; i < n; ++i ) {
        scanf("%d", &a[i]);
        while ( stk.size() && a[stk.back()] < a[i] ) {
            int now = stk.back();
            stk.pop_back();
            if ( stk.size() ) ret += 1LL * ( i - stk.back() - 1) * ( min( a[i], a[stk.back()] ) - a[now] );
        }
        stk.push_back( i );
    }
    return 0 * printf("%lld\n", ret);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值