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.
1using namespace std;
vector<int> recomputeEvenSumAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {
vector<int> result;
for (const auto& query : queries) {
nums[query[1]] += query[0];
int evenSum = 0;
for (int num : nums) {
if (num % 2 == 0) evenSum += num;
}
result.push_back(evenSum);
}
return result;
}
Each query modifies the specified index, and then we recompute the evenSum by iterating over the entire nums array. This method is simpler to follow but not as efficient as maintaining a running evenSum as in the incremental approach.