Maximum Sum of Products

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 2

output

29

input

2
13 37
2 4

output

174

input

6
1 8 7 6 3 6
5 9 6 8 8 6

output

235

Note

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值