121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock
Photo by Mailchimp / Unsplash


You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

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.


Initial algorithm

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # we can do this with an O(n^2) algo
        # for i in prices;
            # for x in prices:
                # calculate max between i and x, and store that if its global max
                # but can we go faster?
        maxP = 0
        if len(prices) < 1:
            return maxP
        for i in range(0, len(prices)):
            for x in range(i + 1, len(prices)):
                # high take away low
                profit = prices[x] - prices[i] 
                if profit > maxP:
                    maxP = profit
        return maxP

Time limit exceed, we need some optimisations!

Solution 2

We can do something with ✨ 2 pointers  ✨

Left = buy, right = sell.

Left starts at [0], right at [1].

If left < right, we are buying low and selling high so we do not update the left pointer.

Else if its more, we move the left to the right pointer as its the cheapest option.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        l, r = 0, 1
        maxP = 0

        while r < len(prices):
            # is this profitable?
            if prices[l] < prices[r]:
                maxP = max(maxP, prices[r] - prices[l])
            # else right pointer is less than left pointer
            # so its cheaper, so we want to use it
                l = r
            # increment right
            r += 1
        return maxP