You are given two integer arrays aa and bb of length nn.
You can reverse at most one subarray (continuous subsegment) of the array aa.
Your task is to reverse such a subarray that the sum ∑i=1nai⋅bi∑i=1nai⋅bi is maximized.
Input
The first line contains one integer nn (1≤n≤50001≤n≤5000).
The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).
The third line contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1071≤bi≤107).
Output
Print single integer — maximum possible sum after reversing at most one subarray (continuous subsegment) of aa.
Examples
input
5 2 3 2 1 3 1 3 2 4 2output
29input
2 13 37 2 4output
174input
6 1 8 7 6 3 6 5 9 6 8 8 6output
235Note
In the first example, you can reverse the subarray [4,5][4,5]. Then a=[2,3,2,3,1]a=[2,3,2,3,1] and 2⋅1+3⋅3+2⋅2+3⋅4+1⋅2=292⋅1+3⋅3+2⋅2+3⋅4+1⋅2=29.
In the second example, you don't need to use the reverse operation. 13⋅2+37⋅4=17413⋅2+37⋅4=174.
In the third example, you can reverse the subarray [3,5][3,5]. Then a=[1,8,3,6,7,6]a=[1,8,3,6,7,6] and 1⋅5+8⋅9+3⋅6+6⋅8+7⋅8+6⋅6=2351⋅5+8⋅9+3⋅6+6⋅8+7⋅8+6⋅6=235.
思路是DP
dp[i][j] 是i到j间所有的数全部逆转后的和。
dp[i][j] = dp[i+1][j-1] + a[l]*b[r]+a[r]*b[l]
- 当j-i = 0时:区间长度为1,dp[i][j]就等于当前数的乘积。
- 当j-i = 1时:区间长度为2时,dp[i][j] 就等于两个端点交换后的成积和。
- 当j-i = 2时:区间长度为3时,dp[i][j] = 两端交换后的两端端点乘积 + 中间一个数逆转(即原来的数)后的乘积。
- 当j-i = 3时:区间长度为4时,dp[i][j] = 两端交换后的两端端点乘积 + 中间两个数逆转(之前已经求过)后的乘积。
举例 :1 2 3 4 5逆转方式为:1和5逆转+ [2,4]一整个区间的逆转。
由于区间长度是由小到大的,所以保证了中间的区间逆转一定已经求过。
#include<bits/stdc++.h>
#define rep(i,a,b) for(int i = a;i <= b;++i)
#define int long long
using namespace std;
const int N = 2e5+10;
int sum[5010];
int dp[5050][5050];
int a[5050],b[5050];
signed main(){
int n; cin >> n;
rep(i,1,n) cin >> a[i];
rep(i,1,n) {
cin >> b[i];
dp[i][i] = a[i]*b[i];
sum[i] = a[i]*b[i] + sum[i-1];
}
int maxn = sum[n];
int l,r;
rep(len,2,n){
rep(i,1,n-len+1){
int l = i,r = i + len -1;
dp[l][r] = dp[l+1][r-1]+a[l]*b[r]+a[r]*b[l];
maxn=max(maxn,dp[l][r]+sum[l-1]+sum[n]-sum[r]);
}
}
cout << maxn << endl;
return 0;
}