Sum of Even Numbers After Queries

We have an array A of integers, and an array queries of queries.

For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index].  Then, the answer to the i-th query is the sum of the even values of A.

(Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)

Return the answer to all queries.  Your answer array should have answer[i] as the answer to the i-th query.

Example:

Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<intsumEvenAfterQueries(vector<int&A,
                                vector<vector<int>> &queries)
{

    vector<int> res;
    int n = A.size();
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        if (A[i] % 2 == 0)
            sum += A[i];
    }
    for (int i = 0; i < queries.size(); i++)
    {
        int val = queries[i][0];
        int index = queries[i][1];
        if (A[index] % 2 == 0)
        {
            sum -= A[index];
        }
        A[index] = A[index] + val;
        if (A[index] % 2 == 0)
        {
            sum += A[index];
        }
        res.push_back(sum);
    }
    return res;
}

int main()
{
    vector<int> A = {1234};
    vector<vector<int>> queries = {{10}, {-31}, 
{-40}, {23}};

    vector<int> res = sumEvenAfterQueries(A, queries);

    for (int i = 0; i < res.size(); i++)
    {
        cout << res[i] << " ";
    }

    return 0;
}


No comments:

Post a Comment