알고리즘

[leetcode] Best Time to Buy and Sell Stock

nayeonee__ 2023. 9. 30. 00:17

[문제]  https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

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

 

배열에 가격이 주어진다.

가격[i]은 그 날 주어진 주식의 가격이다.

하루만 주식을 사고 다른 한 날을 선택해서 주식을 판매하여 수익을 극대화 해야한다.

이 거래를 통해 얻을 수 있는 최대 이익을 반환하는 문제이다.

하지만 어떤 이익도 얻을 수 없다면 0을 반환해야한다.

 

 

[풀이 과정]

주어진 배열에서 가장 적은 가격과 가장 큰 가격을 구한다.

가장 적은 가격은 주어진 배열에서 가장 작은 가격이 나타나면 그 가격을 최소 가격으로 대입한다.

가장 큰 가격은 현재 가격에서 최소 가격을 뺀 금액과 저장된 큰 금액을 비교해서 큰 가격을 대입해서 반환한다.

 

 

 

[풀이 코드]

class Solution {
   public static int maxProfit(int[] prices) {
        int profitMin = Integer.MAX_VALUE;
        int profitMax = 0;

        for(int i = 0; i < prices.length; i++) {
            if (prices[i] < profitMin) {
                profitMin = prices[i];
            }
            profitMax = Math.max(profitMax, prices[i] - profitMin);
        }
        return profitMax;
    }
}

 

'알고리즘' 카테고리의 다른 글

[leetcode] Tow Sum  (0) 2023.10.13
[leetcode] Valid Parentheses  (0) 2023.10.03
[leetcode] ContainsDuplicate  (0) 2023.09.29
[백준] 2309 _ 일곱난쟁이  (0) 2023.09.19
[백준] 13300 _ 방배정  (0) 2023.09.19