ORIGINAL CODING QUESTION
One inventory trade gain
Buy once and later sell once, or do nothing. Return the maximum nonnegative gain from the daily prices.
Original exercise · easy. Editorial role relevance does not imply a company has asked this question.
Input and output
n, then n integer values. Print one integer as described.
Constraints
1 ≤ n ≤ 200; 0 ≤ price ≤ 100.
Example 1
Input
6 7 1 5 3 6 4
Output
5
Buy at 1 and sell at 6 for gain 5.
Example 2
Input
3 5 4 3
Output
0
Doing nothing gives 0.
Explain your approach
Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?
Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.
Hint 1
A purchase must precede a sale.
Hint 2
Remember the cheapest earlier price.
Hint 3
Compare each current price against the minimum seen so far.
Practice this question
Save your work privately, explain decisions and return to your revision queue.
Open practice workspaceBrowse the question library →