Sum of odd Array elements after each update query
Last Updated :
22 Aug, 2023
Given an integer array Arr[] of length N and an array Queries[] of length Q where Queries[i] = [valuei, indexi]. For each query i, update Arr[indexi] = Arr[indexi] + valuei, then print the sum of the all the odd values of Arr[].
Examples:
Input: N = 4, Arr = [1,2,3,5], Q = 4, Queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: 8 7 7 9
Explanation: At the beginning, the array is [1,2,3,5].
After adding 1 to Arr[0], the array is [2,2,3,5], and the sum of odd values is 3 + 5 = 8.
After adding -3 to Arr[1], the array is [2,-1,3,5], and the sum of odd values is -1 + 3 + 5 = 7.
After adding -4 to Arr[0], the array is [-2,-1,3,5], and the sum of odd values is -1 + 3 + 5 = 7.
After adding 2 to Arr[3], the array is [-2,-1,3,7], and the sum of odd values is -1 + 3 + 7 = 9.
Input: N = 1 , Arr = [1], Q = 1,Queries = [[4,0]]
Output: [5]
Explanation: At the beginning, the array is [1].
After adding 4 to Arr[0], the array is [5], and the sum of odd values is 0.
Naive Approach: The problem can be solved by implementing the operations as mentioned.
For each query first update the value and then iterate through the array to find the sum of odd integers.
Follow the steps mentioned below to implement the idea:
- Declare the answer array.
- Run a loop form j = 0 to Q-1:
- Increment arr[idx] (where idx is the index mentioned in the query) by the given value in the query.
- Initialize the sum to 0.
- Run a nested loop from i = 0 to N-1:
- If the element is odd, then add that value to the sum.
- Add the sum to the answer array.
- Print the answer array.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > Sumodd( int N, int Arr[], int Q,
int Queries[][2])
{
vector< int > ans;
for ( int j = 0; j < Q; j++) {
Arr[Queries[j][1]] += Queries[j][0];
int sum = 0;
for ( int i = 0; i < N; i++) {
if (Arr[i] % 2 == 1 || Arr[i] % 2 == -1) {
sum += Arr[i];
}
}
ans.push_back(sum);
}
return ans;
}
int main()
{
int Arr[] = { 1, 2, 3, 5 };
int N = sizeof (Arr) / sizeof (Arr[0]);
int Q = 4;
int Queries[Q][2]
= { { 1, 0 }, { -3, 1 }, { -4, 0 }, { 2, 3 } };
vector< int > ans = Sumodd(N, Arr, Q, Queries);
for ( int x : ans)
cout << x << " " ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
public static ArrayList<Integer>
Sumodd( int N, int Arr[], int Q, int Queries[][])
{
ArrayList<Integer> ans = new ArrayList<Integer>();
for ( int j = 0 ; j < Q; j++) {
Arr[Queries[j][ 1 ]] += Queries[j][ 0 ];
int sum = 0 ;
for ( int i = 0 ; i < N; i++) {
if (Arr[i] % 2 == 1 || Arr[i] % 2 == - 1 ) {
sum += Arr[i];
}
}
ans.add(sum);
}
return ans;
}
public static void main(String[] args)
{
int Arr[] = { 1 , 2 , 3 , 5 };
int N = Arr.length;
int Q = 4 ;
int Queries[][]
= { { 1 , 0 }, { - 3 , 1 }, { - 4 , 0 }, { 2 , 3 } };
ArrayList<Integer> ans = Sumodd(N, Arr, Q, Queries);
for ( int x : ans)
System.out.print(x + " " );
}
}
|
Python3
def Sumodd(N, Arr, Q, Queries):
ans = []
for j in range (Q):
Arr[Queries[j][ 1 ]] + = Queries[j][ 0 ]
Sum = 0
for i in range (N):
if (Arr[i] % 2 is 1 or Arr[i] % 2 is - 1 ):
Sum + = Arr[i]
ans.append( Sum )
return ans
Arr = [ 1 , 2 , 3 , 5 ]
N = len (Arr)
Q = 4
Queries = [[ 1 , 0 ],
[ - 3 , 1 ],
[ - 4 , 0 ],
[ 2 , 3 ]]
ans = Sumodd(N, Arr, Q, Queries)
for x in range ( len (ans)):
print (ans[x], end = " " )
|
C#
using System;
public class HelloWorld
{
static int [] Sumodd( int N, int [] Arr, int Q,
int [,] Queries)
{
int [] ans= new int [Q];
for ( int j = 0; j < Q; j++) {
Arr[Queries[j,1]] += Queries[j,0];
int sum = 0;
for ( int i = 0; i < N; i++) {
if (Arr[i] % 2 == 1 || Arr[i] % 2 == -1) {
sum += Arr[i];
}
}
ans[j]=(sum);
}
return ans;
}
public static void Main( string [] args)
{
int [] Arr = { 1, 2, 3, 5 };
int N = Arr.Length;
int Q = 4;
int [,] Queries = new int [4,2]{ { 1, 0 }, { -3, 1 }, { -4, 0 }, { 2, 3 } };
int [] ans = Sumodd(N, Arr, Q, Queries);
for ( int x = 0; x < ans.Length; x++){
Console.Write(ans[x] + " " );
}
}
}
|
Javascript
<script>
function Sumodd(N, Arr, Q, Queries)
{
let ans = [];
for (let j = 0; j < Q; j++) {
Arr[Queries[j][1]] += Queries[j][0];
let sum = 0;
for (let i = 0; i < N; i++) {
if (Arr[i] % 2 == 1 || Arr[i] % 2 == -1) {
sum += Arr[i];
}
}
ans.push(sum);
}
return ans;
}
let Arr = [ 1, 2, 3, 5 ];
let N = Arr.length;
let Q = 4;
let Queries
= [[ 1, 0 ], [ -3, 1 ], [ -4, 0 ], [ 2, 3 ]];
let ans = Sumodd(N, Arr, Q, Queries);
for (let x in ans)
document.write(ans[x] + " " );
</script>
|
Time Complexity: O(Q*N).
Auxiliary Space: O(Q) i.e answer array of Q size.
Efficient Approach using Precomputation:
The problem can be solved using precomputation based on the following observation:
Say the sum of odd elements was S before performing an update query. So, for update query, there can be four cases:
- Element changes from odd to odd: In this case the sum increases by value (where value is the amount needed to be updated as per the query). This can be interpreted as subtracting the previous value from S and then adding the new updated value.
- Element changes from even to odd: In this case the increase in sum is the same as the new odd value.
- Element changes from odd to even: In this case the sum decreases by an amount same as the previous value of the element.
- Element changes from even to even: In this case there is no change in sum.
So we can see that whenever the element was odd before update, initially there is a decrement in the sum and if the new updated value is odd, there is an increment of that amount in S.
Follow the steps mentioned below to implement the idea:
- Declare the answer array.
- Iterate throughout the array and calculate the sum of the odd values.
- Run a loop from j = 0 to Q-1:
- Store the previous value of Arr[indexj] in temp variable.
- If the temp value is odd then decrement the sum by temp.
- Incrementing the value Arr[indexj] by valuej and update temp.
- If the temp value is odd then increment the sum by temp.
- Push the sum into the answer array.
- Print the answer array.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > Sumodd( int N, int Arr[], int Q,
int Queries[][2])
{
vector< int > ans;
int sum = 0;
for ( int i = 0; i < N; i++) {
if (Arr[i] % 2 != 0) {
sum += Arr[i];
}
}
for ( int j = 0; j < Q; j++) {
int temp = Arr[Queries[j][1]];
if (temp % 2 != 0) {
sum -= temp;
}
Arr[Queries[j][1]] += Queries[j][0];
temp = Arr[Queries[j][1]];
if (temp % 2 != 0) {
sum += temp;
}
ans.push_back(sum);
}
return ans;
}
int main()
{
int Arr[] = { 1, 2, 3, 5 };
int N = sizeof (Arr) / sizeof (Arr[0]);
int Q = 4;
int Queries[Q][2]
= { { 1, 0 }, { -3, 1 }, { -4, 0 }, { 2, 3 } };
vector< int > ans = Sumodd(N, Arr, Q, Queries);
for ( int x : ans)
cout << x << " " ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static List<Integer> Sumodd( int N, int [] Arr, int Q,
int [][] Queries)
{
List<Integer> ans = new ArrayList<>();
int sum = 0 ;
for ( int i = 0 ; i < N; i++) {
if (Arr[i] % 2 != 0 ) {
sum += Arr[i];
}
}
for ( int j = 0 ; j < Q; j++) {
int temp = Arr[Queries[j][ 1 ]];
if (temp % 2 != 0 ) {
sum -= temp;
}
Arr[Queries[j][ 1 ]] += Queries[j][ 0 ];
temp = Arr[Queries[j][ 1 ]];
if (temp % 2 != 0 ) {
sum += temp;
}
ans.add(sum);
}
return ans;
}
public static void main(String[] args)
{
int [] Arr = { 1 , 2 , 3 , 5 };
int N = Arr.length;
int Q = 4 ;
int [][] Queries
= { { 1 , 0 }, { - 3 , 1 }, { - 4 , 0 }, { 2 , 3 } };
List<Integer> ans = Sumodd(N, Arr, Q, Queries);
for ( int i = 0 ; i < ans.size(); i++) {
System.out.print(ans.get(i) + " " );
}
}
}
|
Python3
def Sumodd(N, Arr, Q, Queries):
ans = []
Sum = 0
for i in range (N):
if (Arr[i] % 2 ! = 0 ):
Sum + = Arr[i]
for j in range (Q):
temp = Arr[Queries[j][ 1 ]]
if (temp % 2 ! = 0 ):
Sum - = temp
Arr[Queries[j][ 1 ]] + = Queries[j][ 0 ]
temp = Arr[Queries[j][ 1 ]]
if (temp % 2 ! = 0 ):
Sum + = temp
ans.append( Sum )
return ans
Arr = [ 1 , 2 , 3 , 5 ]
N = len (Arr)
Q = 4
Queries = [[ 1 , 0 ], [ - 3 , 1 ], [ - 4 , 0 ], [ 2 , 3 ]]
ans = Sumodd(N, Arr, Q, Queries)
for i in range ( len (ans)):
print (ans[i], end = " " )
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG {
static ArrayList Sumodd( int N, int [] Arr, int Q,
int [, ] Queries)
{
ArrayList ans = new ArrayList();
int sum = 0;
for ( int i = 0; i < N; i++) {
if (Arr[i] % 2 != 0) {
sum += Arr[i];
}
}
for ( int j = 0; j < Q; j++) {
int temp = Arr[Queries[j, 1]];
if (temp % 2 != 0) {
sum -= temp;
}
Arr[Queries[j, 1]] += Queries[j, 0];
temp = Arr[Queries[j, 1]];
if (temp % 2 != 0) {
sum += temp;
}
ans.Add(sum);
}
return ans;
}
static public void Main()
{
int [] Arr = { 1, 2, 3, 5 };
int N = Arr.Length;
int Q = 4;
int [, ] Queries
= { { 1, 0 }, { -3, 1 }, { -4, 0 }, { 2, 3 } };
ArrayList ans = Sumodd(N, Arr, Q, Queries);
for ( int i = 0; i < ans.Count; i++) {
Console.Write(ans[i] + " " );
}
}
}
|
Javascript
function Sumodd(N, Arr, Q, Queries)
{
let ans = []
let sum = 0;
for (let i = 0; i < N; i++) {
if (Arr[i] % 2 != 0) {
sum += Arr[i];
}
}
for (let j = 0; j < Q; j++) {
let temp = Arr[Queries[j][1]];
if (temp % 2 != 0) {
sum -= temp;
}
Arr[Queries[j][1]] += Queries[j][0];
temp = Arr[Queries[j][1]];
if (temp % 2 != 0) {
sum += temp;
}
ans.push(sum);
}
return ans;
}
let Arr = [ 1, 2, 3, 5 ];
let N = Arr.length;
let Q = 4;
let Queries = [ [ 1, 0 ], [ -3, 1 ], [ -4, 0 ], [ 2, 3 ] ];
let ans = Sumodd(N, Arr, Q, Queries);
console.log(ans);
|
Time Complexity: O(max(Q, N)).
Auxiliary Space: O(Q) i.e answer array of Q size.
Another Approach:
- Start by including the necessary header files and defining the namespace as std.
- Define the function Sumodd() that takes four arguments – the size of the array N, the array itself Arr[], the number of queries Q, and the array of queries Queries[][2].
- Initialize an empty vector ans to store the results.
- Declare an integer array bit[] of size N+1 and initialize all its elements to zero.
- Initialize an integer variable sum to zero.
- Iterate over the elements of Arr[] using a for loop and check if each element is odd. If an element is odd, add it to the sum variable and update the corresponding index in bit[] by adding the element to it.
- For each query in Queries[][], extract the index and value from the query.
- Check if the element at the given index in Arr[] is odd. If it is odd, subtract it from both the sum variable and the corresponding index in bit[].
- Update the element at the given index in Arr[] by adding the given value.
- Check if the new value at the given index in Arr[] is odd. If it is odd, add it to both the sum variable and the corresponding index in bit[].
- Push the current value of sum to the ans vector.
- Return the ans vector.
- In the main() function, initialize the input arrays Arr[] and Queries[][].
- Call the Sumodd() function with the input arrays and store the result in a vector ans.
- Print the elements of the ans vector.
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > Sumodd( int N, int Arr[], int Q,
int Queries[][2])
{
vector< int > ans;
int bit[N + 1];
memset (bit, 0, sizeof (bit));
int sum = 0;
for ( int i = 0; i < N; i++) {
if (Arr[i] % 2 != 0) {
sum += Arr[i];
bit[i + 1] += Arr[i];
}
}
for ( int i = 0; i < Q; i++) {
int index = Queries[i][1];
int val = Queries[i][0];
if (Arr[index] % 2 != 0) {
bit[index + 1] -= Arr[index];
sum -= Arr[index];
}
Arr[index] += val;
if (Arr[index] % 2 != 0) {
bit[index + 1] += Arr[index];
sum += Arr[index];
}
ans.push_back(sum);
}
return ans;
}
int main()
{
int Arr[] = { 1, 2, 3, 5 };
int N = sizeof (Arr) / sizeof (Arr[0]);
int Q = 4;
int Queries[Q][2]
= { { 1, 0 }, { -3, 1 }, { -4, 0 }, { 2, 3 } };
vector< int > ans = Sumodd(N, Arr, Q, Queries);
for ( int x : ans)
cout << x << " " ;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
int [] arr = { 1 , 2 , 3 , 5 };
int n = arr.length;
int q = 4 ;
int [][] queries
= { { 1 , 0 }, { - 3 , 1 }, { - 4 , 0 }, { 2 , 3 } };
List<Integer> ans = sumOdd(n, arr, q, queries);
for ( int x : ans)
System.out.print(x + " " );
}
public static List<Integer>
sumOdd( int n, int [] arr, int q, int [][] queries)
{
List<Integer> ans = new ArrayList<>();
int [] bit = new int [n + 1 ];
int sum = 0 ;
for ( int i = 0 ; i < n; i++) {
if (arr[i] % 2 != 0 ) {
sum += arr[i];
bit[i + 1 ] += arr[i];
}
}
for ( int i = 0 ; i < q; i++) {
int index = queries[i][ 1 ];
int val = queries[i][ 0 ];
if (arr[index] % 2 != 0 ) {
bit[index + 1 ] -= arr[index];
sum -= arr[index];
}
arr[index] += val;
if (arr[index] % 2 != 0 ) {
bit[index + 1 ] += arr[index];
sum += arr[index];
}
ans.add(sum);
}
return ans;
}
}
|
Python3
def Sumodd(N, Arr, Q, Queries):
ans = []
bit = [ 0 ] * (N + 1 )
sum_ = 0
for i in range (N):
if Arr[i] % 2 ! = 0 :
sum_ + = Arr[i]
bit[i + 1 ] + = Arr[i]
for i in range (Q):
index = Queries[i][ 1 ]
val = Queries[i][ 0 ]
if Arr[index] % 2 ! = 0 :
bit[index + 1 ] - = Arr[index]
sum_ - = Arr[index]
Arr[index] + = val
if Arr[index] % 2 ! = 0 :
bit[index + 1 ] + = Arr[index]
sum_ + = Arr[index]
ans.append(sum_)
return ans
Arr = [ 1 , 2 , 3 , 5 ]
N = len (Arr)
Q = 4
Queries = [( 1 , 0 ), ( - 3 , 1 ), ( - 4 , 0 ), ( 2 , 3 )]
ans = Sumodd(N, Arr, Q, Queries)
print ( * ans)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static List< int > Sumodd( int N, int [] Arr, int Q, int [,] Queries)
{
List< int > ans = new List< int >();
int [] bit = new int [N + 1];
Array.Clear(bit, 0, bit.Length);
int sum = 0;
for ( int i = 0; i < N; i++)
{
if (Arr[i] % 2 != 0)
{
sum += Arr[i];
bit[i + 1] += Arr[i];
}
}
for ( int i = 0; i < Q; i++)
{
int index = Queries[i, 1];
int val = Queries[i, 0];
if (Arr[index] % 2 != 0)
{
bit[index + 1] -= Arr[index];
sum -= Arr[index];
}
Arr[index] += val;
if (Arr[index] % 2 != 0)
{
bit[index + 1] += Arr[index];
sum += Arr[index];
}
ans.Add(sum);
}
return ans;
}
static void Main()
{
int [] Arr = { 1, 2, 3, 5 };
int N = Arr.Length;
int Q = 4;
int [,] Queries = { { 1, 0 }, { -3, 1 }, { -4, 0 }, { 2, 3 } };
List< int > ans = Sumodd(N, Arr, Q, Queries);
foreach ( int x in ans)
Console.Write(x + " " );
}
}
|
Javascript
function Sumodd(N, Arr, Q, Queries) {
const ans = [];
const bit = new Array(N + 1).fill(0);
let sum = 0;
for (let i = 0; i < N; i++) {
if (Arr[i] % 2 !== 0) {
sum += Arr[i];
bit[i + 1] += Arr[i];
}
}
for (let i = 0; i < Q; i++) {
const index = Queries[i][1];
const val = Queries[i][0];
if (Arr[index] % 2 !== 0) {
bit[index + 1] -= Arr[index];
sum -= Arr[index];
}
Arr[index] += val;
if (Arr[index] % 2 !== 0) {
bit[index + 1] += Arr[index];
sum += Arr[index];
}
ans.push(sum);
}
return ans;
}
const Arr = [1, 2, 3, 5];
const N = Arr.length;
const Q = 4;
const Queries = [
[1, 0],
[-3, 1],
[-4, 0],
[2, 3]
];
const ans = Sumodd(N, Arr, Q, Queries);
for (let x of ans) {
process.stdout.write(x + " " );
}
|
Time Complexity:O(Q log N)
Auxiliary Space: O(N)
Similar Reads
Sum of array elements after reversing each element
Given an array arr[] consisting of N positive integers, the task is to find the sum of all array elements after reversing digits of every array element. Examples: Input: arr[] = {7, 234, 58100}Output: 18939Explanation:Modified array after reversing each array elements = {7, 432, 18500}.Therefore, th
7 min read
Sum and Maximum of elements in array from [L, R] before and after updates
Prerequisite: Segment Trees, Lazy Propagation in Segment Tree. Given an array arr[] of N integers. The task is to do the following operations: Change the value arr[i] to min(arr[i], X) where X is an integer for a given range [L, R].Find the maximum value from index L to R where 0 ? L ? R ? N-1 befor
11 min read
Find the sum of array after performing every query
Given an array arr[] of size N and Q queries where every query contains two integers X and Y, the task is to find the sum of an array after performing each Q queries such that for every query, the element in the array arr[] with value X is updated to Y. Find the sum of the array after every query. E
7 min read
Sum of even values and update queries on an array
Given an array arr[] of integers and an array q[] of queries. For the ith query, index = q[i][0] and value = q[i][1]. The task is for every query, update arr[index] = arr[index] + value and then return the sum of all the even elements from the array. Examples: Input: arr[] = {1, 2, 3, 4}, q[] = {{0,
13 min read
Sum of array elements whose count of set bits are unique
Given an array arr[] consisting of N positive integers, the task is to find the sum of all array elements having a distinct count of set bits in the array. Examples: Input: arr[] = {8, 3, 7, 5, 3}Output: 15Explanation:The count of set bits in each array of elements is: arr[0] = 8 = (1000)2, has 1 se
7 min read
Find sum of all unique elements in the array for K queries
Given an arrays arr[] in which initially all elements are 0 and another array Q[][] containing K queries where every query represents a range [L, R], the task is to add 1 to each subarrays where each subarray is defined by the range [L, R], and return sum of all unique elements.Note: One-based index
8 min read
Sum of even elements of an Array using Recursion
Given an array arr[] of integers, the task is to find the sum of even elements from the array. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8} Output: 20 2 + 4 + 6 + 8 = 20Input: arr[] = {4, 1, 3, 6} Output: 10 4 + 6 = 10 Approach: Write a recursive function that takes the array as an argument wit
5 min read
Pair of arrays with equal sum after removing exactly one element from each
Given K arrays of different size. The task is to check if there exist any two arrays which have the same sum of elements after removing exactly one element from each of them. (Any element can be removed, but exactly one has to be removed). Print the indices of the array and the index of the removed
10 min read
Sum of product of each element with each element after it
Given an array arr[] of n integers. The task is to find the sum of product of each element with each element after it in the array. In other words, find sum of product of each arr[i] with each arr[j] such that j > i. Examples : Input : arr[] = {9, 3, 4, 2}Output : 107Explanation: Sum of product o
10 min read
Check if sum of exactly K elements of the Array can be odd or not
Given an array, arr[] and an integer K. Check whether it is possible to get an odd sum by choosing exactly K elements of the array. Examples: Input: arr[] = {1, 2, 3}, K = 2 Output: Possible Explanation: {2, 3} â¾ 2 + 3 = 5 Input: arr[] = {2, 2, 4, 2}, K = 4 Output: Not Possible Explanation: {2, 2, 4
10 min read