
代码实现
cpp
typedef long long ll;
const int N = 2e5 + 10; // 因为要拼接数组,所以长度翻倍
ll a[N], tmp, ret;
int main()
{
int n; cin >> n;
ll circ = 0;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
circ += a[i];
a[i + n] = a[i]; // 拼接数组,处理环形
}
int l = 1;
tmp = 0, ret = 0;
for (int r = 1; r <= 2 * n; r++) // 遍历到2n
{
tmp += a[r];
// 当当前和超过半周长时,从左边移出元素
while (tmp > circ / 2)
{
tmp -= a[l];
l++;
}
// 更新最大的最近距离
ret = max(ret, tmp);
// 防止窗口长度超过n(即绕回一圈以上)
if (r - l + 1 > n)
{
tmp -= a[l];
l++;
}
}
cout << ret << endl;
}
cpp
typedef long long ll;
const int N = 1e5 + 10;
ll a[N], tmp, ret;
int main()
{
int n; cin >> n;
ll circ = 0;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
circ += a[i];
}
int l = 1, r = 1;
while (r <= n)
{
// 入窗口
tmp += a[r];
// 判断
while (tmp * 2 > circ)
{
ret = max(ret, circ - tmp);
// 出窗口
tmp -= a[l];
l++;
}
// 更新结果
ret = max(ret, tmp);
r++;
}
cout << ret << endl;
}