diff --git a/best-time-to-buy-and-sell-stock/saysimple.py b/best-time-to-buy-and-sell-stock/saysimple.py new file mode 100644 index 000000000..f64093fc7 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/saysimple.py @@ -0,0 +1,18 @@ +""" +https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ +""" +# - time complexity : O(n) +# - space complexity : O(n) + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + now = prices[0] + diff = [0] * len(prices) + + for i, v in enumerate(prices[1:]): + if now > v: + now = v + else: + diff[i+1] = v - now + + return max(diff) diff --git a/contains-duplicate/saysimple.py b/contains-duplicate/saysimple.py new file mode 100644 index 000000000..f7d206534 --- /dev/null +++ b/contains-duplicate/saysimple.py @@ -0,0 +1,14 @@ +""" +https://leetcode.com/problems/contains-duplicate/ +""" +# - time complexity : O(n) +# - space complexity : O(n) + +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + visited = {} + for n in nums: + if n in visited: + return True + visited[n] = True + return False diff --git a/two-sum/saysimple.py b/two-sum/saysimple.py new file mode 100644 index 000000000..5e8e101e9 --- /dev/null +++ b/two-sum/saysimple.py @@ -0,0 +1,21 @@ +""" +https://leetcode.com/problems/two-sum/ +""" +# - time complexity : O(nlogn) +# - space complexity : O(n) + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + s, e = 0, len(nums) - 1 + arr = [nums[i]:=[n,i] for i, n in enumerate(nums)] + + arr.sort(key=lambda x: x[0]) + + while s <= e: + now = arr[s][0] + arr[e][0] + if now == target: + return [arr[s][1], arr[e][1]] + if now < target: + s += 1 + else: + e -= 1 diff --git a/valid-anagram/saysimple.py b/valid-anagram/saysimple.py new file mode 100644 index 000000000..c733af351 --- /dev/null +++ b/valid-anagram/saysimple.py @@ -0,0 +1,11 @@ +""" +https://leetcode.com/problems/valid-anagram/ +""" +# - time complexity : O(n) +# - space complexity : O(n) + +from collections import Counter + +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return Counter(s) == Counter(t) diff --git a/valid-palindrome/saysimple.py b/valid-palindrome/saysimple.py new file mode 100644 index 000000000..f95dbafb1 --- /dev/null +++ b/valid-palindrome/saysimple.py @@ -0,0 +1,10 @@ +""" +https://leetcode.com/problems/valid-palindrome/ +""" +# - time complexity : O(n) +# - space complexity : O(n) + +class Solution: + def isPalindrome(self, s: str) -> bool: + s = "".join([i for i in s if i.isalnum()]).lower() + return s == s[::-1]