Bob is planning an attack on a suspicious castle owned by the evil villain Joe! The castle can be thought of as an by grid of towers, with each tower having an integer height. To scout for this attack, Bob sent his only drone that can instantly transmit pictures to take photos of the castle. However, the drone only managed to take 2 photos before critically running out of battery and tumbling into the forest. One photo was taken of the front side of the castle, while the other captured its right side. It was also discovered (slightly too late) that the drone's camera cannot capture depth! Since Bob does not want to fail this attack, he would like to know the maximum possible volume of the castle, or if the photos are incorrect and a castle cannot be reconstructed. Can you help him find out?
Input Specification
The first line of the input will contain an integer , representing the dimensions of the castle.
The second line will contain integers , representing the height of the tallest tower in the column.
The third line will contain integers , representing the height of the tallest tower in the row.
Output Specification
A single integer, representing the maximum possible volume of the castle, or -1
if it is impossible to reconstruct a castle.
Constraints
For all subtasks:
Subtask 1 [30%]
Subtask 2 [70%]
No additional constraints.
Sample Input 1
4
1 3 4 2
2 2 1 4
Sample Output 1
28
Sample Input 2
4
1 2 6 2
5 3 3 3
Sample Output 2
-1
Explanation for Sample Output 2
No matter how you assign heights to each tower, it is impossible to reconstruct a castle that satisfies both photos.
Comments
Any hints how to optimize? I thought it would be fast enough but it's TLEing for the second last case. Edit: thank you to 4fecta and joelfu for speeding up my input, I will use this for future problems instead of scanner if needed. :) Andrew template is so convenient.
Your code looks more or less correct. Try using a faster input method such as
BufferedReader
, sinceScanner
becomes quite slow when reading in large amounts of data (around 2 million integers for this problem). More details about the syntax ofBufferedReader
can be found here.Thanks 4fecta, much appreciated.
can someone help me, I keep getting the second last case wrong.
Your multiplication on line 50 is overflowing, as mentioned below.
if you get out of memory error, then try different input stream.
Can someone take a look at my code, I am wrong answering on the second last case.
Some of your variables declared as
int
are overflowing.Thank you!
I finally got this after 3 days! This is a good problem.
I admire your persistence.
Is an by grid required to solve this problem? I am getting a memory error at the second last test case.
no, it is not necessary to create an n by n grid
i'm still stuck on the second last case... hint pls?
Your code has a time complexity of , which is too slow to pass the second subtask. Try thinking of how you can optimize your algorithm to a better complexity.