diff --git a/best-time-to-buy-and-sell-stock/EcoFriendlyAppleSu.kt b/best-time-to-buy-and-sell-stock/EcoFriendlyAppleSu.kt new file mode 100644 index 000000000..aa0621599 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/EcoFriendlyAppleSu.kt @@ -0,0 +1,43 @@ +package leetcode_study + +/* +* 두 거래일 사이 최고의 수익을 구하는 문제 +* 시간 복잡도: O(n^2) +* -> 모든 경우의 수를 순회하며 거래일 사이 최고 가격을 구하는 로직: O(n^2) +* 공간 복잡도: O(1) +* 아래 로직은 시간 초과 발생 O(n^2)의 복잡도를 줄여야함. +* */ +fun maxProfit(prices: IntArray): Int { + var result = Int.MIN_VALUE + + for (i in prices.indices) { + for (j in i + 1 until prices.size) { + if (prices[i] < prices[j]) { + if (result < prices[j] - prices[i]) { + result = prices[j] - prices[i] + } + } + } + } + if (result == Int.MIN_VALUE) return 0 + return result +} + +/* +* 가장 작은 값을 저장하는 변수와 가장 큰 수익을 갖는 변수를 두고 문제 해결 +* 시간 복잡도: O(n) +* 공간 복잡도: O(1) +* */ +fun maxProfit2(prices: IntArray): Int { + var minValue = Int.MAX_VALUE + var maxValue = 0 + + for (price in prices) { + if (price < minValue) { + minValue = price + } else if (price - minValue > maxValue) { + maxValue = price - minValue + } + } + return maxValue +} diff --git a/encode-and-decode-strings/EcoFriendlyAppleSu.kt b/encode-and-decode-strings/EcoFriendlyAppleSu.kt new file mode 100644 index 000000000..98868ccf9 --- /dev/null +++ b/encode-and-decode-strings/EcoFriendlyAppleSu.kt @@ -0,0 +1,33 @@ +package leetcode_study + +/* +* 문자열 인코딩 디코딩 문제 +* 시간 복잡도: O(n) +* 공간 복잡도: O(n) +* */ +fun encoding(strs: List): String { + var result = "" + if (strs.isEmpty()) return result + for (index in 0 until strs.size - 1) { + if (strs[index] == ":") { + result += strs[index] + "::;" + } else { + result += strs[index] + ":;" + } + } + result += strs[strs.size - 1] + return result +} + +fun decoding(str: String): List{ + val splitedStrList = str.split(":;") + val result = mutableListOf() + for (splitStr in splitedStrList){ + if (splitStr == "::") { + result.add(":") + } else { + result.add(splitStr) + } + } + return result +} diff --git a/group-anagrams/EcoFriendlyAppleSu.kt b/group-anagrams/EcoFriendlyAppleSu.kt new file mode 100644 index 000000000..cbd93e97e --- /dev/null +++ b/group-anagrams/EcoFriendlyAppleSu.kt @@ -0,0 +1,19 @@ +package leetcode_study + +/* +* 주어진 문자열 배열에서 anagram을 그룹핑하는 문제 +* 자료구조 Map을 사용해 문제 해결. 오름차순으로 정렬한 char type을 재조합해 key 값으로 사용. value는 조회 대상 문자열 +* 시간 복잡도: O(n) +* 공간 복잡도: O(n) +* */ +fun groupAnagrams(strs: Array): List> { + val result = mutableMapOf>() + + for (str in strs) { + val key = str.toCharArray().sorted().joinToString("") + result.computeIfAbsent(key) { mutableListOf() }.add(str) + } + + if (strs.isEmpty()) return listOf(listOf()) + return result.values.toList() +}