Minimum count of numbers needed from 1 to N that yields the sum as K
Last Updated :
26 Dec, 2022
Given two positive integers N and K, the task is to print the minimum count of numbers needed to get the sum equal to K, adding any element from the first N natural numbers only once. If it is impossible to get the sum equal to K, then print “-1“.
Examples:
Input: N = 5, K = 10
Output: 3
Explanation:
The most optimal way is to choose number {1, 4, 5} to which will sum up to 10.
Therefore, print 3 which is the minimum count of elements needed.
Input: N = 5, K = 1000
Output: -1
Explanation:
It is impossible to get the sum equal to 1000.
Approach: The problem can be solved using the greedy algorithm. Follow the steps below to solve this problem:
- If K is greater than the sum of first N natural numbers, then the print “-1” and then return.
- If K is less than equal to N, then print 1 and then return.
- Otherwise, Initialize the variable say sum, and count as 0 to store the sum and minimum count of numbers needed.
- Iterate until N is greater than equal to 1 and sum is less than K and perform the following steps:
- Incrementing count by 1, sum by N, and then decrement the N by 1.
- Finally, if none of the above cases satisfy then print the count as the answer.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int Minimum( int N, int K)
{
int sum = N * (N + 1) / 2;
if (K > sum)
return -1;
if (K <= N)
return 1;
sum = 0;
int count = 0;
while (N >= 1 && sum < K) {
count += 1;
sum += N;
N -= 1;
}
return count;
}
int main()
{
int N = 5, K = 10;
cout << (Minimum(N, K));
return 0;
}
|
Java
import java.io.*;
class GFG {
static int Minimum( int N, int K)
{
int sum = N * (N + 1 ) / 2 ;
if (K > sum)
return - 1 ;
if (K <= N)
return 1 ;
sum = 0 ;
int count = 0 ;
while (N >= 1 && sum < K) {
count += 1 ;
sum += N;
N -= 1 ;
}
return count;
}
public static void main(String[] args)
{
int N = 5 , K = 10 ;
System.out.println(Minimum(N, K));
}
}
|
Python3
def Minimum(N, K):
sum = N * (N + 1 ) / / 2
if (K > sum ):
return - 1
if (K < = N):
return 1
sum = 0
count = 0
while (N > = 1 and sum < K):
count + = 1
sum + = N
N - = 1
return count
if __name__ = = '__main__' :
N = 5
K = 10
print (Minimum(N, K))
|
C#
using System;
class GFG{
static int Minimum( int N, int K)
{
int sum = N * (N + 1) / 2;
if (K > sum)
return -1;
if (K <= N)
return 1;
sum = 0;
int count = 0;
while (N >= 1 && sum < K)
{
count += 1;
sum += N;
N -= 1;
}
return count;
}
static public void Main()
{
int N = 5, K = 10;
Console.Write(Minimum(N, K));
}
}
|
Javascript
<script>
function Minimum(N, K)
{
let sum = N * (N + 1) / 2;
if (K > sum)
return -1;
if (K <= N)
return 1;
sum = 0;
let count = 0;
while (N >= 1 && sum < K) {
count += 1;
sum += N;
N -= 1;
}
return count;
}
let N = 5, K = 10;
document.write(Minimum(N, K));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...