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.
1public class Solution {
2 public int[] SumEvenAfterQueries(int[] nums, int[][] queries) {
3 int evenSum = 0;
4 foreach (int num in nums) {
5 if (num % 2 == 0) evenSum += num;
6 }
7 int[] result = new int[queries.Length];
8 for (int i = 0; i < queries.Length; i++) {
9 int val = queries[i][0], index = queries[i][1];
10 if (nums[index] % 2 == 0) evenSum -= nums[index];
11 nums[index] += val;
12 if (nums[index] % 2 == 0) evenSum += nums[index];
13 result[i] = evenSum;
14 }
15 return result;
16 }
17}
The initial sum of even numbers is calculated first. For each query operation, we potentially modify this even sum by first removing the indexed value if it is even, applying the query modification, and then potentially adding the new value if it results in an even number.
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.