Represent N as sum of K even or K odd numbers with repetitions allowed | Java implementation to find an array of size K with all the even or odd elements in the array ; Function to find the array with all the even / odd elements ; First let 's check  kth is odd or even ; If last element is also an odd number then we can choose odd elements for our answer ; Add 1 in the array ( k - 1 ) times ; Add last odd element ; If array of even elements would be the answer then k - 1 elements would be 2 ; If last element is also an even number then we can choose even elements for our answer ; Add 2 in the array ( k - 1 ) times ; Add last even element ; Printing the array ; Driver code
import java . util . * ; class GFG { static void getArrayOfSizeK ( int n , int k ) { Vector < Integer > ans = new Vector < Integer > ( ) ; int odd = n - ( ( k - 1 ) * 1 ) ; if ( odd > 0 && odd % 2 != 0 ) { for ( int i = 0 ; i < k - 1 ; i ++ ) { ans . add ( 1 ) ; } ans . add ( odd ) ; } int even = n - ( ( k - 1 ) * 2 ) ; if ( even > 0 && even % 2 == 0 && ans . size ( ) == 0 ) { for ( int i = 0 ; i < k - 1 ; i ++ ) { ans . add ( 2 ) ; } ans . add ( even ) ; } if ( ans . size ( ) > 0 ) { for ( int i = 0 ; i < k ; i ++ ) { System . out . print ( ans . get ( i ) + " ▁ " ) ; } } else { System . out . println ( " NO " ) ; } } public static void main ( String args [ ] ) { int n = 10 , k = 3 ; getArrayOfSizeK ( n , k ) ; } }