思路
维护股票的最低价格和最高利润即可。
AC代码
C++
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
int minx = prices[0];
int profit = 0;
for(int i = 0; i < len; ++i){
profit = max(profit, prices[i]-minx);
minx = min(minx,prices[i]);
}
return profit;
}
};
Python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
length = len(prices)
profit = 0
minx = prices[0]
for i in range(length):
profit = max(profit, prices[i]-minx)
minx = min(minx, prices[i])
return profit