Created
June 13, 2025 14:21
-
-
Save DimsFromDergachy/f2b8a06855afb930282a122de7224357 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // a - element | |
| // c - amount | |
| // answer is - p1.a * p1.c + p2.a * p2.c | |
| // Invariant: p2.a == p3.a | |
| using Triple = ((int a, int c) p1, (int a, int c) p2, (int a, int c) p3); | |
| internal static class SubArray | |
| { | |
| internal static int Solve(int[] xs) | |
| { | |
| Triple start = ((0, 0), (0, 0), (0, 0)); | |
| return xs.Scan(start, Next) | |
| .Max(t => t.p1.a * t.p1.c + t.p2.a * t.p2.c); | |
| } | |
| private static Triple Next(Triple prev, int x) | |
| { | |
| (var p1, var p2, var p3) = prev; | |
| if (p1.a == x) | |
| return (p2, p1.Increment(), x.Single()); | |
| if (p2.a == x) | |
| return (p1, p2.Increment(), p3.Increment()); | |
| return (p3, x.Single(), x.Single()); | |
| } | |
| private static (int a, int c) Single(this int x) => (x, 1); | |
| private static (int a, int c) Increment(this (int a, int c) p) => (p.a, p.c + 1); | |
| // Scan [1,2,3,4,5] 0 (+) => [0,1,3,6,10,15] | |
| internal static IEnumerable<TAccumulate> Scan<TSource, TAccumulate>( | |
| this IEnumerable<TSource> source, | |
| TAccumulate seed, | |
| Func<TAccumulate, TSource, TAccumulate> func) | |
| { | |
| yield return seed; | |
| foreach (var item in source) | |
| { | |
| seed = func(seed, item); | |
| yield return seed; | |
| } | |
| } | |
| } | |
| public class ArrayTest | |
| { | |
| [Theory] | |
| [InlineData(0 /*empty array*/)] | |
| [InlineData(4, 1, 1, 1, 1)] | |
| [InlineData(7, 1, 2, 3, 4)] | |
| [InlineData(7, 1, 2, 2, 1, 1, 3, 1, 1)] | |
| [InlineData(8, 1, 2, 2, 1, 1, 3, 3)] | |
| [InlineData(9, 1, 2, 2, 1, 1, 1, 3, 6)] | |
| [InlineData(8, 1, 2, 2, 1, 1, 1, 3, 2)] | |
| public void Test(int e, params int[] a) | |
| { | |
| Assert.Equal(e, SubArray.Solve(a)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
По мотивам статьи на Habr тоже решил попробовать решить примеры.
Решение "в лоб" получается чуть эффективнее (как по скорости, так и по памяти)
https://github.com/insanity13/sandbox/blob/main/Sandbox/SubArrays/readme.md