Warrenww
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 121.Best Time to Buy and Sell Stock <span class="tag" data-diff="easy" /> {%hackmd RN5D4nggQRO8wzNqxuvlNw %} ## 題目 You are given an array `prices` where `prices[i]` is the price of a given stock on the $i^{th}$ 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 <= $10^5$ - 0 <= prices[i] <= $10^4$ ## 思路 這題其實是在面試台積時遇到的白板題,面試官看著我做所以很緊張XDD 一開始看到Easy的時候還想說應該穩了,結果... 最原始的想法是採暴力解,loop過每一個item,並在剩下的元素中找最大值與他比較,來決定是否更新當前的`maxProfit` ```typescript function maxProfit(prices: number[]): number { let maxProfit: number = -1; for (let i = 0; i < prices.length; i ++) { const max = Math.max(...prices.slice(i + 1)); const profit = max - prices[i]; maxProfit = Math.max(maxProfit, profit); } return Math.max(maxProfit, 0); }; ``` 一開始還抱著僥倖的心態想說是easy應該怎麼寫只要答案對都可以過吧!結果就是慘紅的TLE,而且還在面試當中好丟臉>///< 還好面試官人很好(?)的說沒關係,暴力解也是一個方法... 總之,分析一下上面的code,就可以知道他的時間複雜度足足有 $O(n^2)$ 雖然不確定JS是怎麼實作`Math.max`的function,但考慮到這是一個沒有sorted的array,應該多少還是要 $O(n)$ 的時間吧...這就是一個快速好懂有用,但效率極差的程式。而要如何優化,答案也很簡單,就是鼎鼎大名的**Dynamic Programming**! 說實話我覺得一題Easy的題目要用到DP實在是太超過了QQ ### Dynamic Programming > 動態規劃(Dynamic Programming)採用「以空間換取時間」的策略,將計算過的結果記錄在table中,來**避免重複計算子問題**,採**bottom up**的方式進行運算。 以費氏數列(Fabonacci)來看,要求 $F_5$ 的值,如果採Top-Down的算法: ```graphviz graph{ rankdir="LR"; node [color=black,shape=circle]; F3_1[label="F3",color="red"]; F3_2[label="F3",color="red"]; F2_1[label="F2",color="blue"]; F2_2[label="F2",color="blue"]; F2_3[label="F2",color="blue"]; F1_1[label="F1",color="orange"]; F1_2[label="F1",color="orange"]; F1_3[label="F1",color="orange"]; F1_4[label="F1",color="orange"]; F1_5[label="F1",color="orange"]; F0_1[label="F0",color="orange"]; F0_2[label="F0",color="orange"]; F0_3[label="F0",color="orange"]; F5 -- F4; F5 -- F3_1; F4 -- F3_2; F4 -- F2_3; F3_1 -- F2_1; F3_1 -- F1_1; F3_2 -- F2_2; F3_2 -- F1_2; F2_1 -- F1_3; F2_1 -- F0_1; F2_2 -- F1_4; F2_2 -- F0_2; F2_3 -- F1_5; F2_3 -- F0_3; } ``` 會發現 $F_3$ 與 $F_2$ 都被計算了1次以上,但這個計算是可以被記錄的sub-problem,以下是改用bottom-up的計算方法: | n |0|1|2|3|4|5| | - |-|-|-|-|-|-| |$F_n$|0|1|1|2|3|5| 將每次計算的結果存起來,在後續要使用時就可以直接調用,無須重複計算,大大提升了效率。 ### DP設計流程 1. 觀察問題 2. 拆解為optimal substructure,一個問題的最佳解要如何用其sub-problem構成 3. 改寫為recurrsive 4. 用bottom up寫出DP Algorithm ### 開始設計 根據上面的定義,要設計出DP Algorithm需要幾個要素: - bottom-up - 由sub problem組成的optimal solution - 記住之前算過的結果 但此題並未用到上述的第二點,僅需要用bottom-up的觀念即可完成(這麼看來說他是easy好像也沒有不對)。 用bottom-up來看,最開始(`n=2`)我們只有開頭的兩天,這時如果`prices[1] > prices[0]`則`maxProfit`為兩者相減,否則回傳0。當再多一天時,會需要考慮以下情況: - 由於最大利潤一定是由至今為止的最小值算出來的,如果當前的price比至今為止的最小值還小,則需要將其記錄在`memorizedMin`中 - 如果當前的price比至今為止的最小值大,則他有可能產生最大利潤,故根據他產生的利潤去更新`maxProfit` ```typescript function maxProfit(prices: number[]): number { let maxProfit: number = 0; let memorizedMin = prices[0]; for (let i = 1; i < prices.length; i ++) { const current = prices[i]; if (current < memorizedMin) memorizedMin = current; if (current > memorizedMin) { maxProfit = Math.max(current - memorizedMin, maxProfit); } } return maxProfit; }; ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully