Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Difference between sum of K maximum even and odd array elements
Next article icon

Absolute difference between sum of even elements at even indices & odd elements at odd indices in given Array

Last Updated : 13 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] containing N elements, the task is to find the absolute difference between the sum of even elements at even indices & the count of odd elements at odd indices. Consider 1-based indexing

Examples:

Input: arr[] = {3, 4, 1, 5}
Output: 0
Explanation: Sum of even elements at even indices: 4 {4}
Sum of odd elements at odd indices: 4 {3, 1}
Absolute Difference = 4-4 = 0

Input: arr[] = {4, 2, 1, 3}
Output: 1

 


Approach: The task can be solved by traversing the array from left to right, keeping track of sum of odd and even elements at odd & even indices respectively. Follow the steps below to solve the problem:

  • Traverse the array from left to right.
  • If the current index is even, check whether the element at that index is even or not, If it's even, add it to the sum evens.
  • If the current index is odd, check whether the element at that index is odd or not, If it's odd, add it to the sum odds.
  • Return the absolute difference between odds and evens.

Below is the implementation of the above approach.

C++
// C++ program to implement the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the required absolute difference int xorOr(int arr[], int N) {     // Store the count of odds & evens at odd     // and even indices respectively     int evens = 0, odds = 0;      // Traverse the array to count even/odd     for (int i = 0; i < N; i++) {         if ((i + 1) % 2 == 0             && arr[i] % 2 == 0)             evens += arr[i];         else if ((i + 1) % 2 != 0                  && arr[i] % 2 != 0)             odds += arr[i];     }      return abs(odds - evens); }  // Driver Code int main() {     int arr[] = { 3, 4, 1, 5 };     int N = sizeof(arr) / sizeof(arr[0]);     cout << xorOr(arr, N);     return 0; } 
Java
// Java code for the above approach import java.util.*; class GFG  {    // Function to find the required absolute difference static int xorOr(int arr[], int N) {     // Store the count of odds & evens at odd     // and even indices respectively     int evens = 0, odds = 0;      // Traverse the array to count even/odd     for (int i = 0; i < N; i++) {         if ((i + 1) % 2 == 0             && arr[i] % 2 == 0)             evens += arr[i];         else if ((i + 1) % 2 != 0                  && arr[i] % 2 != 0)             odds += arr[i];     }      return Math.abs(odds - evens); }  // Driver Code     public static void main (String[] args) {        int arr[] = { 3, 4, 1, 5 };     int N = arr.length;               System.out.println(xorOr(arr, N));     } }  // This code is contributed by Potta Lokesh 
Python3
# Python code for the above approach  # Function to find the required absolute difference def xorOr(arr, N):        # Store the count of odds & evens at odd     # and even indices respectively     evens = 0;     odds = 0;      # Traverse the array to count even/odd     for i in range(N):         if ((i + 1) % 2 == 0 and arr[i] % 2 == 0):             evens += arr[i];         elif ((i + 1) % 2 != 0 and arr[i] % 2 != 0):             odds += arr[i];      return abs(odds - evens);  # Driver Code if __name__ == '__main__':     arr = [3, 4, 1, 5];     N = len(arr);      print(xorOr(arr, N));  # This code is contributed by 29AjayKumar  
C#
// C# code for the above approach using System; using System.Collections; class GFG  {    // Function to find the required absolute difference static int xorOr(int []arr, int N) {        // Store the count of odds & evens at odd     // and even indices respectively     int evens = 0, odds = 0;      // Traverse the array to count even/odd     for (int i = 0; i < N; i++) {         if ((i + 1) % 2 == 0             && arr[i] % 2 == 0)             evens += arr[i];         else if ((i + 1) % 2 != 0                  && arr[i] % 2 != 0)             odds += arr[i];     }      return Math.Abs(odds - evens); }  // Driver Code public static void Main () {     int []arr = { 3, 4, 1, 5 };     int N = arr.Length;               Console.Write(xorOr(arr, N)); } }  // This code is contributed by Samim Hossain Mondal. 
JavaScript
<script> // Javascript program to implement the above approach   // Function to find the required absolute difference function xorOr(arr, N) {     // Store the count of odds & evens at odd     // and even indices respectively     let evens = 0, odds = 0;      // Traverse the array to count even/odd     for (let i = 0; i < N; i++) {         if ((i + 1) % 2 == 0             && arr[i] % 2 == 0)             evens += arr[i];         else if ((i + 1) % 2 != 0             && arr[i] % 2 != 0)             odds += arr[i];     }      return Math.abs(odds - evens); }  // Driver Code let arr = [3, 4, 1, 5]; let N = arr.length; document.write(xorOr(arr, N));  // This code is contributed by gfgking. </script> 

 
 


