/121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

Easy
Arrays56.5% acceptance

Given an integer array price_history where price_history[i] represents the price of an asset at time index i, determine the maximum possible profit from a single buy-sell transaction. The buy must occur before the sell. Return the maximum profit, or 0 if no profit is possible.

Example 1

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

Output: 8

Explanation: Buy at index 1 (price 2), sell at index 4 (price 9), profit = 9 - 2 = 7. But buying at index 0 (price 3) and selling at index 2 (price 8) gives profit = 8 - 3 = 5. The best is buy at index 3 (price 1), sell at index 4 (price 9), profit = 8.

Example 2

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

Output: 0

Explanation: Prices decrease, so no profit is possible.

Example 3

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

Output: 4

Explanation: Buy at index 0 (price 1), sell at index 4 (price 5), profit = 4.

Constraints

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

Case 1

Input: [10, 7, 5, 8, 11, 9]

Expected: 6

Case 2

Input: [2, 2, 2, 2, 2]

Expected: 0

Case 3

Input: [9, 1, 10, 2, 11]

Expected: 10

Case 4

Input: [1, 10000]

Expected: 9999

Case 5

Input: [10000, 1]

Expected: 0