Menu
CoddyTech

Stock Span Problem

You get the closing price of a stock on each day: prices[i] is the price on day i. The span of day i is the number of days in a row, ending with day i and counting it, on which the price was less than or equal to prices[i].

Return every day's span, in the same order as prices. Every span is at least 1, because a day always counts itself.

Function

stockSpan(prices: integer-array) → integer-array
pricesinteger-array
the price on each day, in order
Returnsinteger-array
the span of every day, in the same order

Constraints

  • 1 ≤ prices.length ≤ 104
  • 1 ≤ prices[i] ≤ 105
  • An earlier day with the same price counts toward the span; only a strictly higher price stops it.

Examples

Input
prices = [31, 27, 14, 21, 30, 18, 40]
Output
[1, 1, 1, 2, 4, 1, 7]
Explanation
Day 3 at 21 reaches back over 14 and stops at 27: span 2. Day 4 at 30 stops at 31: span 4. Day 6 at 40 tops every earlier price and covers all 7 days.
challenge icon

Follow-up

Prices now arrive one at a time, and you must report each span as its price comes in. Which approach still works, and what does it keep between calls?

Reset code
def stockSpan(prices):
    # Write code here

Test #1

Test #2

Test #3

Argument

prices = [31, 27, 14, 21, 30, 18, 40]

Expected Output

[1, 1, 1, 2, 4, 1, 7]