Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Online Stock Span

Posted on September 21, 2018July 26, 2020 by braindenny

Online Stock Span



Similar Problems:

  • LeetCode: Sum of Subarray Minimums
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #monotone, #buystock

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 backwards) 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 1:

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.

Note that (for example) S.next(75) returned 4, because the last 4 prices
(including today's price of 75) were less than or equal to today's price.

Note:

  1. Calls to StockSpanner.next(int price) will have 1 <= price <= 10^5.
  2. There will be at most 10000 calls to StockSpanner.next per test case.
  3. There will be at most 150000 calls to StockSpanner.next across all test cases.
  4. The total time limit for this problem has been reduced by 75% for C++, and 50% for all other languages.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
## https://code.dennyzhang.com/online-stock-span
## Basic Ideas: monotone stack
##
##   100, 80, 60, 70, 60, 75, 85
##
##   100, (80, ((60), 70, 60), 75), 85
## Complexity: Time O(n), Space O(n)
class StockSpanner:
    def __init__(self):
        self.stack = collections.deque()

    def next(self, price: int) -> int:
        # each item: val, cnt
        v = 1
        while len(self.stack)>0 and self.stack[-1][0]<=price:
            v += self.stack.pop()[1]
        self.stack.append((price, v))
        return v

# Your StockSpanner object will be instantiated and called as such:
# obj = StockSpanner()
# param_1 = obj.next(price)

  • Solution:
// https://code.dennyzhang.com/online-stock-span
// Basic Ideas: monotone stack
//
// For the previous prices, merge low prices into previous high prices
//
// If yesterday price is higher than today, it terminates the check.
//
// Complexity: Time O(n), Space O(n)
type MyNode struct {
    price int
    count int
}

type StockSpanner struct {
    nodes []MyNode
}

func Constructor() StockSpanner {
    return StockSpanner{nodes: []MyNode{}} 
}

func (this *StockSpanner) Next(price int) int {
    res := 1
    // Find all small prices and remove them out of stack
    for len(this.nodes)>0 && this.nodes[len(this.nodes)-1].price <= price {
        // good to extend our consecutive span
        res += this.nodes[len(this.nodes)-1].count
        this.nodes = this.nodes[0:len(this.nodes)-1]
    }
    this.nodes = append(this.nodes, MyNode{price, res})
    return res
}

/**
 * Your StockSpanner object will be instantiated and called as such:
 * obj := Constructor();
 * param_1 := obj.Next(price);
 */
linkedin
github
slack

Post Views: 0
Posted in MediumTagged buystock, monotone

Post navigation

LeetCode: Bitwise ORs of Subarrays
LeetCode: Smallest Range I

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.