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:
parent
349e7a8914
commit
5048736010
1 changed files with 20 additions and 0 deletions
|
@ -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;
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue