18. Best Buy-Sell Day

A collector follows the daily price of a rare trading card. She will buy exactly one card on some day and sell it on a later day, and she wants to make as much profit as possible. If no pair of days can give her a profit, she will not trade at all.

Write a method maxProfit that takes the array prices, where prices[i] is the card's price on day i, and returns the largest profit she can make, or 0 if every possible trade would lose money or break even.

Example 1

Input:
prices = [7,1,5,3,6,4]
Output:
5
Explanation:

Buy on day 1 at price 1 and sell on day 4 at price 6 for a profit of 5.

Example 2

Input:
prices = [7,6,4,3,1]
Output:
0
Explanation:

The price only falls, so any trade loses money and the answer is 0.

Constraints

1 ≤ prices.length ≤ 1000

0 ≤ prices[i] ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…