0

We have an array having n integers whose sum is non negative.

I need to prove that there exists an index i, such that starting from i, all prefix sums are non negative, till we reach i again circularly.

Say the array is a1, a2, a3, ..... , an, such that a1 + a2 + a3 + ..... + an>=0.

So we need to prove that for some index i, all prefix sums are non-negative, i.e,
ai >= 0,
ai + ai+1 >=0,
ai + ai+1 + ai+2 >=0
.
.
ai + ai+1 + ... + an + a1 + .... + ai-1 >=0

I need this for the following question, https://www.interviewbit.com/problems/gas-station/. Though I've already used the above statement in the solution of this question, but I am still not able to prove it.

sahil
  • 21
  • 5

3 Answers3

2

Suppose we repeat the array multiple times and then construct the prefix sums of this repeated array. The prefix sums will have the same pattern, except each repetition is higher by an amount equal to the sum of the array.

Consider the index x where the prefix sum is the smallest. This will occur within the first n samples (if the sum of the array is positive).

If you start computing prefix sums from this position x, then all subsequent prefix sums will be non-negative by construction.

Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75
0

Given the premise that you need to prove that there exists at least 1 index for which the property holds, I would propose the opposite to be true (i.e. for every index it holds that at least one prefix sum is negative), then deduce a contradiction implicating that it must be true that at least one index holds this property.

Glubus
  • 2,819
  • 1
  • 12
  • 26
0

Across all pairs of indices {j, k} there exists one such pair with minimal (maximially negative) sum(j, k). Set i = k+1.

If there exists some sequence a(i), a(i+1), ... a(i+n) for n not in the range {j...k} such that sum(i, n) is negative (i.e., a negative prefix sum), then that would mean sum(j, n) < sum(j, k), which contradicts our initial statement. (This is true because sum (j, n) = sum (j, k) + sum (k+1, n) = sum(i, n), and we claim sum (i, n) to be negative.)

If there exists some n in the range {j...k} such that sum(a, n) is negative, then that means that sum(k+1, j-1) + sum(j, n) < 0. As we know the complete sum to be positive, sum(k+1, j-1) + sum (j, k) > 0 (as that includes all elements.) Therefor sum(j, n) < sum(j, k), which contradicts our initial constraint.

QED

Edward Peters
  • 3,623
  • 2
  • 16
  • 39