# 121. Best Time to Buy and Sell Stock

### Leetcode

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

### 題目

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`.

&#x20;

**Example 1:**

<pre><code><strong>Input: prices = [7,1,5,3,6,4]
</strong><strong>Output: 5
</strong><strong>Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
</strong>Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
</code></pre>

**Example 2:**

<pre><code><strong>Input: prices = [7,6,4,3,1]
</strong><strong>Output: 0
</strong><strong>Explanation: In this case, no transactions are done and the max profit = 0.
</strong></code></pre>

### 解答 <a href="#ti-jie" id="ti-jie"></a>

* **方法一**

只需要紀錄兩個指標，就可以算出最大的獲利

1. 過去最小的買進價格 `min`
2. 目前為止可以得到的最大獲利 `profit`

```javascript
var maxProfit = function(prices) {
    let min = Number.MAX_SAFE_INTEGER;
    let profit = 0;

    for(let i=0; i<prices.length; i++) {
        const price = prices[i];

        if (price < min) {
            min = price;
        }
        if (price - min > profit) {
            profit = price - min;
        }
    }

    return profit;
};
```

Runtime: 64 ms Beats 92.33% of users with JavaScript

Memory: 59.34 MB Beats 17.92% of users with JavaScript

* **方法二 - 雙指針**

`min` 紀錄最低價

`left` 紀錄最低價時的 index

`right` 一直往右移動，當 `right` 遇到的價格低於 `min` 時，重設 `min` 與 `left` 的值

```javascript
var maxProfit = function (prices) {
    const length = prices.length;
    if (length === 1) return 0;

    let left = 0;
    let right = 1;
    let profit = 0;
    let min = prices[left];

    while(right !== length) {
        const lastPrice = prices[left];
        const todayPrice = prices[right];

        if (todayPrice - lastPrice > profit) {
            profit = todayPrice - lastPrice;
        }
        if (todayPrice < min) {
            left = right;
            min = prices[left];
        }
        right++;
    }

    return profit;
};
```

Runtime: 56 ms Beats 99.03% of users with JavaScript

Memory: 58.56 MB Beats 44.47% of users with JavaScript

**參考資料**

{% embed url="<https://weikaiwei.com/algorithm/leetcode-121/>" %}
