본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 121] Best Time to Buy and Sell Stock

by m2162003 2020. 10. 22.

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

 

Example 1:

Input: [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.   Not 7-1 = 6, as selling price needs to be larger than buying price.

 

Example 2:

Input: [7,6,4,3,1] Output: 0

Explanation: In this case, no transaction is done, i.e. max profit = 0.

 

문제 풀이:

- 처음 푼 방법: 매번 buy를 min으로 sell을 max로 업데이트함 =>에러. buy한다음에 sell을 해야 했기 때문에 index를 따져야 한다.

- 수정: 

 

 A B           A' B'가 있다고 하면(A'는 current 값, B'는 cur 다음 값)

if A<A'

then result = max(B-A, B'-A)

else

then result = max(B-A, B'-A')

B-A는 과거 result 값

buy는 매번 최소값으로 업데이트 한다.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int result = 0;
        
        if(prices.size() == 0){
            return 0;
        }
        
        int sell=0, buy=INT_MAX;
        for(int i=0; i<prices.size()-1; i++){
            if(prices[i] > prices[i+1]) continue;
            
            if(prices[i]>buy){
                result = max(prices[i+1] - buy, result);
            }else {
                result = max(prices[i+1] - prices[i], result);
            }
            buy = min(buy, prices[i]);
            
        }
        return result;
    }
};

댓글