假設某股票的價格按照時間先后順序存儲在數(shù)組中,問買賣該股票一次可能獲得的最大利潤是多少?
- 如一支股票在某段時間內(nèi)的價格為{9, 11, 8, 5, 7, 12, 16, 14}那么能在價格為5的時候購入并在價格為16時賣出,能獲得最大利潤11
轉(zhuǎn)換成求每個位置價格和之前的最小股價的最大差問題,遍歷每個位置,求出每個位置與之前位置的最大差,并記錄下最大差,每次循環(huán)還保證記錄下之前的最小值。
/**
* 掃描數(shù)組一次,時間復雜度為O(n)
* 遍歷數(shù)組,同時記錄當前數(shù)值和前面所有數(shù)值的最小值,計算并記錄最大差值
* @param prices
* @return
*/
public int getMaxDiff(int[] prices) {
if (prices == null || prices.length < 0){
return 0;
}
//最大差值和前面的最小值
int maxDiff = 0;
int min = prices[0];
for (int i=1;i<prices.length;i++){
if (prices[i-1] < min) min = prices[i-1];
int diff = prices[i]-min;
if (maxDiff < diff) maxDiff = diff;
}
return maxDiff;
}
public static void main(String[] args) {
int[] prices = {9, 11, 8, 5, 7, 12, 16, 14};
MaxDiff maxDiff = new MaxDiff();
System.out.println(maxDiff.getMaxDiff(prices));
}