user8305079
user8305079

Reputation:

Is it due to operator precedence?

I have the code below:

#include<algorithm>
#include<cstdio>
#include<iostream>
#include<vector>
#include<numeric>

using namespace std;

int maxScore(vector<int>& cardPoints, int k) {
    if(k==cardPoints.size()) return accumulate(cardPoints.begin(), cardPoints.end(), 0);

    int endSum=accumulate(cardPoints.begin()+(cardPoints.size()-k), cardPoints.end(), 0);
    int maxValue=endSum;
    int i=0;
    int j=cardPoints.size()-k;

    while(i<k && j<cardPoints.size()) {
        endSum-=cardPoints[j++]+cardPoints[i++];   //-> will change this line
        maxValue=max(maxValue, endSum);
    }

    return maxValue;
}

int main() {
    vector<int> v={100,40,17,9,73,75};
    cout<<maxScore(v, 3);

    return 0;
}

The output I get is: 157. However, if I change the line commented above as:

endSum=endSum-cardPoints[j++]+cardPoints[i++];

the output I get is 248. Live examples here and here respectively. I don't think I am doing anything different in the two statements above. I think it might be due to the post increment operations for i and j. Since all of them execute on a single line, I am unable to use any print statements to debug.

Could someone please point out why I am getting a different output?

Upvotes: 0

Views: 60

Answers (2)

John Kugelman
John Kugelman

Reputation: 361556

endSum -= cardPoints[j++] + cardPoints[i++];

The equivalent statement with = would be:

endSum = endSum - (cardPoints[j++] + cardPoints[i++]);

or

endSum = endSum - cardPoints[j++] - cardPoints[i++];

Upvotes: 1

cigien
cigien

Reputation: 60208

This line:

a -= b + c;

is equivalent to:

a = a - (b + c);

or

a = a - b - c;

which is not the same as:

a = a - b + c;

Upvotes: 2

Related Questions