首页 > 代码库 > LeetCode: Best Time to Buy and Sell Stock [121]

LeetCode: Best Time to Buy and Sell Stock [121]

【题目】

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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.



【题意】

    给定一个数组prices, prices[i]表示第i天的股价。只允许做一次股票交易(只能一次买入,一次卖出),要求计算最大获利是多少?


【思路】

    只需要维护一个指针p,一遍扫描数组即可。 在扫描的过程中记录当前位置p之前的最小值,每到以为位置p, 就可以计算在当前位置卖出是的最大收益。与全局最大收益比较后更新即可。


【代码】

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int size=prices.size();
        if(size<=1)return 0;
        
        int maxProfit=0;
        int minPrice=INT_MAX;
        for(int i=0; i<size; i++){
            if(minPrice!=INT_MAX){
                //计算第i天卖出的最大收益
                if(prices[i]-minPrice > maxProfit) maxProfit=prices[i]-minPrice;
            }
            //更新最小股价
            if(prices[i]<minPrice)minPrice=prices[i];
        }
        return maxProfit;
    }
};