Skip to content

985. Sum of Even Numbers After Queries

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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 auto& 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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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
Back to top