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.
1class Solution {
2 public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {
3 int evenSum = 0;
4 for (int num : 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}
Initially, we calculate the sum of even numbers in the array. As each query modifies an element value, it potentially changes the evenSum. We handle this by first removing the value from evenSum if it's even, applying the query, and then adding the new value if it is even.
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.