203. Best Time to Buy and Sell Stock

Easy
Running Minimum
Array

Problem

You are given an array prices where prices[i] represents the price of a stock on the ith day. You want to maximize your profit by choosing one day to buy one stock and choosing a later day to sell that stock. Return the maximum profit you can achieve. If no profit can be achieved, return 0.

Examples

Example 1

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

Buy at price 1 and sell at price 6.

Example 2

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

No profitable transaction is possible.

Constraints

1 <= prices.length <= 10⁵

0 <= prices[i] <= 10⁴

Hints

?? Track the lowest price seen so far.

?? At each day, calculate the profit if you sold today.

?? Keep the maximum profit seen.

Expected Complexity
Time: O(n)
Space: O(1)
Follow-up

Can you solve the problem in one pass using O(1) extra space?

Practice Notes

Attempts: 0

Time spent: 0min

Hints used: 0

00:00
Loading...
Case 1
Case 2
Case 3
Input
[7,1,5,3,6,4]
Expected
5