Find permutation of numbers upto N with a specific sum in a specific range | Java program for the above approach ; Function to check if sum is possible with remaining numbers ; Stores the minimum sum possible with x numbers ; Stores the maximum sum possible with x numbers ; If S lies in the range [ minSum , maxSum ] ; Function to find the resultant permutation ; Stores the count of numbers in the given segment ; If the sum is not possible with numbers in the segment ; Output - 1 ; Stores the numbers present within the given segment ; Iterate over the numbers from 1 to N ; If ( S - i ) is a positive non - zero sum and if it is possible to obtain ( S - i ) remaining numbers ; Update sum S ; Update required numbers in the segement ; Push i in vector v ; If sum has been obtained ; Break from the loop ; If sum is not obtained ; Output - 1 ; Stores the numbers which are not present in given segment ; Loop to check the numbers not present in the segment ; Pointer to check if i is present in vector v or not ; If i is not present in v ; Push i in vector v1 ; Point to the first elements of v1 and v respectively ; Print the required permutation ; Driver Code
import java . util . ArrayList ; class GFG { public static boolean possible ( int x , int S , int N ) { int minSum = ( x * ( x + 1 ) ) / 2 ; int maxSum = ( x * ( ( 2 * N ) - x + 1 ) ) / 2 ; if ( S < minSum S > maxSum ) { return false ; } return true ; } public static void findPermutation ( int N , int L , int R , int S ) { int x = R - L + 1 ; if ( ! possible ( x , S , N ) ) { System . out . print ( - 1 ) ; return ; } else { ArrayList < Integer > v = new ArrayList < > ( ) ; for ( int i = N ; i >= 1 ; -- i ) { if ( ( S - i ) >= 0 && possible ( x - 1 , S - i , i - 1 ) ) { S = S - i ; x -- ; v . add ( i ) ; } if ( S == 0 ) { break ; } } if ( S != 0 ) { System . out . print ( - 1 ) ; return ; } ArrayList < Integer > v1 = new ArrayList < Integer > ( ) ; for ( int i = 1 ; i <= N ; ++ i ) { boolean it = v . contains ( i ) ; if ( ! it ) { v1 . add ( i ) ; } } int j = 0 , f = 0 ; for ( int i = 1 ; i < L ; ++ i ) { System . out . print ( v1 . get ( j ) + " ▁ " ) ; j ++ ; } for ( int i = L ; i <= R ; ++ i ) { System . out . print ( v . get ( f ) + " ▁ " ) ; f ++ ; } for ( int i = R + 1 ; i <= N ; ++ i ) { System . out . print ( v1 . get ( j ) + " ▁ " ) ; j ++ ; } } return ; } public static void main ( String args [ ] ) { int N + C3 : AC3 = 6 , L = 3 , R = 5 , S = 8 ; findPermutation ( N , L , R , S ) ; } }