Applied AI Engineer (LLM) coding learning path Level 1 This level · 7 of 9

Best Time to Buy and Sell Stock

Easy Single pass

Problem

Given daily prices, choose one day to buy and a later day to sell to maximise profit, or return 0 if no profit is possible.

Original: LeetCode 121: Best Time to Buy and Sell Stock.

Examples

Example 1

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

Example 2

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

Example 3

Input`prices = [5]`
Output`0`

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 121: Best Time to Buy and Sell Stockleetcode.com
  2. Java SE 17 API: Mathdocs.oracle.com
Previous
Next