/121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

Easy
Arrays56.5% acceptance

Given an integer array stock_prices where stock_prices[i] represents the price of a stock on day i, determine the maximum possible profit from a single buy-sell transaction. The buy must occur before the sell. Return 0 if no profit is possible.

Example 1

Input: [8, 3, 6, 2, 7, 5]

Output: 5

Explanation: Buy at 3 (day 1), sell at 8 (day 0) is not allowed. Buy at 2 (day 3), sell at 7 (day 4): profit = 7-2 = 5.

Example 2

Input: [9, 8, 7, 6, 5]

Output: 0

Explanation: Prices decrease every day, so no profit is possible.

Constraints

  • 1 <= len(stock_prices) <= 100000
  • 0 <= stock_prices[i] <= 10000
Python (current runtime)

Case 1

Input: [2, 4, 1, 8, 3]

Expected: 7

Case 2

Input: [5, 5, 5, 5, 5]

Expected: 0

Case 3

Input: [1, 2, 3, 4, 5]

Expected: 4

Case 4

Input: [10, 2, 5, 1, 6]

Expected: 5

Case 5

Input: [3, 2, 6, 1, 4]

Expected: 4