Generate an array with K positive numbers such that arr [ i ] is either | C ++ program for the above approach ; Function to generate the resultant sequence of first N natural numbers ; Initialize an array of size N ; Stores the sum of positive and negative elements ; Mark the first N - K elements as negative ; Update the value of arr [ i ] ; Update the value of sumNeg ; Mark the remaining K elements as positive ; Update the value of arr [ i ] ; Update the value of sumPos ; If the sum of the sequence is negative , then print - 1 ; Print the required sequence ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSequence ( int n , int k ) { int arr [ n ] ; int sumPos = 0 , sumNeg = 0 ; for ( int i = 0 ; i < n - k ; i ++ ) { arr [ i ] = - ( i + 1 ) ; sumNeg += arr [ i ] ; } for ( int i = n - k ; i < n ; i ++ ) { arr [ i ] = i + 1 ; sumPos += arr [ i ] ; } if ( abs ( sumNeg ) >= sumPos ) { cout << -1 ; return ; } for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int N = 10 , K = 6 ; findSequence ( N , K ) ; return 0 ; }