Help me in solving FINALSALE problem

My issue

Can you please help me to spot out the error in this code, Pls

My code

// We have populated the solutions for the 10 easiest problems for your support.
// Click on the SUBMIT button to make a submission to this problem.

#include<bits/stdc++.h>

using namespace std;

int main()
{
    long long int i, j, k, l, m, n, o, p;
    p = 0;
    n = 0;
    cin >> i;
    for (j = 0; j < i; j++) {
        cin >> k;
        vector < long long int > vec;
        for (l = 0; l < k; l++) {
            cin >> m;
            vec.push_back(m);
        }
        n = accumulate(vec.begin(), vec.begin() + (k - 1), 0);
        n = n + (vec[k - 1] * 2);
        p = n;
        for (o = k - 2; o >= 0; o--) {
            p = p - (vec[o + 1] * 2) - vec[o];
            p = p + (vec[o] * 2);
            if (p > n) {
                n = p;
            }
        }
        cout << n << endl;
        p = 0;
        n = 0;
    }

    return 0;

}

Problem Link: Sale Practice Coding Problem - CodeChef

Your logic is correct and solves the problem within the constraints, it’s even efficient (I think you have work on your variable names, it is a little hard to read).

Your problem is how you use the accumulate function.

  • The third argument of accumulate recives a number to work with, but it also takes the variable type. If you only send a 0, you are making it work with an int type which is then saved in a long long, but it’s overflowing in the meanwhile. You have to tell it explicitly the variable type, like this:
n = accumulate(vec.begin(), vec.begin() + (k - 1), (long long)0);

And there you go

1 Like