方法一:直接遍历,时间复杂度为O(n^2)
int maxProfit(int* prices, int pricesSize) {
//直接遍历
int max = 0;
int i,j;
for(i = 0; i < pricesSize - 1; i++)
for(j = i+1; j < pricesSize; j++)
{
if(prices[j] - prices[i] > max)
max = prices[j] - prices[i];
}
return max;
}
方法二:一次遍历,min和maxprices分别表示当前位置之前的最小值及此时最大利润
int maxProfit(int* prices, int pricesSize) {
int maxprofit = 0;
int i;
int min = prices[0];
for(i = 0; i < pricesSize; i++)
{
if(min > prices[i])
min = prices[i];
else if(prices[i] - min > maxprofit)
maxprofit = prices[i] - min;
}
return maxprofit;
}
Python版:
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0
minprice = prices[0]
profit = 0
for i in range(len(prices)):
if prices[i] < minprice:
minprice = prices[i]
profit = max(prices[i] - minprice, profit)
return profit