CK week4 day2

BnDCยท2021๋…„ 10์›” 12์ผ
0

code Kata

๋ชฉ๋ก ๋ณด๊ธฐ
17/22

๐Ÿงจ ๋ฌธ์ œ

prices๋Š” ๋ฐฐ์—ด์ด๋ฉฐ, ๊ฐ ์š”์†Œ๋Š” ๋งค์ผ์˜ ์ฃผ์‹ ๊ฐ€๊ฒฉ์ด๋‹ค. ํ•œ ๋ฒˆ์”ฉ๋งŒ ์‚ฌ๊ณ  ํŒ” ์ˆ˜ ์žˆ๋‹ค๋ฉด,
์ œ์ผ ํฐ ์ด์ต์€ ์–ผ๋งˆ์ธ์ง€ ๊ณ„์‚ฐํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด๋ผ


input: [7, 1, 5, 3, 6, 4]
output: 5

1(2์ผ)์—์„œ ์‚ฌ์„œ 6(5์ผ)์— ํŒŒ๋Š” ๊ฒƒ์ด ๊ฐ€์žฅ ํฐ ์ˆ˜์ต
(๋ฏธ๋ž˜์ธ 1์—์„œ ์‚ฌ์„œ, ๊ณผ๊ฑฐ 7์—์„œ ํŒŒ๋Š” ๊ฒƒ ์•ˆ๋Œ)

input: [7, 6, 4, 3, 1]
output: 0

๋งค์ผ ๊ฐ€๊ฒฉ์ด ๋‚ฎ์•„์ง€๊ธฐ ๋•Œ๋ฌธ์— ์ˆ˜์ต์ด ์—†์Œ






๐ŸŽฏ ๋‚ด ํ’€์ด

def maxProfit(prices): 
#step1
    after_price = []
    result = set()

#step2
    for price in sorted(prices):
    
        if prices.index(price) != len(prices) - 1:
            after_price = prices[prices.index(price) + 1:]
            
        else:
            after_price = [price]
            
#step3
        profit = max(after_price) - price
        
        if after_price and profit >= 0:
          result.add(profit)
    
    return max(result)
    

๊ฐ€๊ฒฉ์„ ๋‚ฎ์€ ๊ฐ€๊ฒฉ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ ๋ฆฌ์ŠคํŠธ๋ฅผ for๋ฌธ์œผ๋กœ ์ˆœํšŒํ•˜๋ฉด์„œ, ๊ฐ๊ฐ์— ๋Œ€ํ•ด ๊ฐ€์žฅ ํฐ ์‹œ์„ธ ์ฐจ์ต์„ ๊ณ„์‚ฐํ•œ๋‹ค

์‹œ์„ธ ์ฐจ์ต์ด 0์ด์ƒ์ด๋ฉด, ๊ทธ ๊ฐ’์„ result์— ๋‹ด๊ณ 
๊ฐ€์žฅ ํฐ result๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.




๐Ÿ“ step1

def maxProfit(prices): 
#step1
    after_price = []
    result = set()

ํŠน์ • ๊ฐ€๊ฒฉ์ผ ๋•Œ, ๊ทธ ๊ฐ€๊ฒฉ ์ดํ›„์˜ ๊ฐ€๊ฒฉ์„ ์ €์žฅํ•  after_price, ์‹œ์„ธ ์ฐจ์ต์„ ๋‹ด์„ result๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.




๐Ÿ“ step2

def maxProfit(prices): 
#... ...#

#step2
    for price in sorted(prices):
    
        if prices.index(price) != len(prices) - 1:
            after_price = prices[prices.index(price) + 1:]
            
        else:
            after_price = [price] 

์ •๋ ฌ๋œ prices๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ, price ๋’ค์— ๋ฆฌ์ŠคํŠธ๋ฅผ ์ž˜๋ผ after_price์— ๋‹ด๋Š”๋‹ค.

๋งŒ์•ฝ price๊ฐ€ prices ๋ฆฌ์ŠคํŠธ์˜ ๊ฐ€์žฅ ๋ ์š”์†Œ์ด๋ฉด, after_price๋ฅผ price๋งŒ์„ ์›์†Œ๋กœ ๊ฐ–๋Š” ๋ฆฌ์ŠคํŠธ๋กœ ์ดˆ๊ธฐํ™” ํ•œ๋‹ค.




๐Ÿ“ step3

def maxProfit(prices): 
#... ...#

#... ...#
            
#step3
        profit = max(after_price) - price
        
        if after_price and profit >= 0:
          result.add(profit)
    
    return max(result)

profit ์ด 0๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๋‹ค๋ฉด, result์— ์ถ”๊ฐ€ํ•˜๊ณ  result์˜ max๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

profile
โ€œLife is C (Choice) between B (Birth) and D (Death).โ€ - ์ธ์ƒ์€ B์™€ D์‚ฌ์ด์˜ C

0๊ฐœ์˜ ๋Œ“๊ธ€