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.
1var sumEvenAfterQueries = function(nums, queries) {
2 let evenSum = nums.reduce((sum, num) => num % 2 === 0 ? sum + num : sum, 0);
3 let result = [];
4 for (let [val, index] of queries) {
5 if (nums[index] % 2 === 0) evenSum -= nums[index];
6 nums[index] += val;
7 if (nums[index] % 2 === 0) evenSum += nums[index];
8 result.push(evenSum);
9 }
10 return result;
11};
First, the evenSum captures the total of even elements. Each query demands the modification of one array element and can shift the evenSum as well. By removing initially even values and re-evaluating after updates, we manage the evenSum effectively for each query.
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
For each query, the change applied to nums calls for a full recomputation of the evenSum, iterating through each element of nums. While less optimal when compared to maintaining a running sum, it is straightforward.