Skip to content

Instantly share code, notes, and snippets.

@DimsFromDergachy
Created June 13, 2025 14:21
Show Gist options
  • Select an option

  • Save DimsFromDergachy/f2b8a06855afb930282a122de7224357 to your computer and use it in GitHub Desktop.

Select an option

Save DimsFromDergachy/f2b8a06855afb930282a122de7224357 to your computer and use it in GitHub Desktop.
// 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));
}
}
@insanity13
Copy link

insanity13 commented Jul 15, 2025

По мотивам статьи на Habr тоже решил попробовать решить примеры.
Решение "в лоб" получается чуть эффективнее (как по скорости, так и по памяти)
https://github.com/insanity13/sandbox/blob/main/Sandbox/SubArrays/readme.md

Method Mean Error StdDev Gen0 Allocated
DimsFromDergachyVersion 27.065 ms 0.0228 ms 0.0202 ms 93.7500 839936 B
DenisNP_Version 79.534 ms 0.3393 ms 0.3174 ms - 959584 B
MySolutionVersion 8.913 ms 0.0088 ms 0.0082 ms - 32 B

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment