iT邦幫忙

2025 iThome 鐵人賽

0
自我挑戰組

Leetcode30天挑戰系列 第 24

Day24-Best Time to Buy and Sell Stock III

  • 分享至 

  • xImage
  •  

今天的題目為123.Best Time to Buy and Sell Stock III,今天是最難的版本,今天是給定一個整數陣列prices,其中prices[i]表示第i天某支股票的價格,請找出能夠獲得的最大利潤而最多可以完成兩次交易,不能同時進行多筆交易。

以下為程式碼:

class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) return 0;

        int n = prices.length;
        int[] leftProfit = new int[n]; 
        int[] rightProfit = new int[n]; 

        int minPrice = prices[0];
        for (int i = 1; i < n; i++) {
            minPrice = Math.min(minPrice, prices[i]);
            leftProfit[i] = Math.max(leftProfit[i - 1], prices[i] - minPrice);
        }

        int maxPrice = prices[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            maxPrice = Math.max(maxPrice, prices[i]);
            rightProfit[i] = Math.max(rightProfit[i + 1], maxPrice - prices[i]);
        }

        int maxTotalProfit = 0;
        for (int i = 0; i < n; i++) {
            maxTotalProfit = Math.max(maxTotalProfit, leftProfit[i] + rightProfit[i]);
        }

        return maxTotalProfit;
    }
}

今天的是最最最難的一題,需要很多不同的轉換。


上一篇
Day23-Best Time to Buy and Sell Stock II
下一篇
Day25-Binary Tree Maximum Path Sum
系列文
Leetcode30天挑戰30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言