Skip to content

Commit 2e944b3

Browse files
authored
Merge pull request #1404 from JustHm/main
[JustHm] Week 05 Solution
2 parents ac71dd2 + 9c12f7c commit 2e944b3

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// time: O(n) space: O(n)
2+
class Solution {
3+
func maxProfit(_ prices: [Int]) -> Int {
4+
guard !prices.isEmpty else { return 0 }
5+
var result = [Int]()
6+
var current = prices[0]
7+
8+
for price in prices {
9+
if current > price {
10+
current = price
11+
continue
12+
}
13+
result.append(price - current)
14+
}
15+
return result.max() ?? 0
16+
}
17+
}
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
2+
class Trie {
3+
var children: [Character: Trie] = [:]
4+
var isEndOfWord = false
5+
6+
func insert(_ word: String) {
7+
guard !word.isEmpty else { return }
8+
var node = self
9+
for char in word {
10+
if node.children[char] == nil {
11+
node.children[char] = Trie()
12+
}
13+
node = node.children[char]!
14+
}
15+
node.isEndOfWord = true
16+
}
17+
18+
func search(_ word: String) -> Bool {
19+
guard let node = findNode(word) else { return false }
20+
return node.isEndOfWord
21+
}
22+
23+
func startsWith(_ prefix: String) -> Bool {
24+
return findNode(prefix) != nil
25+
}
26+
27+
private func findNode(_ word: String) -> Trie? {
28+
var node = self
29+
for char in word {
30+
guard let next = node.children[char] else { return nil }
31+
node = next
32+
}
33+
return node
34+
}
35+
}

0 commit comments

Comments
 (0)