Best Time to Buy and Sell Stock - aloalgo

Best Time to Buy and Sell Stock

Easy

You are given an array of numbers, prices, where prices[i] is the price of a stock on day i.

Your task is to calculate the maximum profit achievable by buying a stock on one day and selling it on a subsequent day.

Note that:

  • You must sell the stock on a day strictly after you buy it.

Return the maximum profit possible. If no profit can be made, return 0.

Example 1

Input
[5, 3, 8, 6, 7, 11]
Output
8
Explanation:

Buy on day 1 at price 3 and sell on day 5 at price 11 for a maximum profit of 8.

Example 2

Input
[10, 15, 4, 16, 12]
Output
12
Explanation:

Buy on day 2 at price 4 and sell on day 4 at price 16 for maximum profit of 12.

Example 3

Input
[1, 7, 5, 10, 6]
Output
9
Explanation:

Buy on day 0 at price 1 and sell on day 3 at price 10 for maximum profit of 9.

Example 4

Input
[20, 18, 15, 12, 10]
Output
0
Explanation:

All prices decrease, so no profit can be made.

Example 5

Input
[8, 2, 5, 10, 12, 16, 7]
Output
14
Explanation:

Buy on day 1 at price 2 and sell on day 5 at price 16 for maximum profit of 14.

Loading...
Input
[5, 3, 8, 6, 7, 11]
Output
8

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!