From 523920f8df62975ae760a761c9a5443e1dea9d75 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:49:03 +0300 Subject: [PATCH] Add Maximum Subarray in C# --- archive/c/c-sharp/MaximumSubarray.cs | 63 ++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 archive/c/c-sharp/MaximumSubarray.cs diff --git a/archive/c/c-sharp/MaximumSubarray.cs b/archive/c/c-sharp/MaximumSubarray.cs new file mode 100644 index 000000000..876e78395 --- /dev/null +++ b/archive/c/c-sharp/MaximumSubarray.cs @@ -0,0 +1,63 @@ +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 in the format: \"1, 2, 3, 4, 5\""); + 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)) + ShowUsage(); + return val; + }) + .ToList(); + + if (list.Count == 0) + ShowUsage(); + + return list; + } + + private static int MaximumSubarraySum(IReadOnlyList numbers) + { + if (numbers.Count == 0) + return 0; + + int currentSum = numbers[0]; + int maxSum = numbers[0]; + + for (int i = 1; i < numbers.Count; i++) + { + int number = numbers[i]; + currentSum = Math.Max(number, currentSum + number); + maxSum = Math.Max(maxSum, currentSum); + } + + return maxSum; + } + + public static int Main(string[] args) + { + if (args.Length != 1) + ShowUsage(); + + var inputList = ParseIntegerList(args[0]); + + Console.WriteLine(MaximumSubarraySum(inputList)); + + return 0; + } +}