GFG App
Open App
Browser
Continue

# Minimize the indices of consecutive ones

Given an array X[] of odd length N(N â‰Ą 3) and an integer K. Arrange elements of X[] in such a way that the merged binary representation of all the elements let’s say S has the minimum number of indices i such that  Si = Si+1 = 1. Then you need to perform the given operation K times where you can increment any element by 1 on the initial array, the task is to return the arrangement of elements following the given condition to minimize indices such that
Si = Si+1 = 1 in the binary representation of new arrangement elements and maximized median of X[] that can be maximized using the given operation.

Note: If there are multiple arrangements satisfying the given criteria then print any valid arrangement.

Examples:

Input: N = 3, X[] = {3, 6, 5}, K = 2
Output: Arrangement = 6 5 3
Maximum Median = 6
Explanation:

• Arrangement:
• Binary representations of 6, 5, and 3 are 110, 101, and 11 respectively. String S is formed by merging all binary representations: 11010111. It has 3 indices i (1, 6, and 7) such that Si = Si+1 = 1. Which are the minimum possible number of such indices.
• Maximum Median:
• Initial X[]: {3, 6, 5}
• Let us chose X[3] = 5, and increment it by 1. Then updated X[] is: {3, 6, 6}
• Let us chose X[3] = 6, and increment it by 1. Then updated X[] is: {3, 6, 7}
• It can be verified that using a given operation under K = 2 times, the Median can’t be maximized than 6.

Input: N = 5, X[] = {5, 3, 1, 2, 3}, K = 4
Output: Arrangement = 3 1 2 3 5
Maximum Median = 5
Explanation: It can be verified that the above inputs will generate the outputs as per problem statement.

Approach: Implement the idea below to solve the problem:

The problem is observation and Greedy logic based and can be solve by using some observations. The observations are related to odd numbers present inside X[]. For maximizing median first Sort X[], then increment mid element, Formally X[mid] += 1 and then move X[mid] to its respective sorted position again. You can follow this approach K times

Steps were taken to solve the problem:

• Steps were taken for arrangement:
• Create a variable let’s say odd and initialize it equal to -1,
• Create a StringBuilder object let’s say Sb.
• Run a loop for traversing X[] and follow the below-mentioned steps under the scope of the loop:
• if (X[ i ] % 2 ! =  0 && odd ==  -1),  Then odd = X[ i ]
• else Sb.append( X[ i ] )
• if (odd != -1) then Sb.append(odd)
• Output StringBuilder Sb.
• Steps were taken for maximizing the median:
• Sort X[].
• Create a variable let’s say mid = (X.length – 1)/2
• Run a loop K number of times and follow the below-mentioned steps under the scope of the loop:
• Increment X[mid], Formally X[mid] += 1
• Swap X[mid] to its right side at its respective sorted position.
• Output X[mid].

Below is the code to implement the approach:

## C++

 `#include ` `#include ` `#include `   `using` `namespace` `std;`   `// Method for valid arrangements` `void` `Arrangement(``int` `N, vector<``int``>& X) {` `    ``int` `odd = -1;`   `    ``// Vector object created` `    ``vector<``int``> l;`   `    ``// Loop for traversing over X[]` `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``if` `(X[i] % 2 != 0 && odd == -1) {` `            ``odd = X[i];` `        ``} ``else` `{` `            ``l.push_back(X[i]);` `        ``}` `    ``}`   `    ``if` `(odd != -1) {` `        ``l.push_back(odd);` `    ``}`   `    ``// Printing arrangement` `    ``cout << ``"Arrangement : "``;` `    ``for` `(``int` `i = 0; i < l.size(); i++) {` `        ``cout << l[i] << ``" "``;` `    ``}` `    ``cout << endl;` `}`   `// Method for maximizing median` `void` `Max_Median(``int` `K, vector<``int``>& X) {` `    ``// Sorting X[] using in-built sort function` `    ``sort(X.begin(), X.end());`   `    ``// Calculating mid-index` `    ``int` `mid = (X.size() - 1) / 2;`   `    ``// Loop for K number of times` `    ``for` `(``int` `j = 1; j <= K; j++) {` `        ``// Incrementing mid` `        ``X[mid]++;`   `        ``// Temporary variable to hold mid index value` `        ``int` `i = mid;`   `        ``// Loop for sorting X[] after incrementing X[mid] element` `        ``// Formally, It swaps mid element until it is greater than its` `        ``// right adjacent element for placing incremented X[mid]` `        ``// at its sorting position` `        ``while` `(X[i] > X[i + 1] && i <= X.size() - 2) {` `            ``int` `temp = X[i];` `            ``X[i] = X[i + 1];` `            ``X[i + 1] = temp;`   `            ``if` `(i < X.size() - 2) {` `                ``i++;` `            ``}` `        ``}` `    ``}`   `    ``// Printing Maximized median` `    ``cout << ``"Maximum Median : "` `<< X[mid] << endl;` `}`   `// Driver Function` `int` `main() {` `    ``// Inputs` `    ``int` `N = 3;` `    ``int` `K = 2;` `    ``vector<``int``> X {3, 6, 5};`   `    ``// Function call for arrangement` `    ``Arrangement(N, X);`   `    ``// Function call for Maximum Max_Median` `    ``Max_Median(K, X);`   `    ``return` `0;` `}`   `// This code is contributed by Tushar_Rokade`

