mirror of
https://github.moeyy.xyz/https://github.com/TheAlgorithms/C.git
synced 2023-10-11 15:56:24 +08:00
077517d6ae
* add Sum of Even Numbers After Queries leetcode task * chore: apply suggestions from code review Co-authored-by: David Leal <halfpacho@gmail.com>
40 lines
1.0 KiB
C
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;
|
|
}
|