Leetcode - 122. Best Time to Buy and Sell Stock II

숲사람·2022년 9월 15일
0

멘타트 훈련

목록 보기
145/237

문제

i번째 인덱스는 해당 날의 주가를 의미한다. 날이 지날수록 사고팔고를 반복할수 있을때 가장 많은 수익금액은?

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.

해결 O(n)

그래프로 그리고 생각해보면 인접요소의 기울기가 양수인경우를 모두 더하면 가장 돈을 많이 번게 됨.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int sum = 0;
        for (int i = 0; i < prices.size() - 1; i++) {
            if (prices[i + 1] - prices[i] > 0)
                sum += prices[i + 1] - prices[i];
        }
        return sum;
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글