Loading...
Loading...
Nikhil is testing a game where each level changes the score multiplier. Level i multiplies the score by a[i], which can be negative or zero.
He may play any stretch of levels that are next to each other, with at least one level. Print the largest product of the numbers in such a stretch.
long.Example 1
Input
4 2 3 -2 4
Output
6
The stretch 2 3 gives 6. Any stretch with the -2 is negative.
Example 2
Input
3 -2 3 -4
Output
24
The whole line gives 24, because the two negatives cancel out.
Try the problem first. Open one hint at a time.
A negative number turns the largest product into the smallest one, and the smallest into the largest.
So for each position i keep two values: the largest and the smallest product of a stretch that ends at i.
Each of them is the best of three choices: a[i] alone, a[i] times the largest before it, or a[i] times the smallest before it.
The answer is the largest "ends here" value over every position. Start it from a[1], not from 0.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor