题目: P7404 [JOI 2021 Final] とてもたのしい家庭菜園 4
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 200010;
typedef long long LL;
LL S[N],a[N];
LL n;
LL ans = 0;
int main()
{
cin >> n;
for(int i = 1;i <= n;i ++)
{
cin >> S[i];
a[i] = S[i] - S[i - 1];
}
LL l = 1,r = n;
while(l < r)
{
while(a[l] > 0) l ++;
while(a[r] < 0) r --;
if(l > r)
{
break;
}
else
{
LL x = min(1 - a[l],a[r] + 1);
ans += x;
a[l] += x;
a[r] -= x;
}
}
cout << ans << endl;
return 0;
}