The Bovine Accordion and Banjo Orchestra
InterviewTime limit1sMemory limit128 MB
Choose increasing pairs between two length-N sequences to maximize the sum of A_i*B_j minus the squared sums of each maximal block of unpaired elements on both sides.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Prefix sum, Math, Implementation
- Solved
- No attempts yet
Problem
There are cows () forming an orchestra: accordionists and banjoists. Accordionist has a talent level and banjoist has a talent level , where and .
Farmer John pairs accordionists with banjoists to hold concerts. Pairing accordionist with banjoist earns exactly dollars in donations.
The musicians are stubborn about their seating order, so the pairs must preserve the original order: if accordionist is paired with banjoist , then no accordionist whose index is greater than may be paired with a banjoist whose index is less than . Equivalently, if the chosen pairs are written in increasing order of accordionist index, their banjoist indices must be strictly increasing as well. As a result, some cows may have to be left unpaired.
Every unpaired cow is upset. Consider the accordionists on their own and break the unpaired ones into maximal groups of consecutive indices. A group whose talents sum to costs dollars (spent drowning their sorrows in orange soda). The same rule applies independently to the unpaired banjoists.
Formally, if accordionists through are all unpaired and form one maximal consecutive group, they cost dollars, and the identical relationship holds for banjoists.
Farmer John foots this bill, so he accounts for it when choosing the pairings. Find the maximum net profit (total donations minus total soda cost) he can achieve.
Input
- The first line contains a single integer .
- The next lines contain , one value per line.
- The following lines contain , one value per line.
Output
Print a single integer: the maximum net profit Farmer John can earn.
Notes
Worked example: suppose there are three accordionists with talents and three banjoists with talents . The best plan pairs accordionist (talent ) with banjoist (talent ), earning dollars. The two unpaired accordionists (talents and ) form one group costing dollars, and the two unpaired banjoists (talents and ) form another group costing dollars. The net profit is .
Because pairing accordionist with banjoist for every is always a valid choice, the answer is never negative. The profits and costs can be large, so 64-bit integers are required.