Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions best-time-to-buy-and-sell-stock/JustHm.swift
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

공간 복잡도의 경우 최대 이익을 하나의 변수에 업데이트 해주는 식으로 하면 O(1) 으로 최적화 가능할 것 같습니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// time: O(n) space: O(n)
class Solution {
func maxProfit(_ prices: [Int]) -> Int {
guard !prices.isEmpty else { return 0 }
var result = [Int]()
var current = prices[0]

for price in prices {
if current > price {
current = price
continue
}
result.append(price - current)
}
return result.max() ?? 0
}
}
35 changes: 35 additions & 0 deletions implement-trie-prefix-tree/JustHm.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

class Trie {
var children: [Character: Trie] = [:]
var isEndOfWord = false

func insert(_ word: String) {
guard !word.isEmpty else { return }
var node = self
for char in word {
if node.children[char] == nil {
node.children[char] = Trie()
}
node = node.children[char]!
}
node.isEndOfWord = true
}

func search(_ word: String) -> Bool {
guard let node = findNode(word) else { return false }
return node.isEndOfWord
}

func startsWith(_ prefix: String) -> Bool {
return findNode(prefix) != nil
}

private func findNode(_ word: String) -> Trie? {
var node = self
for char in word {
guard let next = node.children[char] else { return nil }
node = next
}
return node
}
}