Skip to content

121. Best Time to Buy and Sell Stock

难度Easy

刷题内容

原题连接

  • 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)

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;
    }

};


回到顶部