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
21
22
23
24
class Solution {
 public:
  vector<int> sumEvenAfterQueries(vector<int>& nums,
                                  vector<vector<int>>& queries) {
    vector<int> ans;
    int sum =
        accumulate(nums.begin(), nums.end(), 0, [](int subtotal, int num) {
          return subtotal + (num % 2 == 0 ? num : 0);
        });

    for (const vector<int>& query : queries) {
      const int val = query[0];
      const int index = query[1];
      if (nums[index] % 2 == 0)
        sum -= nums[index];
      nums[index] += val;
      if (nums[index] % 2 == 0)
        sum += nums[index];
      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
21
22
class Solution {
  public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {
    int[] ans = new int[queries.length];
    int sum = 0;

    for (final int num : nums)
      sum += num % 2 == 0 ? num : 0;

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

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
    ans = []
    summ = sum(a for a in nums if a % 2 == 0)

    for val, index in queries:
      if nums[index] % 2 == 0:
        summ -= nums[index]
      nums[index] += val
      if nums[index] % 2 == 0:
        summ += nums[index]
      ans.append(summ)

    return ans