Sponsored
Sponsored
In this approach, we will maintain a running sum of even numbers. For each query, before updating the number at the given index, we check if it's even and subtract it from our running total if it is. After updating, we check if the new number is even and add it to the total if it is. This method avoids recalculating the sum of all even numbers from scratch after each query, thus optimizing the solution.
Time Complexity: O(n + m), where n is the length of nums and m is the number of queries.
Space Complexity: O(1), as we use only constant extra space.
1from typing import List
2
3def sumEvenAfterQueries(nums: List[int], queries: List[List[int]]) -> List[int]:
4 even_sum = sum(num for num in nums if num % 2 == 0)
5 result = []
6 for val, index in queries:
7 if nums[index] % 2 == 0:
8 even_sum -= nums[index]
9 nums[index] += val
10 if nums[index] % 2 == 0:
11 even_sum += nums[index]
12 result.append(even_sum)
13 return result
We begin by determining the sum of even elements within nums. As each query could alter this sum, we first subtract the value from evenSum if it's initially even, apply the query change, and then add the new value if it's even. Each query is processed in constant time.
This approach calculates the sum of even numbers from scratch after each query. Though straightforward, it may not be the most efficient, as it recalculates the sum fully rather than in an incremental manner.
Time Complexity: O(n * m), as the even sum is recalculated n times for each query m.
Space Complexity: O(1), aside from the storage for results.
1
Each query is independently processed by updating the indicated index and recalculating the entire array's evenSum afterward. While direct, this method lacks the efficiency of the first approach as every query starts with a new sum computation.