## Java

 `// Java code to implement the approach` `import` `java.io.*;` `import` `java.lang.*;` `import` `java.util.*;`   `class` `GFG {`   `    ``// Driver Function` `    ``public` `static` `void` `main(String[] args)` `        ``throws` `java.lang.Exception` `    ``{`   `        ``// Inputs` `        ``int` `N = ``3``;` `        ``int` `K = ``2``;` `        ``int` `X[] = { ``3``, ``6``, ``5` `};`   `        ``// Function call for arrangement` `        ``System.out.print(``"Arrangement : "``);` `        ``Arrangement(N, X);`   `        ``// Function call for Maximum` `        ``// Max_Median` `        ``Max_Median(K, X);` `    ``}`   `    ``// Method for valid arrangements` `    ``static` `void` `Arrangement(``int` `N, ``int` `X[])` `    ``{` `        ``int` `odd = -``1``;`   `        ``// StringBuilder object created` `        ``StringBuilder sb = ``new` `StringBuilder();`   `        ``// Loop for traversing over X[]` `        ``for` `(``int` `i = ``0``; i < N; i++) {` `            ``if` `(X[i] % ``2` `!= ``0` `&& odd == -``1``) {` `                ``odd = X[i];` `            ``}` `            ``else` `{` `                ``sb.append(X[i]);` `                ``sb.append(``" "``);` `            ``}` `        ``}` `        ``if` `(odd != -``1``) {` `            ``sb.append(odd);` `        ``}`   `        ``// Printing arrangement` `        ``System.out.println(``" "` `+ sb);` `    ``}`   `    ``// Method for maximizing median` `    ``static` `void` `Max_Median(``int` `K, ``int` `X[])` `    ``{`   `        ``// Sorting X[] using in-built sort` `        ``// function` `        ``Arrays.sort(X);`   `        ``// Calculating mid-index` `        ``int` `mid = (X.length - ``1``) / ``2``;`   `        ``// Loop for K number of times` `        ``for` `(``int` `j = ``1``; j <= K; j++) {`   `            ``// Incrementing mid` `            ``X[mid] += ``1``;`   `            ``// Temporary variable to hold` `            ``// mid index value` `            ``int` `i = mid;`   `            ``// Loop for sorting X[] after` `            ``// incrementing X[mid] element` `            ``// Formally, It swaps mid element` `            ``// until it is greater than its` `            ``// right adjacent element for` `            ``// placing incremented X[mid]` `            ``// at its sorting position` `            ``while` `(X[i] > X[i + ``1``] && i <= X.length - ``2``) {` `                ``int` `temp = X[i];` `                ``X[i] = X[i + ``1``];` `                ``X[i + ``1``] = temp;`   `                ``if` `(i < X.length - ``2``)` `                    ``i++;` `            ``}` `        ``}`   `        ``// Printing Maximized median` `        ``System.out.println(``"Maximum Median : "` `+ X[mid]);` `    ``}` `}`

