Drill

ProblemsC++ › data

The imbalance across a split

mediumdataPrefix sumsArraysC++

A load balancer divides a batch at one index and wants the difference between the two halves.

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.

Solve it in Python →

Where you start

int splitImbalance(std::vector<int> values, int at) {
    
}

Worked examples

CallResult
splitImbalance(std::vector<int>{1, 2, 3, 4}, 2)-4
splitImbalance(std::vector<int>{5, 3, 8}, 1)-6
splitImbalance(std::vector<int>{1, 2, 3}, 0)-6
splitImbalance(std::vector<int>{1, 2, 3}, 3)6

Hint

Handle the out-of-range slices first, then sum each side and subtract.

Reference solution in C++
int splitImbalance(std::vector<int> values, int at) {
    int total = 0;
    for (int v : values) total += v;
    if (at <= 0) return -total;
    if (at >= (int) values.size()) return total;
    int left = 0, right = 0;
    for (int i = 0; i < at; i++) left += values[i];
    for (int i = at; i < (int) values.size(); i++) right += values[i];
    return left - right;
}

The same problem in another language

More data problems in C++