# 121. Best Time to Buy and Sell Stock

## Description

See <https://leetcode.com/problems/best-time-to-buy-and-sell-stock/>

## Solution

Pretty straight forward problem and solution. Iterate through the array looking for a lower price than the current one (which is initialized to the first element in the list). Profit is the difference between the current item and the lowest price. Keep track of the max profit.

```python
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        low_price = prices[0]
        profit = 0
        # start at 1 since element 0 is used to initialize the low_price
        for i in range(1, len(prices)):
            if prices[i] <= low_price:
                low_price = prices[i]
            else:
                profit = max(profit, prices[i] - low_price)
        return profit
```

Space O(1), Time O(N)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://monica-granbois.gitbook.io/cs-theory-and-problems/problems/leetcode/121.-best-time-to-buy-and-sell-stock.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