## Python3

 `import` `numpy as np`   `# Method for valid arrangements` `def` `Arrangement(N, X):` `    ``odd ``=` `-``1`   `    ``# List object created` `    ``l ``=` `[]`   `    ``# Loop for traversing over X[]` `    ``for` `i ``in` `range``(N):` `        ``if` `X[i] ``%` `2` `!``=` `0` `and` `odd ``=``=` `-``1``:` `            ``odd ``=` `X[i]` `        ``else``:` `            ``l.append(X[i])`   `    ``if` `odd !``=` `-``1``:` `        ``l.append(odd)`   `    ``# Printing arrangement` `    ``print``(``"Arrangement : "``, end``=``"")` `    ``print``(``*``l, sep``=``" "``)`   `# Method for maximizing median` `def` `Max_Median(K, X):` `    ``# Sorting X[] using in-built sort` `    ``# function` `    ``X ``=` `np.sort(X)`   `    ``# Calculating mid-index` `    ``mid ``=` `(X.shape[``0``] ``-` `1``) ``/``/` `2`   `    ``# Loop for K number of times` `    ``for` `j ``in` `range``(``1``, K``+``1``):` `        ``# Incrementing mid` `        ``X[mid] ``+``=` `1`   `        ``# Temporary variable to hold` `        ``# mid index value` `        ``i ``=` `mid`   `        ``# Loop for sorting X[] after` `        ``# incrementing X[mid] element` `        ``# Formally, It swaps mid element` `        ``# until it is greater than its` `        ``# right adjacent element for` `        ``# placing incremented X[mid]` `        ``# at its sorting position` `        ``while` `X[i] > X[i ``+` `1``] ``and` `i <``=` `X.shape[``0``] ``-` `2``:` `            ``temp ``=` `X[i]` `            ``X[i] ``=` `X[i ``+` `1``]` `            ``X[i ``+` `1``] ``=` `temp`   `            ``if` `i < X.shape[``0``] ``-` `2``:` `                ``i ``+``=` `1`   `    ``# Printing Maximized median` `    ``print``(``"Maximum Median :"``, X[mid])`   `# Driver Function` `if` `__name__ ``=``=` `"__main__"``:`   `    ``# Inputs` `    ``N ``=` `3` `    ``K ``=` `2` `    ``X ``=` `np.array([``3``, ``6``, ``5``])`   `    ``# Function call for arrangement` `    ``Arrangement(N, X)`   `    ``# Function call for Maximum` `    ``# Max_Median` `    ``Max_Median(K, X)`

## C#

 `using` `System;` `using` `System.Collections.Generic;` `using` `System.Linq;`   `class` `Program {` `  `  `  ``// Method for valid arrangements` `  ``static` `void` `Arrangement(``int` `N, List<``int``> X) {` `    ``int` `odd = -1;`   `    ``// List object created` `    ``List<``int``> l = ``new` `List<``int``>();`   `    ``// Loop for traversing over X[]` `    ``for` `(``int` `i = 0; i < N; i++) {` `      ``if` `(X[i] % 2 != 0 && odd == -1) {` `        ``odd = X[i];` `      ``} ``else` `{` `        ``l.Add(X[i]);` `      ``}` `    ``}`   `    ``if` `(odd != -1) {` `      ``l.Add(odd);` `    ``}`   `    ``// Printing arrangement` `    ``Console.Write(``"Arrangement : "``);` `    ``foreach` `(``int` `i ``in` `l) {` `      ``Console.Write(i + ``" "``);` `    ``}` `    ``Console.WriteLine();` `  ``}`   `  ``// Method for maximizing median` `  ``static` `void` `Max_Median(``int` `K, List<``int``> X) {` `    ``// Sorting X[] using in-built sort function` `    ``X.Sort();`   `    ``// Calculating mid-index` `    ``int` `mid = (X.Count - 1) / 2;`   `    ``// Loop for K number of times` `    ``for` `(``int` `j = 1; j <= K; j++) {` `      ``// Incrementing mid` `      ``X[mid]++;`   `      ``// Temporary variable to hold mid index value` `      ``int` `i = mid;`   `      ``// Loop for sorting X[] after incrementing X[mid] element` `      ``// Formally, It swaps mid element until it is greater than its` `      ``// right adjacent element for placing incremented X[mid]` `      ``// at its sorting position` `      ``while` `(X[i] > X[i + 1] && i <= X.Count - 2) {` `        ``int` `temp = X[i];` `        ``X[i] = X[i + 1];` `        ``X[i + 1] = temp;`   `        ``if` `(i < X.Count - 2) {` `          ``i++;` `        ``}` `      ``}` `    ``}`   `    ``// Printing Maximized median` `    ``Console.WriteLine(``"Maximum Median : "` `+ X[mid]);` `  ``}`   `  ``// Driver Function` `  ``static` `void` `Main() {` `    ``// Inputs` `    ``int` `N = 3;` `    ``int` `K = 2;` `    ``List<``int``> X = ``new` `List<``int``> {3, 6, 5};`   `    ``// Function call for arrangement` `    ``Arrangement(N, X);`   `    ``// Function call for Maximum Max_Median` `    ``Max_Median(K, X);` `  ``}` `}`

## Javascript

 ``

Output

```Arrangement :  6 5 3
Maximum Median : 6```

Time Complexity: O(K * N), for arrangement of numbers, O(N * Log(N)), to find maximum median
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up