Best Time to Buy and Sell Stock

Medium

Question

Given a list of stock prices, return the maximum profit that can be made by buying and selling a stock.

If it's not possible to make any profit, return 0.

Input: [4, 9, 2, 8, 6, 12]

Output: 10

The maximum profit that can be made is by buying the stock on the third day when the price is 2 and selling it on the last day when the price is 12, which gives a maximum profit of 10.

Input: [10, 7, 5, 3, 1]

Output: 0

It's not possible to make any profit by buying and selling the stock so the output should be 0.

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

Given the following list of prices, what is the maximum profit that can be made by buying and selling a stock? [3, 5, 1, 4, 7]
4
6
12
20

Login or signup to save your code.

Notes