Sum of Even Numbers After Queries
Question
We have an array
A
of integers, and an arrayqueries
of queries.For the
i
-th queryval = queries[i][0], index = queries[i][1]
, we add val toA[index]
. Then, the answer to thei
-th query is the sum of the even values ofA
.(Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)
Return the answer to all queries. Your
answer
array should haveanswer[i]
as the answer to thei
-th query.
Example 1:
Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]] Output: [8,6,2,4] Explanation: At the beginning, the array is [1,2,3,4]. After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8. After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6. After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2. After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
1 <= queries.length <= 10000
-10000 <= queries[i][0] <= 10000
0 <= queries[i][1] < A.length
Approach 1: Maintain Array Sum
Intuition and Algorithm
Let's try to maintain S
, the sum of the array throughout
one query operation.
When acting on an array element A[index]
, the rest of
the values of A
remain the same. Let's remove
A[index]
from S
if it is even, then add
A[index] + val
back (if it is even.)
Here are some examples:
- If we have
A = [2,2,2,2,2]
,S = 10
, and we doA[0] += 4
: we will updateS -= 2
, thenS += 6
. At the end, we will haveA = [6,2,2,2,2]
andS = 14
. - If we have
A = [1,2,2,2,2]
,S = 8
, and we doA[0] += 3
: we will skip updatingS
(sinceA[0]
is odd), thenS += 4
. At the end, we will haveA = [4,2,2,2,2]
andS = 12
. - If we have
A = [2,2,2,2,2]
,S = 10
and we doA[0] += 1
: we will updateS -= 2
, then skip updatingS
(sinceA[0] + 1
is odd.) At the end, we will haveA = [3,2,2,2,2]
andS = 8
. - If we have
A = [1,2,2,2,2]
,S = 8
and we doA[0] += 2
: we will skip updatingS
(sinceA[0]
is odd), then skip updatingS
again (sinceA[0] + 2
is odd.) At the end, we will haveA = [3,2,2,2,2]
andS = 8
.
These examples help illustrate that our algorithm actually maintains
the value of S
throughout each query operation.
1 | class Solution: |
- Runtime: 180 ms, faster than 49.38% of Python3 online submissions forSum of Even Numbers After Queries.
- Memory Usage: 17.5 MB, less than 5.56% of Python3 online submissions for Sum of Even Numbers After Queries.