# 121. Best Time to Buy and Sell Stock

![](/files/-Mf1DCkKly8pDlh7oVZ2)

![](/files/-Mf1DFMklHM9JOxAR2Gm)

this one: buy one, sell once, so we focus on max profit!

time: O(n)

space: O(1)

```java
class Solution {
    public int maxProfit(int[] prices) {
        // so find min, in the same loop, because profit gen after chosing min 
        // and find max profit = price - min
        
        int min = Integer.MAX_VALUE;
        int profit = 0;
        for (int price : prices) {
            if (min > price) {
                min = price;
            }
            if (price - min > profit) {
                profit = price - min;
            }
        }
        return profit;
    }
}
```

```java
class Solution {
    public int maxProfit(int[] prices) {
        int min = Integer.MAX_VALUE;
        int res = 0;
        for (int price : prices) {
            min = Math.min(min, price);
            res = Math.max(res, price - min);
        }
        return res;
    }
}

/*
[7,1,5,3,6,4]
   m     o
   
[7,1,7,3,2,7]   
*/
```

## dp

time: O(n)

space: O(n)

```java
class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int dp[][] = new int[n][2];
        
        // dp means max profit
        dp[0][0] = 0; // no stock
        dp[0][1] = -prices[0]; // has stock
        
        for (int i = 1; i < prices.length; i++) {
            // 1. keep no stock  2. has stock and sell
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]); 
            
            // only one sell, so we buy only once, 
            // only dp[0][0] can represent no stock!
            dp[i][1] = Math.max(dp[0][0] - prices[i], dp[i-1][1]);
        }
        return dp[n-1][0];
    }
}
```


---

# 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://timmybeeflin.gitbook.io/cracking-leetcode/dynamic-programming/stock-tips/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.
