Best Buy and sell stocks

woori·2022년 11월 24일
0

2일차 best buy and sell stocks

문제 링크 : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

1차원 배열이 주어지고 각 배열의 index는 i번째 날의 가격임.
buy and sell 을 통해 얻을 수 있는 최대 이익을 계산하는 문제.

난이도 매우 easy 배열을 1번 순회하여 이전값보다 비싸면 앞의 날에서 buy 그 다음날 sell 하여 total profit 을 구한다.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int tot = 0;
        
        for(int i = 1; i< prices.size(); i++) {
            if( prices[i] > prices[i-1] ) {
                tot += prices[i] - prices[i-1];
            }
            
        }
        return tot;
    }
};

profile
기록하는개발자

0개의 댓글