feat: add Sum of Even Numbers LeetCode problem (#1145)

* add Sum of Even Numbers After Queries leetcode task

* chore: apply suggestions from code review

Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Alexander Pantyukhin 2022-11-25 22:35:54 +04:00 committed by GitHub
parent 99f06e97e7
commit 077517d6ae
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 0 deletions

View File

@ -92,6 +92,7 @@
| 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) | [C](./src/938.c) | Easy |
| 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree/) | [C](./src/965.c) | Easy |
| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [C](./src/977.c) | Easy |
| 985 | [Sum of Even Numbers After Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries/) | [C](./src/985.c) | Medium |
| 1009 | [Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer/) | [C](./src/1009.c) | Easy |
| 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [C](./src/1089.c) | Easy |
| 1184 | [Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops/) | [C](./src/1184.c) | Easy |

39
leetcode/src/985.c Normal file
View File

@ -0,0 +1,39 @@
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
// collecting sum Runtime: O(len(queries)), Space: O(1)
int* sumEvenAfterQueries(int* nums, int numsSize, int** queries, int queriesSize, int* queriesColSize, int* returnSize){
int summ = 0;
int* result = malloc(queriesSize * sizeof(int));
*returnSize = queriesSize;
for(int i = 0; i < numsSize; i++){
if (nums[i] % 2 == 0) {
summ += nums[i];
}
}
for(int i = 0; i < queriesSize; i++){
int* query = queries[i];
int val = query[0];
int index = query[1];
// sub index value from summ if it's even
if (nums[index] % 2 == 0) {
summ -= nums[index];
}
// modify the nums[index] value
nums[index] += val;
// add index value from summ if it's even
if (nums[index] % 2 == 0) {
summ += nums[index];
}
result[i] = summ;
}
return result;
}