Best Time to Buy and Sell Stock

IF
AlgoAxiomStaff Engineers
JSTS
Easy20 mins

Given an array prices where prices[i] is the price of a given stock on the ith day, find the maximum profit you can achieve by choosing a single day to buy and a single later day to sell.

Return the maximum profit. If no profit can be made, return 0.

Examples

Example 1:

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

Output: 5

Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

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

Output: 0

Explanation: In this case, no transactions are done and the max profit = 0.

Example 3:

Input: prices = [2,4,1]

Output: 2

Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4 - 2 = 2.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
Source: Greedy Techniques pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle