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

link : https://leetcode.com/problems/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 choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

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.

Example 2:

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

포인트

1. 가장 큰 차익을 남길수 있는 날짜를 어떻게 고르느냐에 대한 문제

2. 차익을 낼 수 있는건 '오늘'보다 '내일'의 가격이 높아야한다는 점

3. 계산을 할 때마다 차익의 max값과 기준이 되는 요일을 바꿔줘야한다.

풀이

class Solution {
    public static int maxProfit(int[] prices) {

        int max =0; //차익의 최대값
        int arr = 0; //기준 날짜, 첫째날을 기준으로 시작한다.
        for(int i=1;i<prices.length;i++) {
            if(prices[i] > prices[arr]) { 
                max = Math.max(max, prices[i]-prices[arr]);
            }else {
                arr = i;
            }    
        }
        return max;
    }
}

if문 해석

1. '어제'보다 '오늘'가격이 높다면 차익을 낼 수 있다는 말이므로 차이를 구한다음 max값을 갱신해준다

2. else ==> '어제'보다 '오늘'가격이 낮다면 이 날을 기준으로 해야 시세차익을 더 크게 낼 수 있다.

이번 문제는 코드를 짜는것은 크게 어렵지 않았지만 그 구조를 만드는게 포인트이다.

+ Recent posts