今天的題目為121.Best Time to Buy and Sell Stock,今天的題目為給定一個整數陣列 為prices,其中 prices[i] 表示第i天的股票價格,而你只能進行一次交易(一次買入、一次賣出),且必須在買入之後的某一天賣出,要回傳能獲得的最大利潤,如果無法獲利,回傳0。
以下為程式碼:
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int price : prices) {
if (price < minPrice) {
minPrice = price;
} else {
int profit = price - minPrice;
maxProfit = Math.max(maxProfit, profit);
}
}
return maxProfit;
}
}
我覺得今天的題目非常好,非常貼近生活!