URL: https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray/ Signed-off-by: Matej Focko <me@mfocko.xyz>
20 lines
776 B
C#
20 lines
776 B
C#
public class Solution {
|
|
private record MonotonicAcc(int Increasing, int Decreasing, int Max) {
|
|
public MonotonicAcc() : this(1, 1, 1) { }
|
|
|
|
public MonotonicAcc Increase() => new(Increasing + 1, 1, Math.Max(Max, Increasing + 1));
|
|
public MonotonicAcc Decrease() => new(1, Decreasing + 1, Math.Max(Max, Decreasing + 1));
|
|
public MonotonicAcc Reset() => new(1, 1, Max);
|
|
}
|
|
|
|
public int LongestMonotonicSubarray(int[] nums) =>
|
|
nums.Zip(nums.Skip(1)).Aggregate(
|
|
new MonotonicAcc(),
|
|
(acc, pair) => pair switch {
|
|
_ when pair.First < pair.Second => acc.Increase(),
|
|
_ when pair.First > pair.Second => acc.Decrease(),
|
|
_ => acc.Reset(),
|
|
}
|
|
).Max;
|
|
|
|
}
|