Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 백준 17608번
- 그래프(Graph)
- 백준 10000번
- DFS & BFS
- 백준 9012번
- 이분 그래프(Bipartite Graph)
- 큐(Queue)
- 분할 정복(Divide and Conquer)
- DFS
- 백준 2493번
- 트리(Tree)
- 백준 1707번
- DFS(Depth First Search)
- 알고리즘 개념
- 위상 정렬(Topology Sort)
- 백준 1948번
- 백준 2812번
- 플로이드 워셜 알고리즘(Floyd-Warshall Algorithm)
- 백준 21606번
- BFS
- 다익스트라 알고리즘(Dijkstra Algorithm)
- 백준 2261번
- 백준 18352번
- 그리디 알고리즘(Greedy Algorithm)
- 이분 탐색(Binary Search)
- 백준 2504번
- 동적 프로그래밍(Dynamic Programming)
- BFS(Breadth First Search)
- 위상 정렬(Topological Sort)
- 스택(Stack)
Archives
- Today
- Total
Always Be Wise
배열 : 주식을 사고 팔기 가장 좋은 시점(리트코드 121번) 본문
728x90
▶ 문제 : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Best Time to Buy and Sell Stock - 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
##### 문제 #####
# 한 번의 거래로 낼 수 있는 최대 이익을 산출하라.
##### 입력 #####
# prices = [7, 1, 5, 3, 6, 4]
##### 출력 #####
# 5
▶ 접근 방법
1) 브루트 포스로 계산
사고 팔고를 반복하면서 최대 이익을 갱신하면 된다.
다만, 계산 속도가 너무 느리다.
2) 저점과 현재 값과의 차이 계산
입력 값을 확인하면서 최소 값을 갱신하고,
이후 최소 값과 입력 값의 차이를 계산해서 최대 이익을 갱신한다.
▶ 풀이 코드
prices = [7, 1, 5, 3, 6, 4]
def max_profit(prices: list) -> int:
profit = 0
for i, price in enumerate(prices):
for j in range(i, len(prices)):
profit = max(prices[j] - price, profit)
return profit
print(max_profit(prices))
def max_profit2(prices: list) -> int :
profit = 0
min_profit = float('inf')
for price in prices:
min_profit = min(min_profit, price)
profit = max(profit, price - min_profit)
return profit
print(max_profit2(prices))
▶ 관련 링크
'알고리즘 > 리트코드' 카테고리의 다른 글
스택 : 중복 문자 제거(리트코드 316번) (0) | 2022.02.02 |
---|---|
스택 : 유효한 괄호(리트코드 20번) (0) | 2022.02.02 |
배열 : 세 수의 합(리트코드 15번) (0) | 2022.01.30 |
배열 : 빗물 트래핑(리트코드 42번) (0) | 2021.12.15 |
배열 : 두 수의 합(리트코드 1번) (0) | 2021.12.15 |
Comments