LeetCode 985: Sum of Even Numbers After Queries Solution
Master LeetCode problem 985 (Sum of Even Numbers After Queries), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
985. Sum of Even Numbers After Queries
Problem Explanation
Explanation
To solve this problem, we will iterate over the queries array and for each query, we will update the value at the specified index in the nums array by adding the given value. After each update, we will calculate the sum of even numbers in the nums array and store it in the answer array.
We can optimize the calculation of the sum of even numbers by keeping track of the previous sum and updating it based on the change in the array due to the query.
Time Complexity: O(n) where n is the length of the nums array.
Space Complexity: O(1)
Solution Code
class Solution {
public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {
int sum = 0;
for (int num : nums) {
if (num % 2 == 0) {
sum += num;
}
}
int[] answer = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
int val = queries[i][0];
int index = queries[i][1];
if (nums[index] % 2 == 0) {
sum -= nums[index];
}
nums[index] += val;
if (nums[index] % 2 == 0) {
sum += nums[index];
}
answer[i] = sum;
}
return answer;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 985 (Sum of Even Numbers After Queries)?
This page provides optimized solutions for LeetCode problem 985 (Sum of Even Numbers After Queries) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 985 (Sum of Even Numbers After Queries)?
The time complexity for LeetCode 985 (Sum of Even Numbers After Queries) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 985 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 985 in Java, C++, or Python.