题目要求:
分析:
这道题目就是要先找到最小值,然后从最小值之后找最大值。那么我们可以这样考虑:
设置一个变量min,让它指向prices[0],再定义一个变量max,用来存放最大值(当前值 - 当前min值),然后遍历这个数组:
- 一旦碰到比min更小的值,就令min等于这个值,然后继续遍历;
- 如果遍历到的值比当前的min值大,就求这个值与min值的差值,如果这个max比之前的max要大,则更新这个max值;
- 遍历完之后,返回max即可。
具体代码如下:
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0)
return 0;
int min = prices[0];
int max = 0;
for(int i = 0; i < prices.length; i ++) {
if(prices[i] < min) {
min = prices[i];
} else {
if(max < prices[i] - min) {
max = prices[i] - min;
}
}
}
return max;
}
}