class Solution {
public int maxProfit(int[] prices) {
//特殊情况
if (prices.length == 0){
return 0;
}
int min = Integer.MAX_VALUE;
int max = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < min) {
min = prices[i];
} else {
max = Math.max(max, prices[i] - min);//递推式:历史低价买入当前卖出与之前的最大收益相比
}
}
}
}
共以下 3 个回答
定义一个变量存储i前面的最小值
时间复杂度O(n);空间复杂度O(1)