1. Greedy class Solution: def maxProfit(self, prices: List[int]) -> int: stack = [] answer = 0 for price in prices: if not stack: stack.append(price) else: if stack[-1] < price: answer+=price-stack[-1] stack.pop() stack.append(price) else: stack.pop() stack.append(price) return answer 주어진 날짜에 대한 주식 가격 목록에서 주식을 사고 팔 최댓값을 반환하면 된다. 그리디 하게 생각해서 해결할 수 있는 문제다. [ 1, 3, 7 ] 첫째, 둘째, 셋째 날 주식의 가격이 위와 같다고 가..
Kth Smallest Element in a Sorted Matrix - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 1. 단순하게... class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: temp = [] for item in matrix: temp += item return sorted(temp)[k-1] 2차원 배열에서 k번째로 큰 수를 반환하는 문제다. 그냥 2차..
Game of Life - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 1. 구현 from typing import * ''' Any live cell with fewer than two live neighbors dies as if caused by under-population. 8방으로 이웃이 2개 미만이면 죽인다 Any live cell with two or three live neighbors lives on to the next generation...
Number of 1 Bits - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 1. Bit 성질을 이용한 풀이 class Solution: def hammingWeight(self, n: int) -> int: answer = 0 while n: n = n & (n - 1) answer += 1 return answer 비트 조작은 굉장히 재밌는 성질들이 많다. 내가 아는 몇 안 되는 비트 조작 중 하나가 이것인데, 양의 정수 a와 a-1을 AND 연산하면 양..
Convert Sorted Array to Binary Search Tree - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 1. DFS class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: def dfs(cur_list): if not cur_list: return None mid = len(cur_list) // 2 cur_node = TreeNode(cur_list[mid]) c..
Longest Increasing Subsequence - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 1. 스택과 이진 탐색을 이용한 풀이 from typing import * from bisect import bisect_left class Solution: def lengthOfLIS(self, nums: List[int]) -> int: stack = [] for num in nums: if not stack: stack.append(num) else:..