본문 바로가기
Algorithm

[leetCode 121] Best Time to Buy and Sell Stock (Java)

by ddahu 2023. 8. 24.

1.문제

Best Time to Buy and Sell Stock - LeetCode

 

Best Time to Buy and Sell Stock - LeetCode

Can you solve this real interview question? Best Time to Buy and Sell Stock - You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosin

leetcode.com


2. 문제 설명

 

이 문제는 다른 코딩테스트 연습 사이트에서도 자주나오는 Stock 계산 문제이다. 어느 시점에서 사야지 최고의 이익을 볼 수 있는 문제이다.


3. 소스 코드

public static int maxProfit(int[] price){
        int minPrice = Integer.MAX_VALUE;
        int maxProift = 0;

        for(int pr : price){
            if(pr < minPrice ){
                minPrice = pr;
            } else if (pr - minPrice > maxProift) {
                maxProift = pr - minPrice;
            }
        }
        return maxProift;
    }

4. 문제 해설

 

이 문제는 어느 시점에서 사야지 가장 최고의 이익을 볼 수 있는가를 확인 하기 위해서 Max / Min 알고리즘 과 그리디 알고리즘을 사용한다.

 

MIn 은 최대치 로 설정하여 최솟값을 초기화 하고, Max 는 Integer.MIN_VALUE; 를 사용해도되지만 이문제에서 이익이 없을 경우도 있기 떄문에 0 으로 초기화 한다.

 

for 문을 돌면서 최솟값을 찾고 현재 가격에서 - 최소 가격을 뺀 것이 제일 비싼 것 일 경우에 최댓 값을 현재 가격 - 최소 가격으로 정하면 간단하게 풀 수 있다.