假設把某股票的價格按照時間先後順序存儲在數組中,請問買賣該股票一次可能獲得的最大利潤是多少?
示例 1:
輸入: [7,1,5,3,6,4]
輸出: 5
解釋: 在第 2 天(股票價格 = 1)的時候買入,在第 5 天(股票價格 = 6)的時候賣出,最大利潤 = 6-1 = 5 。
注意利潤不能是 7-1 = 6, 因爲賣出價格需要大於買入價格。
示例 2:
輸入: [7,6,4,3,1]
輸出: 0
解釋: 在這種情況下, 沒有交易完成, 所以最大利潤爲 0。
tips: 一遍遍歷,維護一個之前最低的股價min,用當前位置的股價減去min, 得到當前賣出可以獲得的最大利潤。在此過程中維護一個maxProfit。時間複雜度O(n), 空間複雜度O(1)
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<=1) {
return 0;
}
int minBefore=prices[0];
int maxProfitNow=0;
for (int i = 1; i < prices.size(); i++)
{
if(prices[i]<minBefore) {
minBefore=prices[i];
} else if(prices[i]-minBefore>maxProfitNow){
maxProfitNow=prices[i]-minBefore;
}
}
return maxProfitNow;
}
};