Let’s look at what happens during the first two iterations. We start with:
i = 0
d = 4
L = -5 -4 -3 -2 -1
R = 0
The greater element is L[d]
, so we add that, change the sign of L[i]
, and decrement d
, so now we have:
i = 0
d = 3
L = 5 -4 -3 -2 -1
R = -1
Now the greater element is L[i]
, so we add that, change the sign of L[d]
, and increment i
. So now we have:
i = 1
d = 3
L = 5 -4 -3 2 -1
R = 4
As you can see, after just two iterations the result is already positive, because we added 5
this time.
And on all future iterations, we’ll only add the numbers that have been made positive.
1
solved Why adding negative integers result in a positive integer on this C++ Program?