Skip to content

Commit 35344fc

Browse files
Merge pull request #1857 from prograsshopper/main
[prograsshopper] Week 5 solution
2 parents 5adec3f + b885adc commit 35344fc

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def maxProfit(self, prices: List[int]) -> int:
3+
max_profit = 0
4+
buy_price = float('inf')
5+
6+
for price in prices:
7+
buy_price = min(buy_price, price)
8+
current_profit = price - buy_price
9+
max_profit = max(max_profit, current_profit)
10+
11+
return max_profit

group-anagrams/prograsshopper.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution:
2+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
3+
# sol 1 -> Time Exceed
4+
from collections import defaultdict
5+
word_dict = defaultdict(list)
6+
7+
for string in strs:
8+
exist = False
9+
for elem in word_dict.keys():
10+
if sorted(elem) == sorted(string):
11+
word_dict[elem].append(string)
12+
exist = True
13+
break
14+
if not exist:
15+
word_dict[string] = [string, ]
16+
result = []
17+
for elem in word_dict.values():
18+
result.append(elem)
19+
return result
20+
21+
# sol 2
22+
# Time Complexity O(mn)
23+
result = defaultdict(list)
24+
25+
for string in strs:
26+
key = "".join(sorted(string))
27+
result[key].append(string)
28+
return list(result.values())

0 commit comments

Comments
 (0)