diff --git a/best-time-to-buy-and-sell-stock/sadie100.ts b/best-time-to-buy-and-sell-stock/sadie100.ts new file mode 100644 index 0000000000..6073439a8f --- /dev/null +++ b/best-time-to-buy-and-sell-stock/sadie100.ts @@ -0,0 +1,21 @@ +/* +prices를 순회하며 현재 최저값과의 차이를 구해서 최대 profit을 갱신한 뒤 최저값(구매가)를 갱신, 최종값을 리턴한다 + +시간복잡도 O(N) - N은 prices의 length +*/ + +function maxProfit(prices: number[]): number { + let buy + let result = 0 + + for (let price of prices) { + if (buy === undefined) { + buy = price + continue + } + result = Math.max(result, price - buy) + buy = Math.min(price, buy) + } + + return result +} diff --git a/group-anagrams/sadie100.ts b/group-anagrams/sadie100.ts new file mode 100644 index 0000000000..34f94bc007 --- /dev/null +++ b/group-anagrams/sadie100.ts @@ -0,0 +1,30 @@ +/* +strs의 문자열들을 등장빈도를 바탕으로 계산한 특수 문자열로 전환하고 같은 것끼리 묶는다. + +시간복잡도 : O(N * K) - N은 strs의 개수, K는 strs의 길이. N 순회 안에 K 순회 +*/ + +function groupAnagrams(strs: string[]): string[][] { + const anagramMap = {} + const result = strs.reduce((acc, cur) => { + const charArray = new Array(26).fill(0) + + for (let char of cur) { + const charIdx = char.charCodeAt(0) - 'a'.charCodeAt(0) + charArray[charIdx] += 1 + } + + const sortedValue = charArray.join('#') + + const targetIdx = anagramMap[sortedValue] + if (targetIdx !== undefined) { + acc[targetIdx].push(cur) + } else { + anagramMap[sortedValue] = acc.length + acc.push([cur]) + } + return acc + }, []) + + return result +}