넘치게 채우기

[LeetCode] 122. Best Time to Buy and Sell Stock II 본문

PS/LeetCode

[LeetCode] 122. Best Time to Buy and Sell Stock II

riveroverflow 2023. 7. 8. 13:13
728x90
반응형

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/?envType=study-plan-v2&envId=top-interview-150 

Best Time to Buy and Sell Stock II - LeetCode

Can you solve this real interview question? Best Time to Buy and Sell Stock II - You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock. You can only hold

leetcode.com

문제 유형 : 그리디 / 배열
문제 난이도 : Medium
 
 
문제
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
 
당신은 같은 날에 주식을 사고 팔 수 있습니다. 기간 동안 얻을 수 있는 가장 큰 수익을 구하시오. 주식을 가지고 있는 것은 단 하나의 주식만 가능합니다.
 
 
풀이
오늘 가격이 내일 가격보다 저렴하면 무조건 오늘 사고, 내일 팔면 된다. 이것이 최선의 수익을 얻는 방법이다.
[1, 2, 3, 4, 5]를 예로 들었을때, 1에서 사서 5일때 팔는게 한번에 가장 큰 이득이지만,
단순히 1에서 사고 2에서 판매, 2에서 사고 3에서 판매하는 등의 과정을 거쳐도 같은 결과를 얻는다.
[7, 1, 5, 3, 6, 4]에서도 그때그때 이득을 보면 최선의 수익을 얻을 수 있다.

 
코드(C++)

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        const int n = prices.size();
        int profit = 0;

        for(int i = 0; i < n-1; i++){
            const auto curr = prices[i];
            const auto next = prices[i+1];
            if(next-curr > 0){
                profit += next-curr;
            }
        }

        return profit;
    }
};

 

728x90
반응형

'PS > LeetCode' 카테고리의 다른 글

[LeetCode] 111. Minimum Depth of Binary Tree  (0) 2023.07.10
[LeetCode] 55. Jump Game  (0) 2023.07.09
[LeetCode] 189. Rotate Array  (0) 2023.07.07
[LeetCode] 169. Majority Element  (0) 2023.07.06
[LeetCode] 137. Single Number II  (0) 2023.07.04