Skip to content

Commit 5845d93

Browse files
authored
Add Maximum Array Rotation in C# (#4876)
1 parent 20523f5 commit 5845d93

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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 (e.g. \"8, 3, 1, 2\")");
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) || val < 0)
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 MaximumRotationSum(IList<int> numbers)
35+
{
36+
int n = numbers.Count;
37+
if (n == 0)
38+
ShowUsage();
39+
40+
int totalSum = 0;
41+
int currentWeightedSum = 0;
42+
43+
for (int i = 0; i < n; i++)
44+
{
45+
totalSum += numbers[i];
46+
currentWeightedSum += numbers[i] * i;
47+
}
48+
49+
int maxWeightedSum = currentWeightedSum;
50+
51+
for (int i = 1; i < n; i++)
52+
{
53+
currentWeightedSum = currentWeightedSum + totalSum - n * numbers[n - i];
54+
if (currentWeightedSum > maxWeightedSum)
55+
maxWeightedSum = currentWeightedSum;
56+
}
57+
58+
return maxWeightedSum;
59+
}
60+
61+
public static int Main(string[] args)
62+
{
63+
if (args.Length != 1)
64+
ShowUsage();
65+
66+
var inputList = ParseIntegerList(args[0]);
67+
68+
Console.WriteLine(MaximumRotationSum(inputList));
69+
70+
return 0;
71+
}
72+
}

0 commit comments

Comments
 (0)