- Related Questions & Answers
- Average numbers in array in C Programming
- C Program to Multiply two Floating Point Numbers?
- Sum of the numbers up to N that are divisible by 2 or 5 in c programming
- Sum of first n natural numbers in C Program
- Sum of squares of first n natural numbers in C Program?
- Sum of squares of the first n even numbers in C Program
- 10 Interesting Python Cool Tricks
- howdoi in Python
- How to print without newline in Python?
- How to download Google Images using Python
- How to clear screen in python?
- get() method for dictionaries in Python
- Generating random number list in Python
- gcd() function Python
- frozenset() in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an array of integers called A, and an array queries. For the i-th query value = queries[i][0] and index = queries[i][1], we will add value to A[index]. Then, the answer of the i-th query is the sum of the even values of A. We have to find the answer to all queries. We will find an array, that should have answer[i] as the answer to the i-th query. So if the array is like [1,2,3,4], and the query array is like [[1,0],[-3,1],[-4,0],[2,3]], then the answer array will be like [8,6,2,4]. So at first the array is [1,2,3,4], then after the first query, add 1 with A[0], then array will be [2,2,3,4], the sum of even values are 2 + 2 + 4 = 8. For the second query, it will add -3 with A[1], then the array will be [2,-1,3,4], so sum of even numbers 2 + 4 = 6. Like that we are getting the array [8,6,2,4]

To solve this, we will follow these steps −

- Define an array named res to store results
- sum := 0
- for each element i in A
- if i is even, then sum := sum + i

- for each query i in queries −
- index := i[1]
- val := i[0]
- if A[index] is even, then sum := sum – A[index]
- A[index] := A[index] + val
- if A[index] is even, then sum := sum + A[index]
- sum is appended to the res

- return res

Let us see the following implementation to get better understanding −

class Solution(object): def sumEvenAfterQueries(self, A, queries): """ :type A: List[int] :type queries: List[List[int]] :rtype: List[int] """ result = [] sum = 0 for i in A: if i%2==0: sum+=i for i in queries: index = i[1] val = i[0] if A[index] % 2==0: sum-=A[index] A[index]+=val if A[index]%2==0: sum+=A[index] result.append(sum) return result

[1,2,3,4] [[1,0],[-3,1],[-4,0],[2,3]]

[8,6,2,4]

Advertisements