알고리즘
[Python] LeetCode - Best Time to Buy and Sell Stock
sowish
2023. 5. 19. 14:34
반응형
Problem

Solving Process
i와 j라는 two pointers를 만든 후, (i는 최소값, j는 최댓값을 구분하기 위함이다)
i = 0, j = 1
루프를 돌며 j - i 값의 차이를 구한 후,
해당 값이 max 인지를 검사한다.
또한 i 의 값이 j보다 큰 경우는 ( = 진행 하다 최소값이 나온 경우)
i의 포인터를 j로 바꿔준다.
j가 prices를 다 돌면 루프를 종료하고 max값을 리턴한다.
Solution
class Solution:
def maxProfit(self, prices: List[int]) -> int:
i = 0
j = 1
length = len(prices)
max_price = 0
while j < length:
diff = prices[j] - prices[i]
if diff > max_price:
max_price = diff
elif prices[i] > prices[j]:
i = j
j+=1
return max_price반응형