Skip to main content

Best Time to Buy and Sell Stock - Challenge

Best Time to Buy and Sell Stock

Easy
Problem
You are given an array prices where prices[i] is the price of a stock on day i. Pick one day to buy and a later day to sell to maximize profit. Return the maximum profit; return 0 if no profit is possible.
Constraints
  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
  • Must buy before you sell; only one transaction allowed.
Sample Tests
Test 1
Input
prices = [7, 1, 5, 3, 6, 4]
Expected
5

Buy at 1 (day 1), sell at 6 (day 4).

Test 2
Input
prices = [7, 6, 4, 3, 1]
Expected
0

No profitable buy-sell pair exists.

Test 3
Input
prices = [9, 1, 2, 10]
Expected
9

Best is buy at 1, sell at 10.

Console

Run tests to see verdicts.