Find K positive integers not exceeding N and having sum S | Java implementation for the above approach ; Function to represent S as the sum of K positive integers less than or equal to N ; If S can cannot be represented as sum of K integers ; If sum of first i natural numbers exceeds S ; Insert i into nums [ ] ; Insert first K - 1 positive numbers into answer [ ] ; Insert the K - th number ; Traverse the array answer [ ] ; If current element exceeds N ; Add the extra value to the previous element ; Reduce current element to N ; Printing the K numbers ; Driver code
import java . util . Vector ; class GFG { static void solve ( int S , int K , int N ) { if ( K > N ) { System . out . println ( " - 1" ) ; return ; } int max_sum = 0 , min_sum = 0 ; for ( int i = 1 ; i <= K ; i ++ ) { min_sum += i ; max_sum += N - i + 1 ; } if ( S < min_sum S > max_sum ) { System . out . println ( " - 1" ) ; return ; } int s1 = 0 ; Vector < Integer > nums = new Vector < > ( ) ; for ( int i = 1 ; i <= N ; i ++ ) { if ( s1 > S ) break ; s1 += i ; nums . add ( i ) ; } Vector < Integer > answer = new Vector < > ( ) ; int s2 = 0 ; for ( int i = 0 ; i < K - 1 ; i ++ ) { answer . add ( nums . get ( i ) ) ; s2 += nums . get ( i ) ; } answer . add ( S - s2 ) ; int Max = N ; for ( int i = answer . size ( ) - 1 ; i >= 0 ; i -- ) { if ( answer . get ( i ) > Max ) { int extra = answer . get ( i ) - Max ; if ( i - 1 >= 0 ) answer . set ( i - 1 , answer . get ( i - 1 ) + extra ) ; answer . set ( i , Max ) ; Max -- ; } else break ; } for ( int x : answer ) System . out . print ( x + " ▁ " ) ; System . out . println ( ) ; } public static void main ( String [ ] args ) { int S = 15 , K = 4 , N = 8 ; solve ( S , K , N ) ; } }