-4

This program basically checks the two ends of a given interger sequence, adds the greatest of the two to R and changes the sign of the end we didn't choose. Repeats the process until there's only one number left (which is not add to R). The first line of the input specifies the quantity of intergers in the sequence and the others left is the sequence itself.

For example, if we input "5 5 4 3 2 1", we should get "14", because only the "1" doesn't get add to R.

For some reason when I input "5 -5 -4 -3 -2 -1" I'm getting an output of "10" instead of "-10".

#include <iostream>
using namespace std;

int main(void) {
    int N, *L, R = 0, i = 0, d = 0;
    cin >> N;
    L = new int[N];
    for (; i < N; ++i) cin >> L[i];
    i = 0;
    d = N - 1;
    while (d != i) {
        if (L[i] > L[d]){
            R += L[i];
            L[d] *= -1;
            ++i;
        }
        else {
            R += L[d];
            L[i] *= -1;
            --d;
        }
    }
    cout << R << endl;
    return 0;
}`
Xggggg
  • 1
  • 1
  • Step through the program with a debugger, I expect you'll see it. – Barmar Jun 08 '18 at 03:04
  • `L[d] *= -1;` changes the negative number to a positive number. – Barmar Jun 08 '18 at 03:05
  • This looks like a job for "How to debug small programs"... – John3136 Jun 08 '18 at 03:06
  • https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Barmar Jun 08 '18 at 03:06
  • Yeah but L[d] *= -1 only changes the integer we didn't add. – Xggggg Jun 08 '18 at 03:09
  • But you'll add it on the next iteration. – Barmar Jun 08 '18 at 03:10
  • The algorithm you describe ***should*** produce a result of `10` and not `-10` as you're expecting. When you change the sign of a -ve number remaining in the list it becomes +ve and greater than the -ve number at the other end. You then add the ***+ve*** number to R. So... the sequence `-5-4-3-2-1` adds the following: `-1+5+2+4=+10`; with `+3` remaining. Basically it seems your expectation is wrong. – Disillusioned Jun 08 '18 at 03:57

1 Answers1

0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks. I see that I flipped the wrong element in iteration 2, it should be `-2 => 2`, and that will be the next one added. – Barmar Jun 08 '18 at 05:37