欣迪

出處: https://leetcode.com/explore/interview/card/top-interview-questions-easy/97/dynamic-programming/572/

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.

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.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104
var maxProfit = function(prices) {
    let maxProfit = 0
    let min = prices[0]
    for(let i = 1; i < prices.length; i++) {
        min = Math.min(prices[i], min)
        maxProfit = Math.max(prices[i] - min, maxProfit)
    }
    return maxProfit
}

其實這題想通之後並不是很難。因為他有先後次序的概念,所以必須大概的思維如下:

  • 紀錄當前最小的金額,日後所有出現的金額 – 當前最小金額才有可機會出現最大利潤
  • 取得當前最大利潤,用目前出現的金額 – 當前最小金額,如果利潤更高則覆寫最大利潤

這題用 js 怎麼寫效能都很差。日後研究出更快的寫法再來補充吧。

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。