Loading...
Loading...
A student follows one share price for n days in a paper-trading app. The price is in paise. She may buy one share on one day and sell it on a later day, at most once.
Print the largest profit she can make. If every possible trade loses money or gains nothing, she does not trade, so print 0.
0.Example 1
Input
6 7 1 5 3 6 4
Output
5
Buy on day 2 at 1 and sell on day 5 at 6, for a profit of 5.
Example 2
Input
4 9 7 5 3
Output
0
The price only falls, so the best choice is not to trade.
Try the problem first. Open one hint at a time.
Fix the selling day. Which buying day gives the best profit for it?
The best buying day is the cheapest day before the selling day.
Walk through the days once and keep the lowest price seen so far.
Prices go up to 10^12, so keep prices and profits in long variables.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor