Count distinct sum of pairs possible from a given range
Last Updated :
26 Mar, 2021
Given two positive integers L and R ( where L ? R ), the task is to count the number of distinct integers that can be obtained by adding any pair of integers from the range [L, R].
Examples:
Input: L = 3, R = 5
Output: 11
Explanation: All possible distinct sum of pairs are as follows:
- (3, 3). Sum = 6.
- (3, 4). Sum = 7.
- (3, 5). Sum = 8.
- (4, 5). Sum = 9.
- (5, 5). Sum = 10.
Therefore, the count of distinct sums is 5.
Input: L = 12, R = 14
Output: 5
Naive Approach: The simplest approach to solve the given problem is to find the sum of all possible pairs of numbers from the range [L, R] and print the count of all distinct sums obtained.
Time Complexity: O((L – R)2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observations:
- Since, the given range [L, R] is continuous, the range of numbers obtained by adding will also be continuous.
- The minimum and maximum sum of pairs from the range are given by 2 * L and 2 * R respectively.
- Therefore, the count distinct sum of pairs is given by (2 * R – 2 * L + 1).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int distIntegers( int L, int R)
{
return 2 * R - 2 * L + 1;
}
int main()
{
int L = 3, R = 8;
cout << distIntegers(L, R);
return 0;
}
|
Java
import java.io.*;
class GFG{
static int distIntegers( int L, int R)
{
return 2 * R - 2 * L + 1 ;
}
public static void main (String[] args)
{
int L = 3 , R = 8 ;
System.out.println(distIntegers(L, R));
}
}
|
Python3
def distIntegers(L, R):
return 2 * R - 2 * L + 1
if __name__ = = '__main__' :
L, R = 3 , 8
print (distIntegers(L, R))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int distIntegers( int L, int R)
{
return 2 * R - 2 * L + 1;
}
static public void Main()
{
int L = 3, R = 8;
Console.Write(distIntegers(L, R));
}
}
|
Javascript
<script>
function distIntegers(L,R)
{
return 2 * R - 2 * L + 1;
}
let L = 3, R = 8;
document.write(distIntegers(L, R));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...