前言
  究竟何時才是買賣股票的最好時機呢? 這題邏輯很生活化,就是把一個陣列內所有的價格遍歷完,低買高賣後把最大的差價回傳出來,這題使用了單迴圈遍歷陣列裡所有的價格,遍歷裡也是常數的時間操作,時間複雜度推算可以達到 O(n),這篇有 Java 和 Python 的寫法。
題目
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.
給你一個價格陣列 prices ,prices[i] 是取得一個股票在第 i 天的價格。
你想要最大化你的利潤,藉著選擇一天去買一張股票和選擇在未來不同天裡去賣掉那張股票。
你可以從這個交易回傳最大化的利潤。如果你無法達到任何利潤,就回傳 0。
題目連結:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
題目限制
注意:不能在第二天買入後第一天賣出,必須先買後賣。
1 <= prices.length <= 1050 <= prices[i] <= 104
範例
| 1 | Input: prices = [7,1,5,3,6,4] | 
| 1 | Input: prices = [7,6,4,3,1] | 
思路&筆記
- 判斷陣列中值的大小,把更小的值存起來
- 兩數的相差 = 把當前的索引的值 - 上一個索引的值
- 比較前一個值,將比較大的值存入
JAVA 實現
| 1 | class Solution { | 
Python 實現
使用了和 Java 一樣的邏輯執行,換成 Python 的寫法。
| 1 | class Solution: | 
成績
| Language | Runtime | Memory | 
|---|---|---|
| Java | 2ms | 59.4MB | 
| Python | 984 ms | 25 MB |