Output
0


 

Time Complexity: O(N)
Auxiliary Space: O(1)


 


Next Article
Difference between sum of K maximum even and odd array elements

S

sushmitamittal1329
Improve
Article Tags :
  • Mathematical
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • Difference between sum of odd and even frequent elements in an Array
    Given an array arr[] of integers, the task is to find the absolute difference between the sum of all odd frequent array elements and the sum of all even frequent array elements. Examples: Input: arr[] = {1, 5, 5, 2, 4, 3, 3} Output: 9 Explanation: The even frequent elements are 5 and 3 (both occurri
    12 min read
  • Find the Array Permutation having sum of elements at odd indices greater than sum of elements at even indices
    Given an array arr[] consisting of N integers, the task is to find the permutation of array elements such that the sum of odd indices elements is greater than or equal to the sum of even indices elements. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1 4 2 3 Explanation:Consider the permutation of th
    6 min read
  • Absolute Difference of even and odd indexed elements in an Array
    Given an array of integers arr, the task is to find the running absolute difference of elements at even and odd index positions separately. Note: 0-based indexing is considered for the array. That is the index of the first element in the array is zero. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Out
    6 min read
  • Maximize the difference of sum of elements at even indices and odd indices by shifting an odd sized subarray to end of given Array.
    Given an array arr[] of size N, the task is to maximize the difference of the sum of elements at even indices and elements at odd indices by shifting any subarray of odd length to the end of the array. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}Output: 3Explanation: Initially sum of elements at even
    13 min read
  • Difference between sum of K maximum even and odd array elements
    Given an array arr[] and a number K, the task is to find the absolute difference of the sum of K maximum even and odd array elements.Note: At least K even and odd elements are present in the array respectively. Examples: Input arr[] = {1, 2, 3, 4, 5, 6}, K = 2Output: 2Explanation:The 2 maximum even
    8 min read
  • Find the absolute difference of set bits at even and odd indices of N
    Given an integer N, the task is to find the absolute difference of set bits at even and odd indices of number N. (0-based Indexing) Examples: Input: N = 15Output: 0Explanation: The binary representation of 15 is 1111. So, it contains 1 on the 1st and 3rd position and it contains 1 on the 0th and 2nd
    5 min read
  • Sum of absolute differences of indices of occurrences of each array element | Set 2
    Given an array, arr[] consisting of N integers, the task for each array element arr[i] is to print the sum of |i – j| for all possible indices j such that arr[i] = arr[j]. Examples: Input: arr[] = {1, 3, 1, 1, 2}Output: 5 0 3 4 0Explanation:For arr[0], sum = |0 – 0| + |0 – 2| + |0 – 3| = 5.For arr[1
    11 min read
  • Rearrange sorted array such that all odd indices elements comes before all even indices element
    Given a sorted array arr[] consisting of N positive integers, the task is to rearrange the array such that all the odd indices elements come before all the even indices elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}Output: 2 4 6 8 1 3 5 7 9 Input: arr[] = {0, 3, 7, 7, 10}Output: 3 7
    12 min read
  • Maximize difference between sum of even and odd-indexed elements of a subsequence
    Given an array arr[] consisting of N positive integers, the task is to find the maximum possible difference between the sum of even and odd-indexed elements of a subsequence from the given array. Examples: Input: arr[] = { 3, 2, 1, 4, 5, 2, 1, 7, 8, 9 } Output: 15 Explanation: Considering the subseq
    7 min read
  • Minimize increments required to make differences between all pairs of array elements even
    Given an array, arr[] consisting of N integers, the task is to minimize the number of increments of array elements required to make all differences pairs of array elements even. Examples: Input: arr[] = {4, 1, 2}Output: 1Explanation: Operation 1: Increment arr[1] by 1. The array arr[] modifies to {4
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences