LeetCode Solutions

985. Sum of Even Numbers After Queries

Time:

Space:

			

class Solution {
 public:
  vector<int> sumEvenAfterQueries(vector<int>& A,
                                  vector<vector<int>>& queries) {
    vector<int> ans;
    int sum = accumulate(begin(A), end(A), 0,
                         [](int a, int b) { return a + (b % 2 == 0 ? b : 0); });

    for (const vector<int>& q : queries) {
      if (A[q[1]] % 2 == 0)
        sum -= A[q[1]];
      A[q[1]] += q[0];
      if (A[q[1]] % 2 == 0)
        sum += A[q[1]];
      ans.push_back(sum);
    }

    return ans;
  }
};
			

class Solution {
  public int[] sumEvenAfterQueries(int[] A, int[][] queries) {
    int[] ans = new int[queries.length];
    int sum = 0;

    for (int a : A)
      sum += a % 2 == 0 ? a : 0;

    for (int i = 0; i < queries.length; ++i) {
      if (A[queries[i][1]] % 2 == 0)
        sum -= A[queries[i][1]];
      A[queries[i][1]] += queries[i][0];
      if (A[queries[i][1]] % 2 == 0)
        sum += A[queries[i][1]];
      ans[i] = sum;
    }

    return ans;
  }
}
			

class Solution:
  def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
    ans = []
    summ = sum(a for a in A if a % 2 == 0)

    for q in queries:
      if A[q[1]] % 2 == 0:
        summ -= A[q[1]]
      A[q[1]] += q[0]
      if A[q[1]] % 2 == 0:
        summ += A[q[1]]
      ans.append(summ)

    return ans