diff --git a/best-time-to-buy-and-sell-stock/YuuuuuuYu.java b/best-time-to-buy-and-sell-stock/YuuuuuuYu.java new file mode 100644 index 000000000..a771d5e16 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/YuuuuuuYu.java @@ -0,0 +1,26 @@ +/** + * Runtime: 1ms + * Time Complexity: O(n) + * + * Memory: 94.08MB + * Space Complexity: O(1) + * + * Approach: 그리디 알고리즘 + * - 주어진 prices 배열을 순회하며 최소 가격(min)을 갱신 + */ +class Solution { + public int maxProfit(int[] prices) { + int maxProfit = 0; + int min = prices[0]; + + for (int i=1; i= prices[i]) { + min = prices[i]; + } else { + maxProfit = Math.max(maxProfit, prices[i]-min); + } + } + + return maxProfit; + } +} diff --git a/group-anagrams/YuuuuuuYu.java b/group-anagrams/YuuuuuuYu.java new file mode 100644 index 000000000..cfa1ae97b --- /dev/null +++ b/group-anagrams/YuuuuuuYu.java @@ -0,0 +1,29 @@ +/** + * Runtime: 6ms + * Time Complexity: O(n x k log k) + * - n: 문자열 개수 + * - k: 문자열 최대 길이 + * - k log k: 각 문자열을 정렬하는 시간 + * + * Memory: 49.30MB + * Space Complexity: O(n x k) + * - 최대 n개의 키-값 + * + * Approach: 정렬된 문자열을 키로 사용해서 같은 애나그램끼리 그룹화 + */ +class Solution { + public List> groupAnagrams(String[] strs) { + Map> anagramMap = new HashMap<>(); + + for (String str: strs) { + char[] chs = str.toCharArray(); + Arrays.sort(chs); + String key = new String(chs); + + anagramMap.computeIfAbsent(key, k -> new ArrayList<>()) + .add(str); + } + + return new ArrayList<>(anagramMap.values()); + } +}