985. Sum of Even Numbers After Queries

985. Even sum after query means Get integer array nums and array query. where queries[i] = [vali, indexi]. For each query i, first apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values ​​of nums. Returns an integer array response. response[i] is the response for the ith query. Example 1: Input: number = [1,2,3,4], query = [[1,0], [-3,1], [-4,0], [2,3 ] ]] Output: [8,6,2,4] Description: The first array is [1,2,3,4]. If you add 1 to nums[0] , the array becomes [2,2,3,4] and the sum of the even values ​​is 2 + 2 + 4 = 8. After adding -3 to nums[1] the array is [2,-1,3,4] and the sum of the even numbers is 2 + 4 = 6. Adding -4 to nums[0] gives an array of [-2,- 1, 3, 4]. ], and the sum of the even values ​​is -2 + 4 = 2. is -2 + 6 = 4. Example 2: Input: Number = [1], Query = [[4,0]] Output: [0] Constraint: 1 < = nums .length <= 104 -104 <= nums[i] <= 104 1 <= query.length <= 104 -104 <= valid <= 104 0 <= indexi < nums.length Solution class Solution { public: vector sumEvenAfterQueries(vector& nums, vector>& queries) { int sum = 0, N = queries.size(); for (int n : nums) { if (n % 2 == 0) sum += n; } vector ans(N, 0); // Four cases to handle. for (int i = 0; i < N; i++) { int val = queries[i][0], index = queries[i][1]; int oldValue = nums[index]; nums[index] += val; bool wasEven = (oldValue % 2) == 0; bool nowEven = (nums[index] % 2 == 0); if (wasEven && nowEven) { ans[i] = sum + val; sum += val; } else if (!wasEven && nowEven) { ans[i] = sum + nums[index]; sum += nums[index]; } else if (wasEven && !nowEven) { ans[i] = sum - oldValue; sum -= oldValue; } else { ans[i] = sum; } } return ans; } };

Comments

Popular posts from this blog

1431. Kids With the Greatest Number of Candies

125. Valid Palindrome

771. Jewels and Stones