Given an array of integers prices representing daily closing prices of a financial asset, identify the longest contiguous trend in the data.
A trend is a maximal contiguous subarray where the prices are either strictly increasing or strictly decreasing. Return the length of the longest such trend.
If all elements are equal, the longest trend has length 1. A single element is considered a trend of length 1.
Function Signature
def longest_trend(prices: list[int]) -> int:
...
Rules
-
Two adjacent equal prices are neither increasing nor decreasing, so no trend of length 2 or more contains both of them.
-
The day where the direction changes belongs to both the trend that ends there and the trend that starts there. In
[1, 3, 2]
, both
[1, 3]
and
[3, 2]
are trends of length 2.
Constraints
-
1 <= len(prices) <= 10^5
-
-10^9 <= prices[i] <= 10^9
Examples
Input: prices = [1,2,3,2,1,4,5,6,7]
Output: 5
The longest trend is the strictly increasing subarray [1, 4, 5, 6, 7] of length 5. The earlier trends [1, 2, 3] and [3, 2, 1] have length 3.
Input: prices = [5,4,3,2,1,2,3]
Output: 5
The longest trend is the strictly decreasing subarray [5, 4, 3, 2, 1] of length 5. The rise that follows, [1, 2, 3], has length 3.
Input: prices = [1,1,2,2,3]
Output: 2
The equal pairs break every trend, which leaves [1, 2] and [2, 3] as the longest ones, each of length 2.