> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/dynamic-programming/stock-tips/121.-best-time-to-buy-and-sell-stock.md).

# 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];
    }
}
```
