반응형
Recent Posts
Notice
Recent Comments
Link
250x250
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

지식창고

[Java] LeetCode 121. Best Time to Buy and Sell Stock 본문

Algorithm/Leetcode

[Java] LeetCode 121. Best Time to Buy and Sell Stock

junz 2023. 2. 25. 16:27
728x90
반응형

[Java] LeetCode 121. Best Time to Buy and Sell Stock

 

문   제 : 

날에 따른 주식의 가격을 나타내는 일 차원 정수 배열 prices[] 가 주어진다.

주식을 한 개 사서 판다고 가정했을 때,  가장 최대의 이익을 얻을 수 있을 때, 그 이익은 얼마인가?

 

Constraint

{ 1 <= prices.length <= 10^5 }

{ 0 <= prices[i] <= 10^4 }

 

 

Example )

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: 
Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed 
because you must buy before you sell.

//////////////////////////////////////////////////////////

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: 
In this case, no transactions are done and the max profit = 0.

 



접   근 : 

최소의 가격으로 사서 최대의 가격에 판다.


해   결 : 

prices배열을 돌면서 가장 싼 주식을 최신화 해준다.

가장 싼 주식을 현재가에 팔았을 때의 이익을 최대이익과 비교해 최신화 해준다.


결   과  :

class Solution {
    public int maxProfit(int[] prices) {
        int profit=0;
        int buyStock = Integer.MAX_VALUE;

        for(int i=0; i<prices.length; i++){
            buyStock = Math.min(buyStock, prices[i]);
            profit = Math.max(profit, prices[i] - buyStock);
        }

        return profit;
    }
}
728x90
반응형
Comments