iT邦幫忙

2025 iThome 鐵人賽

DAY 13
0
生成式 AI

Chatting with ChatGPT——一天學習一題Leetcode系列 第 13

開心星期六-121. Best Time to Buy and Sell Stock

  • 分享至 

  • xImage
  •  

我現在眼皮好重,但還是坐在電腦前打鐵人賽。
今天題目大意:給定一個陣列 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;
    }
}

上一篇
美好星期五-66. Plus One
系列文
Chatting with ChatGPT——一天學習一題Leetcode13
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言