Skip to content
Related Articles
Open in App
Not now

Related Articles

Sum of odd Array elements after each update query

Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 02 Jan, 2023
Improve Article
Save Article
Like Article

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++

// C++ code to implement the approach

#include <bits/stdc++.h>
using namespace std;

// Function performing calculations
vector<int> Sumodd(int N, int Arr[], int Q,
                   int Queries[][2])
{
    // Declaring the answer array
    vector<int> ans;
    for (int j = 0; j < Q; j++) {

        // Incrementing the array element
        // for every query
        Arr[Queries[j][1]] += Queries[j][0];

        // Initializing sum variable to
        int sum = 0;
        for (int i = 0; i < N; i++) {

            // If the element is odd then
            // increment the sum
            if (Arr[i] % 2 == 1 || Arr[i] % 2 == -1) {
                sum += Arr[i];
            }
        }

        // Pushing result of every query
        ans.push_back(sum);
    }

    // Return the answer array
    return ans;
}

//  Driver code
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 } };

    // Function call
    vector<int> ans = Sumodd(N, Arr, Q, Queries);
    for (int x : ans)
        cout << x << " ";
    return 0;
}

Java

// Java code to implement the approach
import java.io.*;
import java.util.*;

class GFG 
{

  // Function performing calculations
  public static ArrayList<Integer>
    Sumodd(int N, int Arr[], int Q, int Queries[][])
  {

    // Declaring the answer arraylist
    ArrayList<Integer> ans = new ArrayList<Integer>();
    for (int j = 0; j < Q; j++) {

      // Incrementing the array element
      // for every query
      Arr[Queries[j][1]] += Queries[j][0];

      // Initializing sum variable to
      int sum = 0;
      for (int i = 0; i < N; i++) {

        // If the element is odd then
        // increment the sum
        if (Arr[i] % 2 == 1 || Arr[i] % 2 == -1) {
          sum += Arr[i];
        }
      }

      // Pushing result of every query
      ans.add(sum);
    }

    // Return the answer array
    return ans;
  }

  // Driver Code
  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 } };

    // Function call
    ArrayList<Integer> ans = Sumodd(N, Arr, Q, Queries);
    for (int x : ans)
      System.out.print(x + " ");
  }
}

// This code is contributed by Rohit Pradhan

Python3

# Python program for the above approach

# Function performing calculations
def Sumodd(N, Arr, Q, Queries):
  
    # Declaring the answer arraylist
    ans = []
    for j in range(Q):
      
        # Incrementing the array element for every query
        Arr[Queries[j][1]] += Queries[j][0]

        # Initializing sum variable to 0
        Sum = 0
        for i in range(N):
          
            # If the element is odd then increment the sum
            if(Arr[i] % 2 is 1 or Arr[i] % 2 is -1):
                Sum += Arr[i]

        # Pushing result of every query
        ans.append(Sum)

    # Return the answer array
    return ans

Arr = [1, 2, 3, 5]
N = len(Arr)
Q = 4
Queries = [[1, 0],
           [-3, 1],
           [-4, 0],
           [2, 3]]

# Function call
ans = Sumodd(N, Arr, Q, Queries)
for x in range(len(ans)):
    print(ans[x], end=" ")

# This code is contributed by lokeshmvs21.

C#

// C# implementation
using System;
public class HelloWorld
{

  // Function performing calculations
  static int[] Sumodd(int N, int[] Arr, int Q,
                      int[,] Queries)
  {

    // Declaring the answer array
    int[] ans=new int[Q];
    for (int j = 0; j < Q; j++) {

      // Incrementing the array element
      // for every query
      Arr[Queries[j,1]] += Queries[j,0];

      // Initializing sum variable to
      int sum = 0;
      for (int i = 0; i < N; i++) {

        // If the element is odd then
        // increment the sum
        if (Arr[i] % 2 == 1 || Arr[i] % 2 == -1) {
          sum += Arr[i];
        }
      }
      // Pushing result of every query
      ans[j]=(sum);
    }
    // Return the answer array
    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 } };

    // Function call
    int[] ans = Sumodd(N, Arr, Q, Queries);
    for (int x = 0; x < ans.Length; x++){
      Console.Write(ans[x] + " ");
    }
  }
}

