Given two integers and and an array arr every element of which at index is calculated as arr[i] = i * (-1)i. The task is to find the sum of these elements of the array within the index range .
Input: L = 1 , R = 5
Sum = (-1) + 2 + (-3) + 4 + (-5) = -3
Input: L = 5 , R = 100000000
Naive Approach: According to the definition of array elements, each odd element of the array is negative and even element is positive. So, to find the sum run a for loop from (L to R) and maintain the sum of all the odd(negative) and even(positive) numbers. Finally, return the sum.
Efficient Approach: It can be noted that the sum of all the odd elements of this series will always be equal to (totalOdd)2 where totalOdd = total number of odd elements and sum of the even numbers will be totalEven * (totalEven + 1). Now, all we have to do is to find the sum of all the odd elements upto L and upto R. Store the difference of both to get the sum of all the odd elements between L and R. Do this same for even numbers and finally return the difference of even and odd sums.
Below is the implementation of the above approach:
- Rearrange array such that even index elements are smaller and odd index elements are greater
- Queries for number of distinct elements from a given index till last index in an array
- Construct an array from XOR of all elements of array except element at same index
- Minimum index i such that all the elements from index i to given index are equal
- Count of index pairs with equal elements in an array
- Number of permutations such that sum of elements at odd index and even index are equal
- Check if every index i has an index j such that sum of elements in both directions are equal
- Minimum elements to change so that for an index i all elements on the left are -ve and all elements on the right are +ve
- Index of the elements which are equal to the sum of all succeeding elements
- Count smaller elements on right side and greater elements on left side using Binary Index Tree
- Minimum cost to reach end of array array when a maximum jump of K index is allowed
- Longest alternating sub-array starting from every index in a Binary Array
- Sum of elements till the smallest index such that there are no even numbers to its right
- Find an index such that difference between product of elements before and after it is minimum
- Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.