Stock Price Span Calculator
In financial markets, analyzing stock price trends is crucial for making informed decisions. One common technical indicator is the "price span," which helps identify how long a stock has maintained or increased its value relative to recent history. This problem challenges you to implement an efficient algorithm to calculate this span for a given series of daily stock prices.
Implement the function calculateSpan that takes an array of daily stock prices. For each day, you need to calculate its "span". The span of a stock's price today is defined as the maximum number of consecutive days immediately preceding the current day (and including the current day) for which the stock price was less than or equal to today's price.
Your function should return an array where each element i corresponds to the calculated span for prices[i].
prices: number[]
number[]
result[i] is the calculated span for prices[i]. Each span value will be a positive integer.prices array is always 1, as there are no preceding days.less than or equal to condition, the streak is broken, and you only count days up to that point (including the current day).Examples
Example 1
Input:
prices = [100, 80, 60, 70, 60, 75, 85]
Output:
[1,1,1,2,1,4,6]
Note:
Let's trace:
Example 2
Input:
prices = [10, 4, 5, 90, 120, 80]
Output:
[1,1,2,4,5,1]
Note:
Spans are calculated as follows:
Example 3
Input:
prices = [1, 2, 3, 4, 5]
Output:
[1,2,3,4,5]
Note:
For a strictly increasing sequence, each day's price is greater than or equal to all preceding prices, resulting in spans of 1, 2, 3, 4, 5.
Constraints
1 <= prices.length <= 10^51 <= prices[i] <= 10^9prices[i] are integers.Loading editor...