https://leetcode.com/problems/best-time-to-buy-and-sell-stock
min 변수를 선언하고, 리스트의 가장 첫번째 값을 넣는다.
주어진 리스트를 왼쪽에서 오른쪽으로 순서대로 순회한다.
순회하다가 min 보다 낮은 값을 만나면, min 을 그 낮은 값으로 대체한다.
순회하면서 만나는 값과 min 의 차이를 계속 확인하고 갱신한다.
결과적으로 min 값은 가장 낮은 값이 되고,
(min 값 갱신 이후) 순회하며 만나는 값과의 차이 중 가장 큰 차이값이 반환된다.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if(len(prices)<=1): return 0
min = prices[0]
profit = 0
for i in prices:
if(min > i): min = i
elif(profit < i-min): profit = i-min
return profit
< English (feedback by ChatGPT) >
We declare a 'min' variable and put the first value of the given list into 'min'.
(We declare a min variable and assign it the first value of the given list.)
And we start to iterate through the given list from the beginning to the end.
(Then we iterate through the list from left to right.)
If we encounter a smaller number than the 'min' during traversal, update 'min' as the smaller number.
(If we encounter a number smaller than min during the traversal, we update min with that number.)
Keep checking the difference between numbers on traversal and 'min', and update the difference.
(At each step, we check the difference between the current number and min, and keep track of the maximum difference.)
As result, the 'min' variable becomes the minimum number,
(As a result, min holds the smallest value seen so far,)
and the maximum difference with numbers on traversal (after 'min' is updated) is returned.
(and the largest difference between min and a later number in the list is returned.)
'Coding Interview' 카테고리의 다른 글
[leetcode] 160. Intersection of Two Linked Lists (0) | 2025.05.10 |
---|---|
[leetcode] 141. Linked List Cycle (0) | 2025.05.09 |
[leetcode] 119. Pascal's Triangle II (0) | 2025.05.08 |
[leetcode] 112. Path Sum (0) | 2025.05.08 |
[leetcode] 111. Minimum Depth of Binary Tree (0) | 2025.05.07 |