// This code is contributed by ksam24000

Javascript

<script>
// JavaScript program for the above approach

  // Function performing calculations
  function Sumodd(N, Arr, Q, Queries)
  {

    // Declaring the answer arraylist
    let ans = [];
    for (let j = 0; j < Q; j++) {

      // Incrementing the array element
      // for every query
      Arr[Queries[j][1]] += Queries[j][0];

      // Initializing sum variable to
      let sum = 0;
      for (let i = 0; i < N; i++) {

        // If the element is odd then
        // increment the sum
        if (Arr[i] % 2 == 1 || Arr[i] % 2 == -1) {
          sum += Arr[i];
        }
      }

      // Pushing result of every query
      ans.push(sum);
    }

    // Return the answer array
    return ans;
  }


// Driver Code
    let Arr = [ 1, 2, 3, 5 ];
    let N = Arr.length;
    let Q = 4;
    let Queries
      = [[ 1, 0 ], [ -3, 1 ], [ -4, 0 ], [ 2, 3 ]];

    // Function call
    let ans = Sumodd(N, Arr, Q, Queries);
    for (let x in ans)
      document.write(ans[x] + " ");

// This code is contributed by sanjoy_62.
</script>
Output

8 7 7 9 

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++

// C++ code to implement the approach

#include <bits/stdc++.h>
using namespace std;

// Function performing calculations.
vector<int> Sumodd(int N, int Arr[], int Q,
                   int Queries[][2])
{
    // Declaring the answer array
    vector<int> ans;

    // Initializing the sum variable to 0.
    int sum = 0;
    for (int i = 0; i < N; i++) {

        // Loop to precomputing
        // the sum of odd elements
        if (Arr[i] % 2 != 0) {
            sum += Arr[i];
        }
    }

    for (int j = 0; j < Q; j++) {
        int temp = Arr[Queries[j][1]];

        // If the element was odd then
        // decrement it from the sum
        if (temp % 2 != 0) {
            sum -= temp;
        }

        // Update the array element for every query
        Arr[Queries[j][1]] += Queries[j][0];

        temp = Arr[Queries[j][1]];

        // If the updated value of temp is odd
        // then increment the sum
        if (temp % 2 != 0) {
            sum += temp;
        }

        // Push result of every query
        ans.push_back(sum);
    }

    // Return the answer array
    return ans;
}

//  Driver code
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 } };

    // Function call
    vector<int> ans = Sumodd(N, Arr, Q, Queries);
    for (int x : ans)
        cout << x << " ";
    return 0;
}

Java

// Java code to implement the approach
import java.io.*;
import java.util.*;

class GFG {

  // Function performing calculations
  static List<Integer> Sumodd(int N, int[] Arr, int Q,
                              int[][] Queries)
  {
    // Declaring the answer array
    List<Integer> ans = new ArrayList<>();

    // Initializing the sum variable to 0.
    int sum = 0;
    for (int i = 0; i < N; i++) {

      // Loop to precomputing
      // the sum of odd elements
      if (Arr[i] % 2 != 0) {
        sum += Arr[i];
      }
    }

    for (int j = 0; j < Q; j++) {
      int temp = Arr[Queries[j][1]];

      // If the element was odd then
      // decrement it from the sum
      if (temp % 2 != 0) {
        sum -= temp;
      }

      // Update the array element for every query
      Arr[Queries[j][1]] += Queries[j][0];

      temp = Arr[Queries[j][1]];

      // If the updated value of temp is odd
      // then increment the sum
      if (temp % 2 != 0) {
        sum += temp;
      }

      // Push result of every query
      ans.add(sum);
    }

    // Return the answer array
    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 } };

    // Function call
    List<Integer> ans = Sumodd(N, Arr, Q, Queries);
    for (int i = 0; i < ans.size(); i++) {
      System.out.print(ans.get(i) + " ");
    }
  }
}

// This code is contributed by lokeshmvs21.

Python3

# Python code to implement the approach

