Official

C - Index × A(Continuous ver.) Editorial by en_translator


First, there are only \((N-M+1)\) contiguous subarrays of length \(M\), so we can solve the problem in a total of \(O(N^2)\) time by finding \(\displaystyle \sum_{i=1}^{M} i \times B_i\) naively for all contiguous subarrays, but it does not finish in the execution time limit.

However, since \(\displaystyle \sum_{i=1}^{M} i \times A_i-\displaystyle \sum_{i=1}^{M} i \times A_{i+1} = \left(\sum_{i=1}^{M} A_i\right)-M \times A_{M+1}\), we may compute \(\displaystyle A_1,A_1+A_2,A_1+A_2+A_3,\dots,\sum_{i=1}^{N} A_i\) in a total of \(\mathrm{O}(N)\) time, so that we may obtain \(\displaystyle \sum_{i=1}^{M} i \times A_{i+j+1}\) from \(\displaystyle \sum_{i=1}^{M} i \times A_{i+j}\) in an \(\mathrm{O}(1)\) time.

Therefore, by initially computing \(\displaystyle \sum_{i=1}^{M} i \times A_i\) in an \(\mathrm{O}(M)\) time and then using the equation above to find \(\displaystyle \sum_{i=1}^{M} i \times B_i\) for all contiguous subarrays in a total of \(\mathrm{O}(N)\) time.

All that left is to print the their maximum value. The complexity is \(\mathrm{O}(N)\).

Since the answer and the cumulative sums may be at most \(4 \times 10^{15}\), an overflow will occur if you use 32-bit integer type. Also, be sure not to let initial value \(0\) when finding the maximum value, because the answer may be negative.

Sample code (C++)

#include <bits/stdc++.h>
using namespace std;
int main(){
  int n,m;
  cin>>n>>m;
  vector<long long> a(n);
  for(int i=0;i<n;i++) cin>>a[i];
  vector<long long> sum(n+1);//sum[i] = a_1 + a_2 + ... + a_{i-1}
  for(int i=1;i<=n;i++) sum[i]=sum[i-1]+a[i-1];
  vector<long long> sumi(n-m+1);
  long long now=0;
  for(int i=0;i<m;i++) now+=a[i]*(i+1);
  sumi[0]=now;
  for(int i=1;i<n-m+1;i++) sumi[i]=sumi[i-1]+m*a[m+i-1]-(sum[m+i-1]-sum[i-1]);
  long long ans = -1000000000000000000ll;
  for(int i=0;i<n-m+1;i++) ans=max(ans,sumi[i]);
  cout<<ans<<endl;
}

posted:
last update: