iT邦幫忙

2022 iThome 鐵人賽

DAY 30
0
自我挑戰組

JavaScript - 30天 - 自學挑戰系列 第 30

LeetCode Js-121. Best Time to Buy and Sell Stock

  • 分享至 

  • xImage
  •  

LeetCode Js-121. Best Time to Buy and Sell Stock

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.

給予一個價格陣列,且為每一天對應的股票價格。
你希望透過選擇一天購買股票,同時在未來的一天出售該股票,以便獲得最大的利潤。
回傳在此交易中的最大利潤,如無法獲得任何利潤,則回傳0。

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.

Solution:

  1. 設定 min 為最大值,且起始的 profit 為 0。
  2. 依序將 prices 陣列中的售價進行比對
  3. 抓出售價中的最小值,更新為 min,否則略過。
  4. 更新「當前的利潤」為當前陣列中的售價減去 min,此為利潤。
  5. 如果「當前的利潤」出現最大值,則更新為 profit。
  6. 最終回傳最大的 profit。

Code:

var maxProfit = function(prices) {
    let min = Number.MAX_SAFE_INTEGER
    let profit = 0

    for (let i = 0; i < prices.length; i++) {
        if (prices[i] < min) {min = prices[i]}

        let currentProfit = prices[i] - min
        if (currentProfit > profit) {
          profit = currentProfit
        }
    }
    return profit
}

FlowChart:
Example 1

Input: prices = [7,1,5,3,6,4]

step.1
i = 0
prices[0] < min //7 < Max
min = prices[0] //min = 7
currentProfit = prices[0] - min //7 - 7 = 0
currentProfit > profit //0

step.2
i = 1
prices[1] < min //1 < 7
min = prices[1] //min = 1
currentProfit = prices[1] - min //1 - 1 = 0
currentProfit > profit //0

step.3
i = 2
prices[2] < min //5 > 1
currentProfit = prices[2] - min //5 - 1 = 4
currentProfit > profit //4 > 0
profit = currentProfit //4

step.4
i = 3
prices[3] < min //3 > 1
currentProfit = prices[3] - min //3 - 1 = 2
currentProfit > profit //2 < 4


step.5
i = 4
prices[4] < min //6 > 1
currentProfit = prices[4] - min //6 - 1 = 5
currentProfit > profit //5 > 4
profit = currentProfit //5

step.6
i = 5
prices[5] < min //4 > 1
currentProfit = prices[5] - min //4 - 1 = 3 
currentProfit > profit //3 < 5

return profit //5

上一篇
LeetCode Js-342. Power of Four
系列文
JavaScript - 30天 - 自學挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言