- Related Questions & Answers
- Sum of Even Numbers After Queries in Python
- 8085 program to find the sum of series of even numbers
- Array sum after dividing numbers from previous?
- Sum of squares of the first n even numbers in C Program
- Find Numbers with Even Number of Digits in Python
- Maximize Sum Of Array After K Negations in Python
- 8086 program to find sum of Even numbers in a given series
- Array sum after dividing numbers from previous in C?
- Find sum of even factors of a number in Python Program
- Python Program for Find sum of even factors of a number
- Prime numbers after prime P with sum S in C++
- Average of even numbers till a given even number?
- How to get the sum of the numbers in even positions in an array?
- Python program to print even numbers in a list
- Sum Root to Leaf Numbers 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): 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 ob1 = Solution() print(ob1.sumEvenAfterQueries([1,2,3,4], [[1,0],[-3,1],[-4,0],[2,3]]))

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

[8,6,2,4]

Advertisements