转换二维变量:将i和j,转化为,h和l,即最高和最低价格的下标,其中必须满足h >= l。
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
if (prices == null || prices.length <= 1) return 0;
int h = 0,l = 0;//最高和最低点的价格的下标,必须满足h >= l
int max = 0;
for (int i = 1; i < prices.length; i++) {
int p = prices[i];
if (p > prices[h]){
h = i;
max = prices[h] - prices[l];
}
else if (p < prices[l]){
l = i;
h = i;
}
}
return max;
}
}