我現在眼皮好重,但還是坐在電腦前打鐵人賽。
今天題目大意:給定一個陣列 prices,第 i 天的股票價格是 prices[i],你只能做一次買(在某天)和一次賣(之後某天),求最大利潤。如果無法獲利,回傳 0。
範例:
prices = [7,1,5,3,6,4] → 最大利潤是 5(在價格 1 買入,在價格 6 賣出)。
prices = [7,6,4,3,1] → 無法獲利,回傳 0。
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE; // 目前看到的最小買入價格
int maxProfit = 0; // 目前能取得的最大利潤
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i]; // 更新更便宜的買入價格
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice; // 更新更高的利潤
}
}
return maxProfit;
}
}