Skip to content

Commit 8f69a0a

Browse files
committed
D. J.:
- Added leetcode problem and solution for 121 Best Time to Buy and Sell Stock
1 parent 82de5e4 commit 8f69a0a

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
88
- [27 Remove Element](https://leetcode.com/problems/remove-element/description/)
99
- [80 Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/)
1010
- [88 Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/description/)
11+
- [121 Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)
1112
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
1213

1314
## Development 🔧
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def maxProfit(self, prices: List[int]) -> int:
6+
"""
7+
You are given an array prices where prices[i] is the price of a given stock on the ith day.
8+
9+
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.
10+
11+
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
12+
"""
13+
left, right, best_profit = 0, 1, 0
14+
while right < len(prices):
15+
if prices[left] > prices[right]:
16+
left = right
17+
right += 1
18+
else:
19+
profit = prices[right] - prices[left]
20+
if profit > best_profit:
21+
best_profit = profit
22+
right += 1
23+
return best_profit
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._121_best_time_to_buy_and_sell_stocks import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["prices", "expected"],
10+
argvalues=[
11+
([7, 1, 5, 3, 6, 4], 5),
12+
([7, 6, 4, 3, 1], 0),
13+
],
14+
)
15+
def test_func(prices: List[int], expected: int):
16+
max_profit = Solution().maxProfit(prices)
17+
assert max_profit == expected

0 commit comments

Comments
 (0)