From 452da5283c83a8d48e71881eee9e900ad696bd92 Mon Sep 17 00:00:00 2001 From: sun912 Date: Tue, 10 Sep 2024 22:15:02 +0900 Subject: [PATCH 1/4] [W5] best time to buy and sell stock solution --- best-time-to-buy-and-sell-stock/sun912.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 best-time-to-buy-and-sell-stock/sun912.py diff --git a/best-time-to-buy-and-sell-stock/sun912.py b/best-time-to-buy-and-sell-stock/sun912.py new file mode 100644 index 000000000..8bb626639 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/sun912.py @@ -0,0 +1,21 @@ +""" +TC: O(n) +SC: O(1) +""" +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit= 0 + l = 0 + r = 1 + + while r < len(prices): + if prices[l] < prices[r]: + profit = prices[r] - prices[l] + max_profit = max(max_profit, profit) + + else: + l = r + r +=1 + return max_profit + + From 69969b75332f6f52d5a4d2d8fd9a1e0bff9ce2d5 Mon Sep 17 00:00:00 2001 From: sun912 Date: Wed, 11 Sep 2024 22:11:50 +0900 Subject: [PATCH 2/4] [W5] group-anagrams solution --- group-anagrams/sun912.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 group-anagrams/sun912.py diff --git a/group-anagrams/sun912.py b/group-anagrams/sun912.py new file mode 100644 index 000000000..2472021dd --- /dev/null +++ b/group-anagrams/sun912.py @@ -0,0 +1,19 @@ +""" + TC: O(m*n) + SC: O(26*n) -> O(n) +""" + +from collections import defaultdict + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + result = defaultdict(list) + + for word in strs: + count = [0] * 26 + + for c in word: + count[ord(c)-ord("a")] += 1 + result[tuple(count)].append(word) + + return result.values() From 599da3e8bbe3c104c3d8768cdc2d80869306b00a Mon Sep 17 00:00:00 2001 From: sun912 Date: Fri, 13 Sep 2024 17:00:28 +0900 Subject: [PATCH 3/4] 3sum solution --- 3sum/sun912.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 3sum/sun912.py diff --git a/3sum/sun912.py b/3sum/sun912.py new file mode 100644 index 000000000..e69de29bb From 7e1791056e4342c73418295d7d7cb4f8ddd088db Mon Sep 17 00:00:00 2001 From: sun912 Date: Sat, 14 Sep 2024 22:03:34 +0900 Subject: [PATCH 4/4] [W5] 3sum solution --- 3sum/sun912.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/3sum/sun912.py b/3sum/sun912.py index e69de29bb..275f88cef 100644 --- a/3sum/sun912.py +++ b/3sum/sun912.py @@ -0,0 +1,25 @@ +""" + TC: O(n^2) + SC: O(1) +""" + +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + result = set() + nums.sort() + + for i in range(len(nums)-2): + left,right = i+1, len(nums)-1 + while left < right: + three_sum = nums[i]+nums[left]+nums[right] + + if three_sum < 0: + left += 1 + elif three_sum > 0: + right -= 1 + else: + result.add((nums[i], nums[left], nums[right])) + left,right = left+1, right-1 + + return list(result) +