서하아빠의 개발 블로그

121. Best Time to Buy and Sell Stock 본문

알고리즘/LeetCode

121. Best Time to Buy and Sell Stock

서하아빠 2022. 5. 20. 19:39
 

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

 

문제설명

Stock의 가격이 배열로 주어지고 하루는 하루는 판다고 했을 때, 가장 큰 이익(maximum profit)을 구하는 문제

 

풀이설명

min과 result 변수를 선언하고 해당값들을 update해가면서 최대 이익을 계산함.

 

- min : for문을 순회하면서 가장 최저값을 업데이트

- result(최대이익) : 현재 주식가격 - 최저 주식(min) 값을 result값과 비교하면서 최대 값으로 업데이트 함 

class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null || prices.length <= 1)
            return 0;
        
        int min = prices[0];
        int result = 0;
        
        for(int i=0; i< prices.length; i++) {
            min = Math.min(min, prices[i]);
            result = Math.max(result, prices[i]-min);
        }
        return result;
        
    }
}

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

724. Find Pivot Index  (3) 2023.06.17
20. Valid Parentheses  (0) 2022.05.24
217. Contains Duplicate  (0) 2022.05.20
25. Reverse Nodes in k-Group  (0) 2022.05.20
61. Rotate List  (0) 2022.05.19