cs: add «3105. Longest Strictly Increasing or Strictly Decreasing Subarray»

URL:	https://leetcode.com/problems/longest-strictly-increasing-or-strictly-decreasing-subarray/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-03 15:41:24 +01:00
parent 349e7a8914
commit 5048736010
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,20 @@
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;
}