Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Sum of Even Numbers After Queries in Python



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

Example

Let us see the following implementation to get better understanding −

 Live Demo

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]]))

Input

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

Output

[8,6,2,4]
Updated on: 2020-04-28T17:19:35+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements