Skills101
← All coding problems

Best Time to Buy and Sell Stock

easyArrays & Hashing+10 XPTime limit 2s

prices[i] is a share's price on day i. You may buy once and later sell once (selling must happen on a later day than buying). Find the maximum profit, or 0 if no profit is possible.

Input:

  • line 1: n
  • line 2: n prices

Output: the maximum profit.

Constraints: 1 ≤ n ≤ 10⁵, 0 ≤ price ≤ 10⁴.

Think about it: walk through the days once, remembering the cheapest price so far.

Sample input 1

6
7 1 5 3 6 4

Sample output 1

5

Sample input 2

5
7 6 4 3 1

Sample output 2

0

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.