iT邦幫忙

2024 iThome 鐵人賽

DAY 10
0

原文題目

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.

題目摘要

  1. 問題描述:給定 prices,選擇一天買入股票,並在未來某一天賣出股票來找出最大利潤。
  2. 輸入:一個整數陣列 prices,表示股價。
  3. 輸出:最大的利潤。

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.

解題思路

  1. 初始化變數:首先,你需要兩個變數。minPrice 用來記錄到目前為止的最低股價,maxProfit 用來記錄目前為止的最大利潤。最初可以設定 minPrice 為一個很大的值(如 Integer.MAX_VALUE),maxProfit 則設定為 0。
  2. 遍歷股價:遍歷股價陣列中的每一天。對於每一天的股價:
    • 更新最小股價:如果當前的股價比 minPrice 還低,那麼更新 minPrice 為當前的股價。
    • 計算利潤:計算當前股價與 minPrice 之間的差額,這就是在當前股價下的潛在利潤。
    • 更新最大利潤:如果這個潛在利潤大於目前的 maxProfit,那麼更新 maxProfit 為這個潛在利潤。
  3. 回傳結果:遍歷完成後,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)來決定最佳買入時機,再計算每一天的潛在利潤。這種方法就像是理性思考投資機會,避免衝動操作。在程式中,我們逐步找出最大利潤,最終讓利潤最大化,這不僅是股市操作,也是面對很多選擇時可以運用的思維:冷靜分析、步步為營。


上一篇
Day9 演算法介紹:貪婪(Greedy Algorithm)
下一篇
Day11 Greedy Algorithm題目2:55. Jump Game
系列文
Java刷題B:Leetcode Top 100 Liked13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言