一次遍历,不断寻找最小的那个,并每次算出最大差值,遍历完得出。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n=len(prices)
if n==0:
return 0
low,high=prices[0],0
for price in prices:
high=high if high>price-low else (price-low)
low=low if low<price else price
return high
class Solution {
public:
int maxProfit(vector<int>& prices)
{
int n=prices.size();
if(n==0) return 0;
double low=prices[0],high=0.0;
for(int i=0;i<n;i++)
{
high=high>prices[i]-low?high:(prices[i]-low);
low=low<prices[i]?low:prices[i];
}
return high;
}
};