The imbalance across a split
A load balancer divides a batch at one index and wants the difference between the two halves.
- Sum the values strictly left of `at`, and the values from `at` onward inclusive.
- The answer is the left sum minus the right sum.
- A cut at or before the start takes all the weight as the right side: negate the whole sum.
- A cut at or past the end leaves everything on the left: just the whole sum.
SplitImbalance(values: list<int>, at: int) → int
C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
public int SplitImbalance(List<int> values, int at) {
}
Worked examples
| Call | Result |
|---|---|
SplitImbalance(new List<int> { 1, 2, 3, 4 }, 2) | -4 |
SplitImbalance(new List<int> { 5, 3, 8 }, 1) | -6 |
SplitImbalance(new List<int> { 1, 2, 3 }, 0) | -6 |
SplitImbalance(new List<int> { 1, 2, 3 }, 3) | 6 |
Hint
Handle the out-of-range slices first, then sum each side and subtract.
Reference solution in C#
public int SplitImbalance(List<int> values, int at) {
int total = 0;
foreach (var v in values) total += v;
if (at <= 0) return -total;
if (at >= values.Count) return total;
int left = 0;
for (int i = 0; i < at; i++) left += values[i];
int right = 0;
for (int i = at; i < values.Count; i++) right += values[i];
return left - right;
}