[Leetcode] 121. Best Time to Buy and Sell Stock

閱讀時間約 3 分鐘

題目 : 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:

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.


參考影片 : https://youtu.be/1pkOgXD63yU

class Solution:
def maxProfit(self, prices: List[int]) -> int:
l, r = 0 ,1 # Left=buy, Right=sell
# 0,1 分別代表索引值
maxP = 0 # 最高利潤值

while r < len(prices):
if prices[l] < prices[r] : # 如果左側l的金額<右側r的金額,代表可以買低賣高
profit = prices[r] - prices[l] # 計算利潤
maxP = max(maxP, profit) # 用max()回傳較大的數字到maxP,得到目前的最高利潤
else:
l = r
r += 1

return maxP


7會員
47內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言0
查看全部
發表第一個留言支持創作者!
Youna's Devlog 的其他內容
[Leetcode] 35. Search Insert Position
閱讀時間約 2 分鐘
[Leetcode] 69. Sqrt(x)
閱讀時間約 2 分鐘
[Leetcode] 88. Merge Sorted Array
閱讀時間約 4 分鐘
[Leetcode] 27. Remove Element
閱讀時間約 3 分鐘
[Leetcode] 100. Same Tree
閱讀時間約 2 分鐘
你可能也想看
[TS LeetCode] 121. Best Time to Buy and Sell Stock題目摘要 給定一個陣列 prices,其中 prices[i] 代表第 i 天的股票價格。你希望透過在某一天購買一股股票,並在未來的某一天賣出它,以最大化你的利潤。如果無法獲得任何利潤,則返回 0。
Thumbnail
avatar
毛怪
2023-10-19
LeetCode - Rings and Rods #2103 Easy刷題筆記 Easy 題目說明:總共有 10 根竿子,3 種顏色,給予一 string 名為 rings,Ex: R0G1B2 意思是 第1根( index = 0 )有一個紅戒子,第2根( index = 1)有一個綠戒子,第3根(index = 2)有一個藍戒子 目標:回傳有幾根竿子同時有三個顏
avatar
Eason
2023-01-08
【LeetCode】876. Middle of the Linked ListInput: head = [1,2,3,4,5] Output: [3,4,5] 單看列表只是要找中間值,不過給定的資料結構不是陣列,而是鏈結串列。
Thumbnail
avatar
2021-10-09
【LeetCode】189. Rotate Array之前跳過的題目,回來補完成。 Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4]
Thumbnail
avatar
2021-10-08
【LeetCode】557. Reverse Words in a String III今日題目: 把一行字內每個單字都反轉字元。 Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Thumbnail
avatar
2021-10-08
【LeetCode】344. Reverse String今日題目:字串反轉 Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Thumbnail
avatar
2021-10-08
【LeetCode】167. Two Sum II 題目如下: Input: numbers = [2,7,11,15], target = 9 Output: [1,2]
Thumbnail
avatar
2021-10-07
【LeetCode】283. Move Zeroes題目要求如下: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] 把0都搬到後面去,非0的數字移到前面,且不更改原本數字的大小順序。
Thumbnail
avatar
2021-10-07
【LeetCode】704. Binary SearchLeetcode上正好有14天的讀書計畫,今天三題都是二分搜索,順手三題都寫一寫,想法上很固定。
Thumbnail
avatar
2021-10-05
【LeetCode】20. Valid Parentheses 前幾天看別人直播刷題,心血來潮打開很久沒動的leetcode試試,挑了一題當初面試沒寫出來的題目。嗯...我那時才剛碰資料結構,知道要用stack寫卻沒實作過任何東西,現在有工作經驗後再來寫,看看會不會有不一樣的想法。
Thumbnail
avatar
2021-10-04