You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
題目摘要
prices,選擇一天買入股票,並在未來某一天賣出股票來找出最大利潤。prices,表示股價。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.
解題思路
minPrice 用來記錄到目前為止的最低股價,maxProfit 用來記錄目前為止的最大利潤。最初可以設定 minPrice 為一個很大的值(如 Integer.MAX_VALUE),maxProfit 則設定為 0。minPrice 還低,那麼更新 minPrice 為當前的股價。minPrice 之間的差額,這就是在當前股價下的潛在利潤。maxProfit,那麼更新 maxProfit 為這個潛在利潤。maxProfit 就是你能獲得的最大利潤。如果 maxProfit 小於 0,表示沒有利潤可言,你可以回傳 0。程式碼
class Solution {
    public int maxProfit(int[] prices) {
		    //也可將minPrice設定為第一天的價格下去比較
        int minPrice = Integer.MAX_VALUE;
        int maxProfit=0;
        //如果當前股價比minPrice還低,更新minPrice
        for(int i=0; i<prices.length; i++){
            if(prices[i]<minPrice){
                minPrice=prices[i];
            }
            int nowProfit=prices[i]-minPrice; //計算當前股價減去minPrice的差額
            //如果差額比maxProfit還高,更新maxProfit
            if(nowProfit>maxProfit){
                maxProfit=nowProfit;
            }
        }
        //如果maxProfit小於0,回傳0;否則,回傳maxProfit
        return maxProfit<0 ? 0 : maxProfit;
    }
}
結論: 這題「最佳買賣股票時機」其實跟我們生活中的理財抉擇很像。要在低點買進、高點賣出,才能賺取最大利潤。不過,現實中我們無法預知未來價格,這題的解法也是一樣的道理。我們只能透過不斷追蹤過去的最低價(minPrice)來決定最佳買入時機,再計算每一天的潛在利潤。這種方法就像是理性思考投資機會,避免衝動操作。在程式中,我們逐步找出最大利潤,最終讓利潤最大化,這不僅是股市操作,也是面對很多選擇時可以運用的思維:冷靜分析、步步為營。