Vasu090
Vasu090

Reputation: 79

Find the sum of consecutive elements efficiently - INOI 2015, Problem 1

I was recently solving this problem from INOI 2015. In this problem, you are given two arrays A and B and a special sum for the given arrays for two indices i and j is A[i]+A[j] plus the sum of the elements in the B array with indices between i and j. If you want to have a detailed explanation, refer here: Link to question paper. The question paper gives some examples and formal formulas to make the question clearer.

So, I went ahead with a O(n^2) time algorithm which follows.

#include <iostream>
#include <cmath>
using namespace std;

#define rep(i,a,b) for(auto (i)=a;i<b;i++)
#define list(i,N) for(auto (i)=0;i<N;i++)

int main(){

    int N; cin >> N;
    int A[N]; list(i,N) cin >> A[i];
    int B[N]; list(i,N) cin >> B[i];
    int prefix[N]; prefix[0] = B[0]; rep(i,1,N) prefix[i] = prefix[i-1]+B[i];

    int maxSum = A[0];
    list(i,N){
        list(j,N){
            if(i == j) maxSum = max(maxSum,A[i]);
            else if(i < j) maxSum = max(maxSum, A[i] + A[j] + prefix[j-1] - prefix[i]);
            else if(i > j) maxSum = max(A[i] + A[j] + prefix[N-1] + prefix[j-1] - prefix[i], maxSum);
        }
    }

    cout << maxSum;

    return 0;
}

Basically I am computing prefix sums for the array B and going through all the pairs of indices i, j.

Now, since this code runs in a O(n^2) time, I get a TLE on the last test cases but I was expecting to atleast solve the problem for the subtask 1. However, to my disappointment, this code even fails the last test case of the first subtask and some other test cases scattered around in the other subtaskes that is a WA (Wrong Answer). It gives the correct answer on the first two test cases and one another though. I get a TLE (Time Limit Exceeded) on the rest. I referred to this discussion: Commonlounge and the O(n^2) algorithm by everybody is the same algorithm which I am using. I also wanted to optimize my code, but unfortunately I am having some trouble understanding how to do it in O(n) time. Which is why I needed some help. What is apparently wrong? Some helpful hints would be nice too :).

Any help would be really appreciated...

Thank you!

Upvotes: 2

Views: 120

Answers (0)

Related Questions