TheAlgorithms-C/leetcode/src/985.c
Alexander Pantyukhin 077517d6ae
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>
2022-11-25 12:35:54 -06:00

40 lines
1.0 KiB
C

/**
* 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;
}