All problems

Problem 647

Max Dot Product of Two Subsequences

Hard · 30 pts · Dynamic Programming

Problem

Choose a non-empty subsequence of A and a non-empty subsequence of B of the same length, and compute their dot product: the sum of products of corresponding elements. Find the largest possible dot product. Both subsequences must keep the original order. Note that when every product is negative you are still forced to pick at least one pair. Let best[i][j] be the answer using A[0..i] and B[0..j]; either pair A[i] with B[j] (adding the best earlier value only if it is positive) or skip one of them.

Input

The first line contains N and M. The second line contains A. The third line contains B.

Output

Print the maximum dot product.

Constraints

1 <= N, M <= 500; -1000 <= A[i], B[j] <= 1000

Example input

4 3
2 1 -2 5
3 0 -6

Example output

18

Explanation

With A = 2 1 -2 5 and B = 3 0 -6, choose 2 -2 from A and 3 -6 from B. Their dot product is 2 × 3 + (-2) × (-6) = 6 + 12 = 18, the largest possible.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Cherry Pickup Next: Minimum Swaps To Make Sequences Increasing