-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Maxm_consecutive_avgint_pairs.cpp
84 lines (76 loc) · 1.9 KB
/
Maxm_consecutive_avgint_pairs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
A pair of two consecutive members u and v on a line is considered average integer pair
if their average is an integer,
i.e. (u+v)/2 is an integer.
Given an array, arrange the elements,
such that number of consecutive average integer pairs is maximised.
*/
#include<bits/stdc++.h>
using namespace std;
//Function to reorder elements such that number of consecutive average integer pairs is maximised.
void Maximum_consecutive_avgint_pair(int n, int arr[]) {
int odd=0, even=0;
//Count the no of even and odd nos in the array
for( int i=0; i<n ; i++){
if( arr[i] % 2 != 0){
odd++;
}
else{
even++;
}
}
/*If the no of odd is greater than no of even print
the odd nos first followed by the even nos*/
if( odd > even){
for( int i=0; i<n ; i++){
if( arr[i] % 2 != 0){
cout << arr[i] << " ";
}
}
for( int i=0; i<n ; i++){
if( arr[i] % 2 == 0){
cout << arr[i] << " ";
}
}
}
/*If the no of even is greater than no of odd print
the even nos first followed by the odd nos*/
else{
for( int i=0; i<n ;i++){
if( arr[i] % 2 == 0){
cout << arr[i] << " ";
}
}
for( int i=0; i<n ;i++){
if( arr[i] % 2 != 0){
cout << arr[i] << " ";
}
}
}
}
int main() {
int n;
cout << "Enter the no of elements in array:" <<endl;
cin >> n;
int arr[n];
cout << "Enter the elements in array:" <<endl;
for( int i=0; i<n ;i++){
cin >> arr[i];
}
cout << "The reordered array is: "<<endl;
Maximum_consecutive_avgint_pair(n, arr);
return 0;
}
/*
Sample Input/Output:
Input:
Enter the no of elements in array:
8
Enter the elements in array:
10 9 13 15 3 16 9 13
Output:
The reordered array is:
9 13 15 3 9 13 10 16
Time complexity:-O(n) to compute odd and even numbers
Space complexity:- O(n)
*/