Generate an array of size K which satisfies the given conditions | Java implementation of the approach ; Function to generate and print the required array ; Initializing the array ; Finding r ( from above approach ) ; If r < 0 ; Finding ceiling and floor values ; Fill the array with ceiling values ; Fill the array with floor values ; Add 1 , 2 , 3 , ... with corresponding values ; There is no solution for below cases ; Modify A [ 1 ] and A [ k - 1 ] to get the required array ; Driver Code
class GFG { static void generateArray ( int n , int k ) { int [ ] array = new int [ k ] ; int remaining = n - ( k * ( k + 1 ) / 2 ) ; if ( remaining < 0 ) System . out . print ( " NO " ) ; int right_most = remaining % k ; int high = ( int ) Math . ceil ( remaining / ( k * 1.0 ) ) ; int low = ( int ) Math . floor ( remaining / ( k * 1.0 ) ) ; for ( int i = k - right_most ; i < k ; i ++ ) array [ i ] = high ; for ( int i = 0 ; i < ( k - right_most ) ; i ++ ) array [ i ] = low ; for ( int i = 0 ; i < k ; i ++ ) array [ i ] += i + 1 ; if ( k - 1 != remaining k == 1 ) { for ( int u : array ) System . out . print ( u + " ▁ " ) ; } else if ( k == 2 k == 3 ) System . out . printf ( "-1NEW_LINE"); else { array [ 1 ] -= 1 ; array [ k - 1 ] += 1 ; for ( int u : array ) System . out . print ( u + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 26 , k = 6 ; generateArray ( n , k ) ; } }