iT邦幫忙

2025 iThome 鐵人賽

0
自我挑戰組

Leetcode30天挑戰系列 第 23

Day23-Best Time to Buy and Sell Stock II

  • 分享至 

  • xImage
  •  

今天的題目為122.Best Time to Buy and Sell Stock II,這次的題目為前一題的衍生,給一個整數陣列prices,其中prices[i]表示第i天某支股票的價格。你每天都可以選擇買入和/或賣出股票,但你最多只能持有一股股票。你可以在同一天賣出後再買入,只要你在任何時刻都不持有超過一股股票,找出你能夠獲得的最大利潤。

以下為程式碼:

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) {
                profit += prices[i] - prices[i - 1];
            }
        }
        return profit;
    }
}

上一篇
Day22-Best Time to Buy and Sell Stock
下一篇
Day24-Best Time to Buy and Sell Stock III
系列文
Leetcode30天挑戰30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言