Best Time to Buy and Sell Stock

Yixuan Zhou
2 min readAug 12, 2020

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [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.
Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0

Here are three solutions:

  1. Brutal Force

However, this solution exceeds time limit

2. Single Pass 1

Performance: Runtime 68ms, Memory 15.3 MB

3. Single Pass 2

Performance: Runtime 60ms, Memory 15.1 MB

Overall, the sequence of _min and _max doesn’t matter.

For solution 3, the calculation process is like:

  1. _max = max(0,7-inf)=0; _min = min(inf,7)=7
  2. _max = max(0,1–7)=0; _min = min(7,1)=1
  3. _max = max(0,5–1)=4; _min = min(1,5)=1
  4. _max = max(4,3–1)=4; _min = min(1,3)=1
  5. _max = max(4,6–1)=5; _min = min(1,6)=1
  6. _max = max(5,4–1)=5; _min = min(1,4) =1

However, the calculation process of solution 2 is different as follows:

  1. _min = min(inf,7)=7; _max = max(0, 7–7)=0
  2. _min = min(7,1)=1; _max = max(0, 1–1)=0
  3. _min = min(1,5)=1; _max = max(0, 5–1)=4
  4. _min = min(1,3)=1; _max = max(4, 3–1)=4
  5. _min = min(1,6)=1; _max = max(4, 6–1)=5
  6. _min = min(1,4)=1; _max = max(5,4–1)=5

--

--