See the original problem on HackerRank.
John has been analyzing stocks and their prices as his latest assignment. Being a beginner in stocks, he has selected a stock HRC and collected the low, high and close prices for n days in the form of arrays:
- \(low\), where \(low_i\) is the lowest value of the stock on \(i^{th}\) day.
- \(high\), where \(high_i\) is the highest value of the stock on \(i^{th}\) day.
- \(close\), where \(\) is the closing value of the stock on \(i^{th}\) day.
Recently, he came across the concept of Gap Up and Gap Down.
The stock is considered Gap Up if on a given day it’s low price is higher than the previous day’s close price, and the stock is considered Gap Down if it’s high price is lower than the previous day’s close price.
Starting from the \(2^{nd}\) day till the \(n^{th}\) day count the number of Gap Up and Gap Down the stock went through during the \(n\) days.
Input Format
The first line contains an integer \(n\), the number of days for which the stock data is given.
The next line contains the array \(low\) represented by \(n\) space-separated integers, where \(low_i\) is the lowest value of the stock on the \(i^{th}\) day.
The next line contains the array \(high\) represented by \(n\) space-separated integers, where \(high_i\) is the highest value of the stock on the \(i^{th}\) day.
The next line contains the array \(close\) represented by \(n\) space-separated integers, where \(close_i\) is the close value of the stock on the \(i^{th}\) day.
Constraints
- \(2 \leq n \leq 10^5\)
- \(1 \leq low_i, high_i, close_i \leq 10^3\)
Output Format
Print two space-separated integers representing the number of Gap Up and Gap Down observed for the stock respectively.
Example
Input:
|
|
Output:
|
|
Explanation:
There is no Gap Up observed.
There are two Gap Downs observed:
- highPrice[4] closePrice[3]
- highPrice[5] closePrice[4]
So we print 0 and 2 as our answer.
Solutions
This challenge is quite easy: we run a loop from \(1\) to \(n\) and check the two given conditions:
- \(low[i] > close[i-1]\)
- \(high[i] < close[i-1]\)
We keep two counters, each counting the number of times each condition is true.
In C++:
|
|
To learn something more, we can see and code the combination of patterns zip | map | reduce which emerges from this problem.
In C++, we can use inner_product
(equivalent to transform_reduce
):
|
|
In Python:
|
|
It’s interesting to see how to use C++20’s ranges to solve this problem:
|
|
Clearly, all the solutions above do two iterations, one for accumulating low
and one for high
(might be an issue or not, think also about the cache…).
Just for fun, the following one, instead, does only one iteration - using C++20’ ranges:
|
|
Similarly, in Python:
|
|
An Haskell soution by alepez, with parser and serialization included:
|
|