Online Stock Span

ㅋㅋ·2022년 11월 9일
0

알고리즘-leetcode

목록 보기
47/135

날마다의 주식 가격이 적힌 벡터 데이터를 받고,

날자별 가격이 며칠 연속 최고가 인지 계산하는 문제

다른 사람들 하는 걸보니 스택을 사용하여 푸는 것이 정석 같다.

class StockSpanner {
    vector<int> _store;
    int _head;
    int _tail;

public:
    StockSpanner() {
        _store.clear();
        _head = 0;
        _tail = 0;
    }
    
    int next(int price) {
        
        _store.push_back(price);
        if (_store.size() == 1)
        {
            return 1;
        }

        _tail++;

        if (_store[_tail - 1] > _store[_tail])
        {
            _head = _tail;
        }

        while (0 < _head && _store[_head - 1] <= _store[_tail])
        {
            _head--;
        }

        return _tail - _head + 1;
    }
};

/**
 * Your StockSpanner object will be instantiated and called as such:
 * StockSpanner* obj = new StockSpanner();
 * int param_1 = obj->next(price);
 */

0개의 댓글