思路: 就是遍历数组,寻找 最大值 与 最小值的最优差
由于不能以现在的低价格 以 以前的高价格卖出,所以 每当最小值更新时,最大值重置为0;
class Solution {
public int maxProfit(int[] prices) {
int max = 0;
int min = Integer.MAX_VALUE;
int n = prices.length;
int ans = 0;
if(n == 0 || n == 1) return 0;
for(int i = 0 ; i < n ; i++)
{
max = Math.max(prices[i], max);
if(min > prices[i])
{
min = prices[i];//当寻找到最低值时, max必须重新这为零 因为不能以以前最高的价买
max = 0;
}
ans = Math.max(ans , max - min);
}
return ans;
}
}