iT邦幫忙

1

自主學習30日-LeetCode 121.Best Time to Buy and Sell Stock

  • 分享至 

  • xImage
  •  

121.Best Time to Buy and Sell Stock

題目描述

給你一個整數陣列 prices,其中 prices[i] 表示某支股票第 i 天的價格。
你只能 買一次、賣一次,請設計一個演算法找出 能獲得的最大利潤。

解題思路

我們希望找到 一個最小買入價格和 一個最大賣出價格(且賣出時間晚於買入時間)

一次遍歷即可:

  1. 用變數 minPrice 記錄到目前為止的最低價格

  2. 用變數 maxProfit 記錄最大利潤

  3. 每次遍歷:

更新 minPrice = Math.min(minPrice, prices[i])

更新 maxProfit = Math.max(maxProfit, prices[i] - minPrice)

https://ithelp.ithome.com.tw/upload/images/20250929/20169298DmpNSLeTdm.pnghttps://ithelp.ithome.com.tw/upload/images/20250929/20169298yLd8VId2dW.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言