2021년/알고리즘

[파이썬 인터뷰 알고리즘] 주식을 살고팔기 가장 좋은 시점

위지원 2021. 3. 18. 21:32

(12) 주식을 살고팔기 가장 좋은 시점

★ Easy

github.com/onlybooks/algorithm-interview

 

[LeetCode]

 

Best Time to Buy and Sell Stock - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


min_price는 문제에서 10^4가 최대라고 해서 그거보다 그냥 크게 줬다.

지금까지 가장 작았던 값에서 계속 빼면 되는 EZ problem 

 

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        revenue = 0
        min_price = 100000
        for price in prices:
            min_price = min(price, min_price)
            revenue = max(revenue, price-min_price)
        
        return revenue
        

 

자바로도 풀었다. 

class Solution {
    public int maxProfit(int[] prices) {
        int revenue = 0;
        int min_price = 100000;

        for (int price : prices) {
            min_price = Math.min(min_price, price);
            revenue = Math.max(revenue, price - min_price);
        }
        return revenue;
    }
}

 

Go도 이용해봤다.


func maxProfit(prices []int) int {
	revenue, min_price := 0.0, 100000.0
	for _, price := range prices {
		min_price = math.Min(float64(price), float64(min_price))
		revenue = math.Max(float64(revenue), float64(price)-float64(min_price))
	}
    return int(revenue)
}

ㅎ  .. 확실히 파이썬이 느리다;;