links: Algorithms MOC


Problem

You are given an integer array nums and an array queries 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.

Return an integer array answer where answer[i] is the answer to the ith query.

Approach

Loop through each query and update the input array. Once input array is updated, calculate the sum of even numbers using reduce method.

Solution

/**
 * @param {number[]} nums
 * @param {number[][]} queries
 * @return {number[]}
 */
 var sumEvenAfterQueries = function(nums, queries) {
  let result = []
  for(let i = 0; i < queries.length; i++) {
    const [value, index] = queries[i]
    nums[index] = nums[index] + value
    const sum = nums.reduce((acc, curVal) => curVal % 2 === 0 ? acc + curVal : acc, 0)
    result.push(sum)
  }
  return result
};

tags: array , simulation

sources: