根据题目意思,我们需要找到数组中两个元素之间差值的最大值,即需要找到数组中的最大值和最小值。
最简单的方法是使用两个 for 循环,枚举所有的买入和卖出日期。时间复杂度为 O(n^2)。
但是,我们可以使用一次扫描来避免这种情况。我们可以使用一个变量 minPrice 来保存前 i - 1 个数的最小值,再用当前元素减去 minPrice,更新最大收益 maxProfit。时间复杂度为 O(n)。
具体代码实现如下:
class Solution { public int maxProfit(int[] prices) { int minPrice = Integer.MAX_VALUE; int maxProfit = 0; for (int i = 0; i < prices.length; i++) { if (prices[i] < minPrice) { minPrice = prices[i]; } else if (prices[i] - minPrice > maxProfit) { maxProfit = prices[i] - minPrice; } } return maxProfit; } }