Minimum count of numbers needed from 1 to N that yields the sum as K | Java program for the above approach ; Function to find minimum number of elements required to obtain sum K ; Stores the maximum sum that can be obtained ; If K is greater than the Maximum sum ; If K is less than or equal to to N ; Stores the sum ; Stores the count of numbers needed ; Iterate until N is greater than or equal to 1 and sum is less than K ; Increment count by 1 ; Increment sum by N ; Update the sum ; Finally , return the count ; Driver Code ; Given Input ; Function Call
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 ) ) ; } }