Buy Low, Sell High: Intuitive Single-Pass Solution with O(n) Time Complexity 🚀
IntuitionWhen I first read this problem, I thought, Wow, this looks tough! But then I realized: it’s all about timing. The key insight is to buy low and sell hi
# Intuition
When I first read this problem, I thought, *Wow, this looks tough*! But then I realized: it’s all about timing. The key insight is to buy low and sell high, which sounds simple in theory, but how do you do it with just one pass through the data?
I thought, *What if I keep track of the lowest price (buy) as I move through the array?* That way, I can calculate the profit for each day and keep track of the maximum profit. Like spotting a discount at the store—grab it when it’s cheap, and rejoice later when the value goes up! 😆

# Approach
1. **Track the Cheapest Price:** Start by assuming the first day's price is the lowest (buy), then iterate through the array to update it whenever a new low is found.
1. **Calculate Profit:** For each price, calculate the profit if we were to sell at that price (i.e., price - buy).
1. **Update Maximum Profit:** If this calculated profit is higher than our current max_profit, update it.
1. **Return the Result:** Once the loop ends, the max_profit variable will hold the best profit achievable. If no profit is possible (prices always go down), it naturally remains 0.

# Complexity
- Time complexity:
The algorithm makes a single pass through the array of size $$n$$. Thus, the time complexity is: $$O(n)$$

- Space complexity:
We use only two extra variables (buy and max_profit), so the space complexity is: $$O(1)$$
# Code
```python []
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        
        max_profit = 0
        buy = prices[0]
        for i in range(1,len(prices)):
            if prices[i]<buy:
                buy = prices[i]

            profit = prices[i]-buy
            max_profit = max(profit,max_profit)

        return max_profit
```
✨ If you found this explanation helpful or enjoyed the little analogies, please consider giving it an upvote! ✨


['Python']