# 121. Best Time to Buy and Sell Stock

**<font color=red>难度Easy<font>**

## 刷题内容
> 原题连接

* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/

> 内容描述

```


Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.
```

> 思路
******- 时间复杂度: O(n)*****- 空间复杂度: O(1)******
直接遍历数组，每次记录最小值，若此时的price大于最小值，就比较```min(ans,prices[i] - min)```
```cpp
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int min1 = INT_MAX;
        int ans = 0;
        for(int i = 0;i < prices.size();++i)
            if(prices[i] > min1)
                ans = max(ans,prices[i] - min1);
            else
                min1 = prices[i];
        return ans;
    }
                
};
```