Skip to content

Commit 6fab9b8

Browse files
committed
D. J.:
- Added LeetCode problem and solution for 122 Best Time to Buy and Sell Stock II
1 parent b1303fe commit 6fab9b8

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
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/)
1111
- [121 Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)
12+
- [122 Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/)
1213
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
1314

1415
## Development 🔧
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def maxProfit(self, prices: List[int]) -> int:
6+
"""
7+
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
8+
9+
On each day, you may decide to buy and/or sell the stock. You can only hold at
10+
most one share of the stock at any time.
11+
However, you can buy it then immediately sell it on the same day.
12+
13+
Find and return the maximum profit you can achieve.
14+
"""
15+
left, right, best_profit = 0, 1, 0
16+
while right < len(prices):
17+
if prices[left] > prices[right]:
18+
left = right
19+
right += 1
20+
elif prices[right] - prices[left] > 0:
21+
best_profit += prices[right] - prices[left]
22+
left = right
23+
right += 1
24+
else:
25+
right += 1
26+
return best_profit
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._122_best_time_to_buy_and_sell_stock_II import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["prices", "expected"],
10+
argvalues=[
11+
([7, 1, 5, 3, 6, 4], 7),
12+
([1, 2, 3, 4, 5], 4),
13+
([7, 6, 4, 3, 1], 0),
14+
],
15+
)
16+
def test_func(prices: List[int], expected: int):
17+
max_profit = Solution().maxProfit(prices)
18+
assert max_profit == expected

0 commit comments

Comments
 (0)