Generate an array of K elements such that sum of elements is N and the condition a [ i ] < a [ i + 1 ] <= 2 * a [ i ] is met | Set 2 | Function that print the desired array which satisfies the given conditions ; If the lowest filling condition is void , then it is not possible to generate the required array ; Increase all the elements by cnt ; Start filling from the back till the number is a [ i + 1 ] <= 2 * a [ i ] ; Get the number to be filled ; If it is less than the remaining numbers to be filled ; less than remaining numbers to be filled ; Get the sum of the array ; If this condition is void at any stage during filling up , then print - 1 ; Else add it to the sum ; If the sum condition is not satisified , then print - 1 ; Print the generated array ; Driver code
< ? php function solve ( $ n , $ k ) { $ mini = 0 ; $ x1 = 1 ; $ a = array ( ) ; for ( $ i = 1 ; $ i <= $ k ; $ i ++ ) { $ mini += $ x1 ; $ a [ $ i - 1 ] = $ x1 ; $ x1 += 1 ; } if ( $ n < $ mini ) { echo " - 1" ; return ; } $ rem = $ n - $ mini ; $ cnt = floor ( $ rem / $ k ) ; $ rem = $ rem % $ k ; for ( $ i = 0 ; $ i < $ k ; $ i ++ ) $ a [ $ i ] += $ cnt ; for ( $ i = $ k - 1 ; $ i > 0 && $ rem > 0 ; $ i -- ) { $ xx = $ a [ $ i - 1 ] * 2 ; $ left = $ xx - $ a [ $ i ] ; if ( $ rem >= $ left ) { $ a [ $ i ] = $ xx ; $ rem -= $ left ; } else { $ a [ $ i ] += $ rem ; $ rem = 0 ; } } $ sum = $ a [ 0 ] ; for ( $ i = 1 ; $ i < $ k ; $ i ++ ) { if ( $ a [ $ i ] > 2 * $ a [ $ i - 1 ] ) { echo " - 1" ; return ; } $ sum += $ a [ $ i ] ; } if ( $ sum != $ n ) { echo " - 1" ; return ; } for ( $ i = 0 ; $ i < $ k ; $ i ++ ) echo $ a [ $ i ] , " ▁ " ; } $ n = 26 ; $ k = 6 ; solve ( $ n , $ k ) ; ? >