leetcode-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
Example 1
1 | Input: prices = [7,1,5,3,6,4] |
Example 2
1 | Input: prices = [7,6,4,3,1] |
解釋題目
給你一個 array,叫做 prices,prices 中每個值是一支股票每天的價格,題目要求在其中一天買進,另一天賣出,以獲得最大利益。要注意的是,股票要先買進才能賣出,且同一天只能買或賣,不能買賣同時操作。
思路
- 可用雙指針解題,雙指針是左 ( left )、右 ( right ) 指針,一開始會是
left = 0
跟right = 1
- 使用雙指針解題,通常用 while,條件設定是「右指針」走到底結束。
- 目的: 要找到最小值 m,找到 m 後,m 後面的數字減去 m 的最大值就是 max_profit
- 如何要找到最小值?
prices[right] - prices[left]
,如果 > 0,代表prices[left]
,目前是最小值- right 指針繼續往右走,看有沒有更大的 profit
prices[right] - prices[left]
,如果 < 0,代表出現比prices[left]
更小的值,所以透過這樣可以找到最小值 m- 此時,把最小值 m 的位置指派給 left,也就是
left = right
- 此時,把最小值 m 的位置指派給 left,也就是
程式碼
1 | class Solution: |
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 雜耍特技師!