> [!META]- Inline Metadata > [tags:: #career #concepts/programming/algorithms/two-pointers ] > [project group:: Neetcode 150] > [difficulty:: easy] > [status:: done] > [link:: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solutions/127440/best-time-to-buy-and-sell-stock/] > [up:: [[Leetcode MOC]]] ## Problem 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. **Constraints:** - `1 <= prices.length <= 105` - `0 <= prices[i] <= 104` ## Solution ### Mine #### Python ```python class Solution: def maxProfit(self, prices: List[int]) -> int: max_profit = 0 for idx, price in enumerate(prices[:-1]): max_profit = max(max_profit, max(prices[idx+1:]) - price) return max_profit ``` This solution fails on very long input. The two-pointer solution does not: ```python class Solution: def maxProfit(self, prices: List[int]) -> int: max_profit = 0 l = 0 r = 1 while r < len(prices): profit = prices[r] - prices[l] if profit < 0: l = r r += 1 else: max_profit = max(profit, max_profit) r += 1 return max_profit ``` #### Rust ### Neetcode's #### Python ```python def maxProfit(self, prices: List[int]) -> int: l, r = 0, 1 max_p = 0 while r < len(prices): if prices[l] < prices[r]: profit = prices[r] - prices[l] max_p = max(max_p, profit) else: l = r r += 1 return max_p ``` ## Things I Learned ## Scratchpad For each number, take the sub-list of those after it, find the max. If the difference is greater than existing profit, replace it. ### Neetcode Use two-pointer. If L > R, then move L and R forward. If not, then check profit against max profit. Either way, move just R forward. This allows us to do it in one pass. Memory: $O(1)$ Time: $O(n)$