---
# System prepended metadata

title: 121. Best Time to Buy and Sell Stock
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
::-webkit-scrollbar {
    width: 10px;
}
::-webkit-scrollbar-track {
    background: transparent;
}
::-webkit-scrollbar-thumb {
    background: linear-gradient(180deg, #2BE8CF60 0%, #2B83E860 100%);
    border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(180deg, #2BE8CF95 0%, #2B83E895 100%);
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}
   
</style>

###### tags: `Leetcode`

# 121. Best Time to Buy and Sell Stock


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

## 題目
找到最大獲利(選一天買，選之後的某天賣)
## 程式碼

```cpp=
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int diff = 0, Min = prices[0];
        for(int i = 1;i < prices.size();++i){
            if(diff < prices[i] - Min){
                diff = prices[i] - Min;
            }
            Min = min(Min, prices[i]);
        }
        return diff;
    }
};
```