A freight dispatcher has a manifest listing n cargo pallets in a single row; each pallet carries a declared value (a positive value represents profit, a negative value represents a handling penalty for damaged goods). Before loading the truck the dispatcher may permanently delete any number of pallets from the row -- each deletion removes exactly one pallet and the remaining pallets slide together into an unbroken row. Once finished deleting, the dispatcher must load one contiguous stretch of whatever row remains (possibly the whole remaining row, or nothing at all), subject to a single rule: no two pallets loaded onto the truck may carry the same declared value. Determine the greatest total declared value the dispatcher can load onto the truck.
The first line contains an integer n. The second line contains n space-separated integers, the declared values of the pallets in their original left-to-right order.
Print a single integer: the maximum total declared value that can be loaded onto the truck (0 if loading nothing is the best option).
Example 1
Input
5 1 2 3 4 5
Expected
15
Explanation
Every pallet already carries a distinct positive value, so the dispatcher deletes nothing and loads the entire row, for a total of 1+2+3+4+5=15.
Example 2
Input
5 3 -1 3 -1 4
Expected
7
Explanation
Value 3 appears twice, but since every occurrence of a given value is identical it can only ever be loaded once; value -1 appears twice and is never worth loading since it is negative; value 4 appears once and is positive. So the dispatcher deletes both copies of -1 and one of the two 3's, keeping a single 3 and the 4, for a total of 3+4=7.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →