Online Stock Span

Write a class StockSpanner which collects daily price quotes for some stock, and returns the span of that stock's price for the current day.

The span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the price of the stock was less than or equal to today's price.

For example, if the price of a stock over the next 7 days were [100, 80, 60, 70, 60, 75, 85], then the stock spans would be [1, 1, 1, 2, 1, 4, 6].

Example :

Input: ["StockSpanner","next","next","next","next","next","next","next"], [[],[100],[80],[60],[70],[60],[75],[85]]
Output: [null,1,1,1,2,1,4,6]
Explanation: 
First, S = StockSpanner() is initialized.  Then:
S.next(100) is called and returns 1,
S.next(80) is called and returns 1,
S.next(60) is called and returns 1,
S.next(70) is called and returns 2,
S.next(60) is called and returns 1,
S.next(75) is called and returns 4,
S.next(85) is called and returns 6.

Approach:

Java


import java.util.Stack;

public class OnlineStockSpan {
    public static void main(String[] args) {
        StockSpanner obj = new StockSpanner();
        System.out.print(obj.next(100) + " ");
        System.out.print(obj.next(80) + " ");
        System.out.print(obj.next(60) + " ");
        System.out.print(obj.next(70) + " ");
        System.out.print(obj.next(60) + " ");
        System.out.print(obj.next(75) + " ");
        System.out.print(obj.next(85));
    }
}

class StockSpanner {

    Stack<int[]> v = new Stack<int[]>();
    int x = -1;

    public StockSpanner() {
        v.add(new int[] { x, Integer.MAX_VALUE });
    }

    public int next(int price) {
        x++;
        while (!v.isEmpty() && v.peek()[1] <= price)
            v.pop();
        int res = x - v.peek()[0];
        v.add(new int[] { x, price });
        return res;

    }
}

C++

#include <bits/stdc++.h>
using namespace std;

class StockSpanner
{
public:
    vector<pair<intint>> v;
    int x = -1;

    StockSpanner()
    {
        v.push_back({xINT_MAX});
    }

    int next(int price)
    {
        x++;
        while (!v.empty() && v.back().second <= price)
            v.pop_back();
        int res = x - v.back().first;
        v.push_back({xprice});
        return res;
    }
};

int main()
{
    StockSpanner S;

    cout << "[";
    cout << S.next(100<< ", ";
    cout << S.next(80<< ", ";
    cout << S.next(60<< ", ";
    cout << S.next(70<< ", ";
    cout << S.next(60<< ", ";
    cout << S.next(75<< ", ";
    cout << S.next(85);
    cout << "]";

    return 0;
}


No comments:

Post a Comment