Count of distinct sums formed by N numbers taken from range [L, R]
Last Updated :
26 Feb, 2023
Given three integers N, L, and R. The task is to count distinct sums formed by using N numbers from the range [L, R], where any number can be taken infinite times.
Examples:
Input: N = 2, L = 1, R = 3
Output: 5
Explanation: Generating all distinct combinations of 2 numbers taken from the range [1, 3]
{1, 1} => sum = 2
{1, 2} => sum = 3
{1, 3} => sum = 4
{2, 2} => sum = 4
{2, 3} => sum = 5
{3, 3} => sum = 6
Therefore, there are 5 (2, 3, 4, 5, 6) different sums possible with 2 numbers taken from range [1, 3].
Input: N = 3, L = 1, R = 9
Output: 10
Naïve Approach: The simplest approach to solve the given problem is to generate all possible combinations of N numbers from the range [L, R] and then count the total distinct sums formed by those combinations.
Time Complexity: O((R – L)N)
Auxiliary Space: O(1)
Efficient Approach: The given problem can be solved by some observation and by the use of some math. Here minimum and maximum numbers that can be used are L and R respectively. So, the minimum and maximum possible sum that can be formed are L*N (all N numbers are L) and R*N (all N numbers are R) respectively, Similarly, all other sums in between this range can also be formed. Follow the steps below to solve the given problem.
- Initialize a variable say, minSum = L*N, to store the minimum possible sum.
- Initialize a variable say, maxSum = R*N, to store the maximum possible sum.
- The final answer is the total numbers in the range [minSum, maxSum] i.e., (maxSum – minSum + 1).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countDistinctSums( int N, int L, int R)
{
int minSum = L * N;
int maxSum = R * N;
return maxSum - minSum + 1;
}
int main()
{
int N = 2, L = 1, R = 3;
cout << countDistinctSums(N, L, R);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countDistinctSums( int N, int L, int R)
{
int minSum = L * N;
int maxSum = R * N;
return maxSum - minSum + 1 ;
}
public static void main(String[] args)
{
int N = 2 , L = 1 , R = 3 ;
System.out.print(countDistinctSums(N, L, R));
}
}
|
Python3
def countDistinctSums(N, L, R):
minSum = L * N
maxSum = R * N
return maxSum - minSum + 1
if __name__ = = "__main__" :
N = 2
L = 1
R = 3
print (countDistinctSums(N, L, R))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int countDistinctSums( int N, int L, int R)
{
int minSum = L * N;
int maxSum = R * N;
return maxSum - minSum + 1;
}
public static void Main()
{
int N = 2, L = 1, R = 3;
Console.Write(countDistinctSums(N, L, R));
}
}
|
Javascript
<script>
function countDistinctSums(N, L, R) {
let minSum = L * N;
let maxSum = R * N;
return maxSum - minSum + 1;
}
let N = 2, L = 1, R = 3;
document.write(countDistinctSums(N, L, R));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...