解法
使用一个变量min
保存数组前i-1
个元素的最小值,扫描整个数组更新最小值的同时计算差值,通过打擂的方式获得最大利润。
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2) return 0;
int min = prices[0];
int maxDiff = prices[1] - min;
for (int i = 2; i < prices.length; i++) {
if (prices[i-1] < min)
min = prices[i-1];
int currentDiff = prices[i] - min;
if (currentDiff > maxDiff)
maxDiff = currentDiff;
}
return maxDiff < 0 ? 0 : maxDiff;
}
}