File tree 2 files changed +52
-0
lines changed
best-time-to-buy-and-sell-stock
implement-trie-prefix-tree
2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments