File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ 풀이
3+ - 주어진 배열 prices를 한 번 탐색합니다.
4+
5+ - prices[i]가 이전에 저장한 buy_price보다 낮을 경우,
6+ maximum profit이 증가할 가능성이 있습니다.
7+ 따라서 buy_price와 sell_price를 prices[i]로 바꿔줍니다.
8+
9+ - prices[i]가 이전에 저장한 sell_price보다 높은 경우,
10+ 현재 buy_price로 지금까지 기록한 profit보다 더 높은 이익을 내게 됩니다.
11+ 따라서 sell_price를 prices[i]로 바꿔주고 결과값을 갱신합니다.
12+
13+ Big O
14+ - N: 배열 prices의 크기
15+
16+ - Time complexity: O(N)
17+ - 배열의 크기 N이 증가함에 따라 실행 시간도 선형적으로 증가합니다.
18+
19+ - Space complexity: O(1)
20+ - 배열의 크기 N이 증가하여도 사용하는 메모리 공간은 일정합니다.
21+ '''
22+
23+ class Solution :
24+ def maxProfit (self , prices : List [int ]) -> int :
25+ res = 0
26+
27+ buy_price = prices [0 ]
28+ sell_price = prices [0 ]
29+
30+ for i in range (1 , len (prices )):
31+ curr_price = prices [i ]
32+
33+ if buy_price > curr_price :
34+ buy_price = curr_price
35+ sell_price = curr_price
36+ elif sell_price < curr_price :
37+ sell_price = curr_price
38+ res = max (res , sell_price - buy_price )
39+
40+ return res
You can’t perform that action at this time.
0 commit comments