While computing the maximum rise in a stock price is useful for analysis, it does not accurately capture the pattern of price rises. A single rise in value could be an outlier.
A better way to capture the pattern of price rises is to compute, for each price point, the first subsequent rise in its value. Once these rises have been computed for each price point, further analysis can be performed to study the stock behavior more thoroughly.
The problem: For each price of the stock, we compute the first rise in its value; i.e., for each \( i \), we compute first_rise[i] = prices[j] - prices[i]
, where \( j \) is the first index after \( i \) for which prices[j] > prices[i]
.
If no such \( j \) exists for an \( i \), then first_rise[i] = -1
. Consequently, first_rise[n-1] = -1
(where \( n \) is the length of the input).
Firgure 1 below shows a plot of price values and the first rises in their values (the red arrows).
The simple method to compute all first rises checks for each point \( i \), the points \( j > i \) corresponding to the first increase in price value after \( i \). As a warm-up, implement the following function stub using this straightforward approach. However, try not to be wasteful during the process; specifically, as soon the first rise is found for a price point there is no need to look at the subsequent prices.
Use the following main to test your function:
A better method is based on the following observations:
prices[j] > prices[j-1]
is the required point for first_rise[j-1]
.prices[j-k]
, where \( k = 1, 2, 3, ... \), as long as prices[j-k] < prices[j]
.The stack-based solution for this problem is mappable (with small alterations) to the Balanced Brackets problem.
Consider the following comparison:
Implement the first_rises function using the refined approach. Use the same main as above to test your code.