方法1:一次遍历
时间复杂度:$O(n)$
空间复杂度:$O(1)$
解题思路
Java 代码
class Solution {
public int maxProfit(int[] prices) {
//假设已经确定minPrice,遍历卖出的价格,不断更新minPrice即可
int minPrice = Integer.MAX_VALUE;
int maxprofit = 0;
int len = prices.length;
for (int i = 0; i < len; i ++) {
if (prices[i] < minPrice)
minPrice = prices[i];
if ((prices[i] - minPrice) > maxprofit)
maxprofit = prices[i] - minPrice;
}
return maxprofit;
}
}