題目:
給一個股價序列,求一次買入和賣出可以得到的最大利潤
範例:
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
想法:
最大利潤 = 最便宜的買入點 + 最高的賣出點(在買入日之後)
邊走陣列邊更新數值
程式碼:
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE; //初始為最大值
int maxProfit = 0; //初始利潤0
for (int price : prices) { //走訪每天股價
if (price < minPrice) { //若遇到更低股價 → 更新買入價
minPrice = price;
} else if (price - minPrice > maxProfit) { //計算今天賣的利潤
maxProfit = price - minPrice; //若利潤更高 → 更新最大利潤
}
}
return maxProfit;
}
}
實際操作:
prices = [7, 1, 5, 3, 6, 4]
STEP1:
minPrice = 7
profit = 7-7=0
maxProfit = 0
STEP2:
minPrice = 1 (遇到更低價)
profit = 1-1=0
maxProfit = 0
STEP3:
minPrice = 1
profit = 5-1=4
maxProfit = 4 (更新)
STEP4:
minPrice = 1
profit = 3-1=2
maxProfit = 4 (不變)
STEP5:
minPrice = 1
profit = 6-1=5
maxProfit = 5 (更新)
STEP6:
minPrice = 1
profit = 4-1=3
maxProfit = 5 (不變)
最終 maxProfit = 5