andre - 2 months ago 10

C++ Question

Given an array, I would like to find an index, that the numbers before it, and the numbers after it gives equal sum.

for example an array like

`[4,5,6,11,7,8]`

output is index

`3`

`4+5+6 = 7+8`

Answer

First find sum of all items, save it as `sum`

, then read from start of array and sum up items to arrive to `(sum - current index value)/2`

, if you didn't get such result, means there isn't such an index, also if you get `sum/2`

in each index of iteration, means related index is your answer.

Sample: `4,5,6,11,7,8`

sum = 41.

```
check index 0: currentSum = 4, currentSum - currentValue = 4-4 != (41 - 4)/2
check index 1: currentSum = 9, currentSum - currentValue = 9-5 != (41 - 5)/2
check index 2: currentSum = 15, currentSum - currentValue = 15-6 != (41 - 6)/2
check index 3: currentSum = 26, currentSum - currentValue = 15 == (41 - 11)/2
```