1. 采用双指针
如果前面的数值比后面的大 那么就需要舍弃这个数值 直接从下一个开始遍历
代码如下:
public int maxProfit(int[] prices) {
//双指针法
if (prices == null || prices.length == 0 || prices.length == 1) {
return 0;
}
int length = prices.length;
int max = 0;
for (int i = 0; i < length; ) {
for (int j = i + 1; j < length; ) {
int x = prices[i];
int y = prices[j];
if (x < y) {
max = Math.max(max,y-x);
j++;
} else {
break;
}
}
i++;
}
return max;
}