본문 바로가기

Greedy3

[LeetCode] Assign Cookies 파이썬 (greedy) class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() s.sort() result, i = 0, 0 for j in range(len(s)): if i == len(g): break if s[j] >= g[i]: result += 1 i += 1 return result 우선 sort 하고 two pointer(i,j) i를 g의 pointer로 사용하고 j는 s의 pointer로 사용하면서 하나씩 체크해 나간다. i == len(g) 를 통해 g의 모든 element를 체크했으면 exit s의 j-th 원소와 g의 i-th 원소를 비교하면서 조건에 맞으면 result에 count + 1 i를 한.. 2021. 4. 17.
[LeetCode] Best Time to Buy and Sell Stock II python (greedy) class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): profit = 0 for i in range(len(prices) - 1): profit += max(0, prices[i + 1] - prices[i]) return profit 저점 매수 고점 매도 실제 시장에서는 불가능하지만 지금은 prices가 주어졌기 때문에 loss가 발생하기 전에 팔고 하락하자마자 다시 사면 profit maximization이 가능하기 때문에 i+1 과 i 시점에서의 차이가 0보다 클 경우 모두 더해주면 된다. 출처: github.com/jiapengwen/LeetCode/blob/master/.. 2021. 4. 1.
[프로그래머스] 체육복 (python) Python 주의사항은 여벌을 가지고 있는 리스트에서도 도난이 발생할 수 있기 때문에 lost와 reserve 각각에 대해서 중복이 없게 차집합을 만들어 놓아야 한다. (first two lines of codes.) 그리고 여벌 리스트(rsv_pos)를 loop돌면서 도난 당한 리스트(lost_pos)의 앞 or 뒤에 여벌리스트의 요소들이 있는지 체크하면서 도난 리스트를 제거한다. python remove method는 list에서 remove에 주어진 item을 찾아서 삭제하는 메서드이다. 만약, 해당 아이템이 없다면 "ValueError: list.remove(x): x not in list" 이러한 에러 메시지를 보게될 것이다. def solution(n, lost, reserve): rsv_po.. 2021. 1. 18.