Skip to content

Commit f14d2d0

Browse files
committed
Add Maximum Subarray in C# (TheRenegadeCoder#4877)
1 parent f826827 commit f14d2d0

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
5+
public static class Program
6+
{
7+
private static void ShowUsage()
8+
{
9+
Console.Error.WriteLine("Usage: Please provide a list of integers in the format: \"1, 2, 3, 4, 5\"");
10+
Environment.Exit(1);
11+
}
12+
13+
private static List<int> ParseIntegerList(string input)
14+
{
15+
if (string.IsNullOrWhiteSpace(input))
16+
ShowUsage();
17+
18+
var list = input
19+
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
20+
.Select(s =>
21+
{
22+
if (!int.TryParse(s, out var val))
23+
ShowUsage();
24+
return val;
25+
})
26+
.ToList();
27+
28+
if (list.Count == 0)
29+
ShowUsage();
30+
31+
return list;
32+
}
33+
34+
private static int MaximumSubarraySum(IReadOnlyList<int> numbers)
35+
{
36+
if (numbers.Count == 0)
37+
return 0;
38+
39+
int currentSum = numbers[0];
40+
int maxSum = numbers[0];
41+
42+
for (int i = 1; i < numbers.Count; i++)
43+
{
44+
int number = numbers[i];
45+
currentSum = Math.Max(number, currentSum + number);
46+
maxSum = Math.Max(maxSum, currentSum);
47+
}
48+
49+
return maxSum;
50+
}
51+
52+
public static int Main(string[] args)
53+
{
54+
if (args.Length != 1)
55+
ShowUsage();
56+
57+
var inputList = ParseIntegerList(args[0]);
58+
59+
Console.WriteLine(MaximumSubarraySum(inputList));
60+
61+
return 0;
62+
}
63+
}

0 commit comments

Comments
 (0)