Skip to content

Commit 377dea5

Browse files
committed
[20190415] easy problems
1 parent 4df38d8 commit 377dea5

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

โ€ŽREADME.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
| [0103](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/) | Binary Tree Zigzag Level Order Traversal | medium | python | |
3737
| [0107](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/) | Binary Tree Level Order Traversal II | easy | python | |
3838
| [0111](https://leetcode.com/problems/minimum-depth-of-binary-tree/) | Minimum Depth of Binary Tree | easy | [python](๐Ÿ™‚easy/0111.Minimum-Depth-of-Binary-Tree/minimum_depth_of_binary_tree.py) | tree |
39+
| [0121](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | Best Time to Buy and Sell Stock | easy | [python](๐Ÿ™‚easy/0121.Best-Time-to-Buy-and-Sell-Stock/best_time_to_buy_and_sell_stock.py) | |
3940
| [0122](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description) | Best Time to Buy and Sell Stock II | easy | python | |
4041
| [0139](https://leetcode.com/problems/word-break/description/) | Word Break | medium | python | |
4142
| [0141](https://leetcode.com/problems/linked-list-cycle/description) | Linked List Cycle | easy | python | |
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# 121. Best Time to Buy and Sell Stock
2+
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
3+
4+
5+
from typing import List
6+
7+
8+
class Solution:
9+
# prices ๋ผ๋Š” integer list ๊ฐ€ ๋“ค์–ด์˜ฌ ๋•Œ ๊ฐ€์žฅ ์ ์€ ๊ฐ€๊ฒฉ์— ์‚ฌ์„œ ๋น„์‹ธ๊ฒŒ ํŒ” ๋•Œ ์ƒ๊ธฐ๋Š” ์ด์ต์„ ๋ฆฌํ„ดํ•˜๋Š” ๋ฌธ์ œ๋‹ค.
10+
def maxProfit(self, prices: List[int]) -> int:
11+
12+
# ์ตœ์†Œ ๊ธˆ์•ก buy ์™€ ํ˜„์žฌ ๊ธˆ์•ก - buy ์˜ ๊ฐ’์˜ maximum ์„ ๊ตฌํ•˜๋ฉด ๋œ๋‹ค.
13+
# ์™œ๋ƒํ•˜๋ฉด ๊ฐ€์žฅ ์ ์€ ๊ฐ€๊ฒฉ์— ์‚ฌ์„œ (min) ๊ฐ€์žฅ ๋น„์‹ธ๊ฒŒ ํŒ”์•„์•ผ (max) ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.
14+
# greedy ๋กœ ์ƒ๊ฐํ•ด์„œ ํ•˜๋ฉด ๋œ๋‹ค.
15+
16+
buy = float("inf")
17+
res = 0
18+
for price in prices:
19+
# ์ตœ์†Œ ๊ธˆ์•ก ๊ฐฑ์‹ 
20+
buy = min(buy, price)
21+
# ํŒ๋งค ์ตœ๋Œ€ ์ด์ต
22+
res = max(res, price - buy)
23+
24+
return res
25+
26+
27+
if __name__ == '__main__':
28+
sol = Solution()
29+
assert sol.maxProfit([7, 1, 5, 3, 6, 4]) == 5

0 commit comments

Comments
ย (0)