From 249915a9e2257e1b8644a14837dc6deb639859a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C8=98tefan-Iulian=20Alecu?= <165364995+pascalecu@users.noreply.github.com> Date: Tue, 29 Jul 2025 00:43:18 +0300 Subject: [PATCH] Add Maximum Array Rotation in C# --- archive/c/c-sharp/MaximumArrayRotation.cs | 72 +++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 archive/c/c-sharp/MaximumArrayRotation.cs diff --git a/archive/c/c-sharp/MaximumArrayRotation.cs b/archive/c/c-sharp/MaximumArrayRotation.cs new file mode 100644 index 000000000..4eecb255b --- /dev/null +++ b/archive/c/c-sharp/MaximumArrayRotation.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public static class Program +{ + private static void ShowUsage() + { + Console.Error.WriteLine("Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")"); + Environment.Exit(1); + } + + private static List ParseIntegerList(string input) + { + if (string.IsNullOrWhiteSpace(input)) + ShowUsage(); + + var list = input + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(s => + { + if (!int.TryParse(s, out var val) || val < 0) + ShowUsage(); + return val; + }) + .ToList(); + + if (list.Count == 0) + ShowUsage(); + + return list; + } + + private static int MaximumRotationSum(IList numbers) + { + int n = numbers.Count; + if (n == 0) + ShowUsage(); + + int totalSum = 0; + int currentWeightedSum = 0; + + for (int i = 0; i < n; i++) + { + totalSum += numbers[i]; + currentWeightedSum += numbers[i] * i; + } + + int maxWeightedSum = currentWeightedSum; + + for (int i = 1; i < n; i++) + { + currentWeightedSum = currentWeightedSum + totalSum - n * numbers[n - i]; + if (currentWeightedSum > maxWeightedSum) + maxWeightedSum = currentWeightedSum; + } + + return maxWeightedSum; + } + + public static int Main(string[] args) + { + if (args.Length != 1) + ShowUsage(); + + var inputList = ParseIntegerList(args[0]); + + Console.WriteLine(MaximumRotationSum(inputList)); + + return 0; + } +}