Blind 75
12 / 75Free practice

Best Time to Buy and Sell Stock

Easy · Sliding window

Jump to code

Given daily prices, choose one buy day and a later sell day to maximize profit. You may make no transaction, giving profit zero.

Examples

Example 1

prices = [7,1,5,3,6,4]

Output: 5

Example 2

prices = [7,6,4,3,1]

Output: 0

Constraints

  • 1 <= prices.length <= 100
  • 0 <= prices[i] <= 100
Need a hint?

For a sale today, only the cheapest earlier price matters.

Asked in real interviews

Candidates reported versions of Best Time to Buy and Sell Stock from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 9 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    7,
    1,
    5,
    3,
    6,
    4
  ]
]
Expected
5
Case 2
Input
[
  [
    7,
    6,
    4,
    3,
    1
  ]
]
Expected
0
Case 3
Input
[
  [
    1,
    2
  ]
]
Expected
1
Case 4
Input
[
  [
    2,
    1,
    2,
    0,
    1
  ]
]
Expected
1
Case 5
Input
[
  [
    3,
    3,
    5,
    0,
    0,
    3,
    1,
    4
  ]
]
Expected
4

Drafts are saved per language in this browser when storage is available.