Ctrl K

Spot the Price Trend in a Long History

Hard
The array prices holds a stock's price for each day, and the history can be very long. An analyst describes the movement they are looking for with an array trend made of -1, 0 and 1: 1 means the price went up the next day, 0 means it stayed the same, -1 means it went down. A segment of len(trend) + 1 consecutive days fits the trend if, for every j, the move from its j-th day to the next one is the one trend[j] asks for. Return the number of segments that fit. Segments may overlap. Checking the whole trend at every starting day is too slow here; aim for time linear in len(prices) + len(trend).
Example 1
prices=[4, 6, 6, 2, 3, 8, 8, 5, 5], trend=[1, 0, -1] → 2

The trend "up, flat, down" matches the segments [4, 6, 6, 2] and [3, 8, 8, 5].

Example 2
prices=[1, 2, 3, 4, 5], trend=[1, 1] → 3

Two rises in a row: [1, 2, 3], [2, 3, 4] and [3, 4, 5]; matching segments may overlap.

Example 3
prices=[7, 7], trend=[-1] → 0
Constraints
  • 2 ≤ len(prices) ≤ 10⁶
  • 1 ≤ prices[i] ≤ 10⁹
  • 1 ≤ len(trend) < len(prices)
  • each trend[j] is -1, 0 or 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFraming Word Pairs HardPhrase From Word Beginnings, Long Edition HardSpot the Price Trend MediumBookend Word Pairs EasyTarget From Word Beginnings Medium
loading Python…
Input
prices=[4, 6, 6, 2, 3, 8, 8, 5, 5], trend=[1, 0, -1]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 114 tests on the server, hidden ones included.