Bloomberg | Phone | Marketdata

1731
Jun 24, 2022

Marketdata prices are stored sequentially by day. Determine how many days it takes for the price to increase. If there is no increase, the default shall be -1. The interviewer specified a List is received, and the output must be an array of ints.

public static int[] getDays(List<Integer> prices){
        int[] result = new int[prices.size()];
        Arrays.fill(result, -1);
        Deque<Integer> stack = new ArrayDeque<>();
        for (int index = 0; index < prices.size(); index++) {
            if (!stack.isEmpty() && prices.get(index) > prices.get(stack.getLast())) {
                int previous = stack.removeLast();
                result[previous] = index - previous;
            }
            while (!stack.isEmpty() && prices.get(index) > prices.get(stack.getFirst())) {
                int previous = stack.removeFirst();
                result[previous] = index - previous;
            }
            stack.addLast(index);
        }
       return result;
    }
Comments (2)