알고리즘

Best Time to Buy and Sell Stock

point_Man 2023. 8. 23. 22:57

주식을 사고 파는 가장 좋은 시기

 

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

해당 날짜의 특정 주식 가격을 나타내는 prices배열 이 제공됩니다 .prices[i]ith

특정 주식을 구매할 하루를 선택하고 해당 주식을 판매할 미래의 다른 날을 선택 하여 수익을 극대화하려고 합니다 .

이 거래에서 얻을 수 있는 최대 이익을 반환합니다 . 이익을 얻을 수 없으면 0을 반환하십시오.

예시 1:

입력: 가격 = [7,1,5,3,6,4]
 출력: 5
 설명: 2일차에 매수(가격 = 1)하고 5일차에 매도(가격 = 6), 이익 = 6-1 = 5.
판매하기 전에 구매해야 하기 때문에 2일차에 구매하고 1일차에 판매하는 것은 허용되지 않습니다.

예 2:

입력: 가격 = [7,6,4,3,1]
 출력: 0
 설명: 이 경우 거래가 수행되지 않으며 최대 이익 = 0입니다.

제약:

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

1.첫번째 시도

 public int maxProfit(int[] prices) {

        int min = prices[0];
        int minIdx = 0;
        for(int i = 0 ; i < prices.length ; i++){
            if(min>prices[i]){
                min = prices[i];
                minIdx = i;
            }
        }

        int max = prices[minIdx];
        int maxIdx = 0;
        for(int i = minIdx ; i < prices.length ; i++){
            if(max<prices[i]){
                max = prices[i];
                maxIdx = i;
            }
        }
        return max-min;
    }

prices배열의 최소값의 인덱스와 최대값의 인덱스를 찾아서 그 인덱스의 값을 연산하여 해결하였다.

하지만

[2,4,1]에서 무작정 최소값과 최대값을 찾는 것이 정답이 아니라는 것을 확인하였다.

 

2.두번째 시도 (성공)

    public int maxProfit(int[] prices) {

       int currentprices = prices[0];
       int maxProfit = 0;

        for(int i = 0 ; i < prices.length; i++){
           //			내일가격  -  현재가격
            int income = prices[i] - currentprices;
            if(income < 0) { //음수면 내일가격이 더 적은 값
                currentprices = prices[i]; //내일 가격(더적은 값을)을 현재가격으로 치환  
            } 
            else { //양수면 기존 수익과 발생 수익을 비교하여 더 큰 수익을 반환                    
                maxProfit = Math.max(maxProfit, income);
            }


        }
        return maxProfit;

    }

내일가격 - 현재가격을 하여 음수가 나오면 내일의 주식가격이 낮은 것으로 판단하였고 

연산 결과 양수가 나오면 수익을 비교하여 가장 큰 수익을 반환하였다.

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

[Linked List] Linked List Cycle  (0) 2023.08.28
[Two Pointers] Valid Palindrome  (0) 2023.08.28
Rotate Array  (0) 2023.08.25
Remove Duplicates from Sorted Array  (0) 2023.08.24
Jump Game  (0) 2023.08.22