[
array
simulation
]
Leetcode 0985. Sum of Even Numbers After Queries
Problem statement
https://leetcode.com/problems/sum-of-even-numbers-after-queries/
Solution
Simulate process, each time recalculate sum in O(1)
.
Complexity
It is O(n + q)
, where n = len(nums)
and q = len(queries)
.
Code
class Solution:
def sumEvenAfterQueries(self, nums, queries):
sm = sum(i for i in nums if i%2 == 0)
ans = []
for val, idx in queries:
x, y = nums[idx], nums[idx] + val
if x % 2 == 1 and y % 2 == 0: sm += y
if x % 2 == 0 and y % 2 == 1: sm -= x
if x % 2 == 0 and y % 2 == 0: sm += y - x
ans += [sm]
nums[idx] += val
return ans