Generate an array of size K which satisfies the given conditions | Python3 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
import sys NEW_LINE from math import floor , ceil NEW_LINE def generateArray ( n , k ) : NEW_LINE INDENT array = [ 0 ] * k NEW_LINE remaining = n - int ( k * ( k + 1 ) / 2 ) NEW_LINE if remaining < 0 : NEW_LINE INDENT print ( " NO " ) NEW_LINE sys . exit ( ) NEW_LINE DEDENT right_most = remaining % k NEW_LINE high = ceil ( remaining / k ) NEW_LINE low = floor ( remaining / k ) NEW_LINE for i in range ( k - right_most , k ) : NEW_LINE INDENT array [ i ] = high NEW_LINE DEDENT for i in range ( k - right_most ) : NEW_LINE INDENT array [ i ] = low NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT array [ i ] += i + 1 NEW_LINE DEDENT if k - 1 != remaining or k == 1 : NEW_LINE INDENT print ( * array ) NEW_LINE sys . exit ( ) NEW_LINE DEDENT elif k == 2 or k == 3 : NEW_LINE INDENT print ( " - 1" ) NEW_LINE sys . exit ( ) NEW_LINE DEDENT else : NEW_LINE INDENT array [ 1 ] -= 1 NEW_LINE array [ k - 1 ] += 1 NEW_LINE print ( * array ) NEW_LINE sys . exit ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 26 , 6 NEW_LINE generateArray ( n , k ) NEW_LINE DEDENT