# Function performing calculations
def Sumodd(N, Arr, Q, Queries):
    # Declaring the answer array
    ans = []

    # Initializing the sum variable to 0.
    Sum = 0

    for i in range(N):
        # Loop to precomputing
        # the sum of odd elements
        if(Arr[i] % 2 != 0):
            Sum += Arr[i]

    for j in range(Q):
        temp = Arr[Queries[j][1]]
        # If the element was odd then
        # decrement it from the sum
        if(temp % 2 != 0):
            Sum -= temp

        # Update the array element for every query
        Arr[Queries[j][1]] += Queries[j][0]
        temp = Arr[Queries[j][1]]

        # If the updated value of temp is odd
        # then increment the sum
        if(temp % 2 != 0):
            Sum += temp

        # Append result of every query
        ans.append(Sum)

    # Return the answer array
    return ans

Arr = [1, 2, 3, 5]
N = len(Arr)
Q = 4
Queries = [[1, 0], [-3, 1], [-4, 0], [2, 3]]

# Function call
ans = Sumodd(N, Arr, Q, Queries)
for i in range(len(ans)):
    print(ans[i], end=" ")

# This code is contributed by lokeshmvs21.

C#

// C# code to implement the approach
using System;
using System.Collections;
using System.Collections.Generic;

public class GFG {

  // Function performing calculations
  static ArrayList Sumodd(int N, int[] Arr, int Q,
                          int[, ] Queries)
  {
    // Declaring the answer array
    ArrayList ans = new ArrayList();

    // Initializing the sum variable to 0.
    int sum = 0;
    for (int i = 0; i < N; i++) {

      // Loop to precomputing
      // the sum of odd elements
      if (Arr[i] % 2 != 0) {
        sum += Arr[i];
      }
    }

    for (int j = 0; j < Q; j++) {
      int temp = Arr[Queries[j, 1]];

      // If the element was odd then
      // decrement it from the sum
      if (temp % 2 != 0) {
        sum -= temp;
      }

      // Update the array element for every query
      Arr[Queries[j, 1]] += Queries[j, 0];

      temp = Arr[Queries[j, 1]];

      // If the updated value of temp is odd
      // then increment the sum
      if (temp % 2 != 0) {
        sum += temp;
      }

      // Push result of every query
      ans.Add(sum);
    }

    // Return the answer array
    return ans;
  }

  static public void Main()
  {

    // Code
    int[] Arr = { 1, 2, 3, 5 };
    int N = Arr.Length;
    int Q = 4;
    int[, ] Queries
      = { { 1, 0 }, { -3, 1 }, { -4, 0 }, { 2, 3 } };

    // Function call
    ArrayList ans = Sumodd(N, Arr, Q, Queries);
    for (int i = 0; i < ans.Count; i++) {
      Console.Write(ans[i] + " ");
    }
  }
}

// This code is contributed by lokesh.

Javascript

// JS code to implement the approach

// Function performing calculations.
function Sumodd(N,  Arr, Q, Queries)
{
    // Declaring the answer array
    let ans = []

    // Initializing the sum variable to 0.
    let sum = 0;
    for (let i = 0; i < N; i++) {

        // Loop to precomputing
        // the sum of odd elements
        if (Arr[i] % 2 != 0) {
            sum += Arr[i];
        }
    }

    for (let j = 0; j < Q; j++) {
        let temp = Arr[Queries[j][1]];

        // If the element was odd then
        // decrement it from the sum
        if (temp % 2 != 0) {
            sum -= temp;
        }

        // Update the array element for every query
        Arr[Queries[j][1]] += Queries[j][0];

        temp = Arr[Queries[j][1]];

        // If the updated value of temp is odd
        // then increment the sum
        if (temp % 2 != 0) {
            sum += temp;
        }

        // Push result of every query
        ans.push(sum);
    }

    // Return the answer array
    return ans;
}

//  Driver code
let Arr = [ 1, 2, 3, 5 ];
let N = Arr.length;
let Q = 4;
let Queries = [ [ 1, 0 ], [ -3, 1 ], [ -4, 0 ], [ 2, 3 ] ];

// Function call
let ans = Sumodd(N, Arr, Q, Queries);
console.log(ans);

// This code is contributed by akashish__
Output

8 7 7 9 

Time Complexity: O(max(Q, N)).
Auxiliary Space: O(Q) i.e answer array of Q size.


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!