Back to DSA

Best Time to Buy and Sell Stock

easy
Acceptance: 61%
ArraysSliding Window

An array of stock prices is provided where each entry corresponds to the price on a particular day. You may execute at most one transaction consisting of buying on an earlier day and selling on a later day. Determine the highest profit achievable from a single buy-sell pair. If no profitable trade exists, return zero.

Examples

Example 1:
Input:prices = [10,2,8,1,9,5]
Output:8
Explanation: Purchase at price 1 on day 4 and sell at price 9 on day 5 for a gain of 8.
Example 2:
Input:prices = [9,7,5,3,1]
Output:0
Explanation: Prices strictly decline, so no transaction yields a positive return.

Hints

00:00
1234567