Skip to content

Commit bbf7576

Browse files
committed
Solve: best-me-to-buy-and-sell-stock
1 parent 79e797c commit bbf7576

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
๏ปฟ #ํ•ด์„
2+
#prices list๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ์ตœ์†Ÿ๊ฐ’ min_val์„ ์—…๋ฐ์ดํŠธ ํ•œ๋‹ค
3+
#ํ˜„์žฌ prices[n]๊ณผ min_val์˜ ์ฐจ๋ฅผ ์—…๋ฐ์ดํŠธ ํ•ด์ค€๋‹ค.
4+
5+
6+
#Big O
7+
#N: prices ์˜ ํฌ๊ธฐ
8+
9+
#Time Complexity: O(N)
10+
#- for loop : prices์˜ ์›์†Œ ๊ฐฏ์ˆ˜๋งŒํผ ์ˆœํšŒํ•˜๋ฏ€๋กœ O(N)
11+
12+
13+
#Space Complexity: O(1)
14+
#- min_val, answer : ๋ณ€์ˆ˜๋Š” ์ƒ์ˆ˜์ด๋ฏ€๋กœ O(1)
15+
class Solution(object):
16+
def maxProfit(self, prices):
17+
18+
#Initialize variables
19+
min_val = prices[0]
20+
answer = 0
21+
22+
for n in range(len(prices)):
23+
min_val= min(min_val,prices[n]) #Update min value of the prices list
24+
answer = max(prices[n]-min_val,answer) #Update max value of prices[n] - min value
25+
26+
return answer
27+

0 commit comments

Comments
ย (0)