Easy題,就不說暴力解了. 求minDiff我們控制變量叹谁,找最小被減數(shù)饲梭,差就會最大。這樣遍歷一次焰檩,一邊更新最小被減數(shù)排拷,一邊更新最大差值。
public class Solution {
/*
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
// write your code here
if (prices == null || prices.length == 0){
return 0;
}
int min = prices[0];
int maxDiff = 0;
for (int i = 1; i < prices.length; i++){
if (prices[i] < min){
min = prices[i];
} else {
maxDiff = Math.max(maxDiff, prices[i] - min);
}
}
return maxDiff;
}
}