All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0901_1000.s0901_online_stock_span.StockSpanner Maven / Gradle / Ivy

There is a newer version: 1.37
Show newest version
package g0901_1000.s0901_online_stock_span;

// #Medium #Stack #Design #Monotonic_Stack #Data_Stream

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class StockSpanner {
    private final Map map;
    private final Deque stocks;
    private int index;

    public StockSpanner() {
        stocks = new LinkedList<>();
        index = -1;
        map = new HashMap<>();
        stocks.push(-1);
    }

    public int next(int price) {
        if (index != -1) {
            stocks.push(index);
        }
        map.put(++index, price);
        if (stocks.size() == 1) {
            return (index - stocks.peek());
        }
        while (stocks.size() > 1 && map.get(stocks.peek()) <= price) {
            stocks.pop();
        }
        return (index - stocks.peek());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy