https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/algorithm/the-savior-3/description/?layout=old
Below is copied from editorial
Let's start with two simple math facts:
- From elementary math we know that for any two integers a and b, a + b is even if and only if both a and b are even or both a and b are odd.
- If you have an array of K elements, you can produce K * (K - 1) / 2 pairs of its elements
Based on these fact, we can produce an optimal solution. Let ODD be the number of odd integers in A and EVEN be the number of even integers in it.
Then the number of pairs of integers (a, b) from A for which a + b is even equals ODD * (ODD - 1) / 2 + EVEN * (EVEN - 1) / 2. We are almost there, but notice that we are interested in the number of pairs of different integers, so we are possibly counting too much here. For example, if A contains number 3 two times, then it will be taken into the result, but we do not want it to be there.
So this program will fail when there are duplicates:
No comments:
Post a Comment