Skip to content

Commit

Permalink
Solve: best-me-to-buy-and-sell-stock
Browse files Browse the repository at this point in the history
  • Loading branch information
Jay-Mo-99 committed Jan 6, 2025
1 parent 79e797c commit bbf7576
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions best-time-to-buy-and-sell-stock/Jay-Mo-99.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
๏ปฟ #ํ•ด์„
#prices list๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ์ตœ์†Ÿ๊ฐ’ min_val์„ ์—…๋ฐ์ดํŠธ ํ•œ๋‹ค
#ํ˜„์žฌ prices[n]๊ณผ min_val์˜ ์ฐจ๋ฅผ ์—…๋ฐ์ดํŠธ ํ•ด์ค€๋‹ค.


#Big O
#N: prices ์˜ ํฌ๊ธฐ

#Time Complexity: O(N)
#- for loop : prices์˜ ์›์†Œ ๊ฐฏ์ˆ˜๋งŒํผ ์ˆœํšŒํ•˜๋ฏ€๋กœ O(N)


#Space Complexity: O(1)
#- min_val, answer : ๋ณ€์ˆ˜๋Š” ์ƒ์ˆ˜์ด๋ฏ€๋กœ O(1)
class Solution(object):
def maxProfit(self, prices):

#Initialize variables
min_val = prices[0]
answer = 0

for n in range(len(prices)):
min_val= min(min_val,prices[n]) #Update min value of the prices list
answer = max(prices[n]-min_val,answer) #Update max value of prices[n] - min value

return answer

0 comments on commit bbf7576

Please sign in to comment.