Rearrange Array to minimize difference of sum of squares of odd and even index elements
Last Updated :
27 Mar, 2023
Given an array arr[] of size N (multiple of 8) where the values in the array will be in the range [a, (a+8*N) -1] (a can be any positive integer), the task is to rearrange the array in a way such that the difference between the sum of squares at odd indices and sum of squares of the elements at even indices is the minimum among all possible rearrangements.
Note: If there are multiple rearrangements return any one of those.
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8}
Output: 1 2 4 3 7 8 6 5
Explanation: The difference is 0 as 1 + 42 + 72 + 62 = 102 = 22 + 32 + 82 + 52
Input: arr[] = { 9, 11, 12, 15, 16, 13, 10, 14}
Output: 9 10 12 11 15 16 14 13
Explanation: The difference is 0 as 92 + 122 + 152 + 142 = 102 + 112 + 162 + 132 = 646
Approach: This problem can be solved based on the following mathematical observation:
For any positive integer S, ( S )2 + ( S+3 )2 - 4 = ( S+1 )2 + ( S+2 )2. As N is a multiple of 8 so it can be divided into N/8 groups where the difference of sum of squares of elements at odd and even indices for each group is 0.
For the first four elements keep the sum of squares at odd indices greater and four the next four just the opposite to keep the sum of squares of even indices more. So this group of 8 elements will have difference 0. As the similar is done for all N/8 groups the overall difference will be 0.
The sequence of each group can be like: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
Follow the below steps to solve this problem:
- Divide the array into groups of size 8.
- Arrange elements in each group as derived from the observation.
- Return the rearranged array.
Below is the implementation of the above approach:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find
// maximum element of the array
int maximum(int arr[], int size)
{
int ma = INT_MIN;
for (int i = 0; i < size; i++) {
ma = max(ma, arr[i]);
}
return ma;
}
// Function to find
// minimum element of the array
int minimum(int arr[], int size)
{
int mi = INT_MAX;
for (int i = 0; i < size; i++) {
mi = min(mi, arr[i]);
}
return mi;
}
// Function to print the array
void print_min(int arr[], int size)
{
int low = minimum(arr, size);
int high = maximum(arr, size);
// using the fact that
// s^2 + (s+3)^2 = (s+1)^2 + (s+2)^2 + 4.
for (int i = 0; i < size; i += 4) {
// Making the difference +4
// for the odd indices
if (i % 8 == 0) {
arr[i] = low;
arr[i + 2] = low + 3;
arr[i + 1] = low + 1;
arr[i + 3] = low + 2;
}
// Making the difference -4 for
// odd indices +4 - 4 = 0 (balanced)
else {
arr[i] = low + 2;
arr[i + 2] = low + 1;
arr[i + 1] = low + 3;
arr[i + 3] = low;
}
low += 4;
}
// Printing the array
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int N = sizeof(arr) / (sizeof(int));
// Function call
print_min(arr, N);
return 0;
}
Java
// JAVA code to implement the approach
import java.util.*;
class GFG
{
// Function to find
// maximum element of the array
public static int maximum(int arr[], int size)
{
int ma = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
ma = Math.max(ma, arr[i]);
}
return ma;
}
// Function to find
// minimum element of the array
public static int minimum(int arr[], int size)
{
int mi = Integer.MAX_VALUE;
for (int i = 0; i < size; i++) {
mi = Math.min(mi, arr[i]);
}
return mi;
}
// Function to print the array
public static void print_min(int arr[], int size)
{
int low = minimum(arr, size);
int high = maximum(arr, size);
// using the fact that
// s^2 + (s+3)^2 = (s+1)^2 + (s+2)^2 + 4.
for (int i = 0; i < size; i += 4) {
// Making the difference +4
// for the odd indices
if (i % 8 == 0) {
arr[i] = low;
arr[i + 2] = low + 3;
arr[i + 1] = low + 1;
arr[i + 3] = low + 2;
}
// Making the difference -4 for
// odd indices +4 - 4 = 0 (balanced)
else {
arr[i] = low + 2;
arr[i + 2] = low + 1;
arr[i + 1] = low + 3;
arr[i + 3] = low;
}
low += 4;
}
// Printing the array
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int N = arr.length;
// Function call
print_min(arr, N);
}
}
// This code is contributed by Taranpreet
Python3
# Python code to implement the approach
INT_MIN = -2147483647 - 1
INT_MAX = 2147483647
# Function to find
# maximum element of the array
def maximum(arr, size):
ma = INT_MIN
for i in range(size):
ma = max(ma, arr[i])
return ma
# Function to find
# minimum element of the array
def minimum(arr, size):
mi = INT_MAX
for i in range(size):
mi = min(mi, arr[i])
return mi
# Function to print the array
def print_min(arr, size):
low = minimum(arr, size)
high = maximum(arr, size)
# using the fact that
# s^2 + (s+3)^2 = (s+1)^2 + (s+2)^2 + 4.
for i in range(0,size,4):
# Making the difference +4
# for the odd indices
if (i % 8 == 0):
arr[i] = low
arr[i + 2] = low + 3
arr[i + 1] = low + 1
arr[i + 3] = low + 2
# Making the difference -4 for
# odd indices +4 - 4 = 0 (balanced)
else:
arr[i] = low + 2
arr[i + 2] = low + 1
arr[i + 1] = low + 3
arr[i + 3] = low
low += 4
# Printing the array
for i in range(size):
print(arr[i],end=" ")
# Driver code
arr = [1, 2, 3, 4, 5, 6, 7, 8]
N = len(arr)
# Function call
print_min(arr, N)
# This code is contributed by shinjanpatra
C#
// C# code to implement the approach
using System;
class GFG {
// Function to find
// maximum element of the array
static int maximum(int[] arr, int size)
{
int ma = Int32.MinValue;
for (int i = 0; i < size; i++) {
ma = Math.Max(ma, arr[i]);
}
return ma;
}
// Function to find
// minimum element of the array
static int minimum(int[] arr, int size)
{
int mi = Int32.MaxValue;
for (int i = 0; i < size; i++) {
mi = Math.Min(mi, arr[i]);
}
return mi;
}
// Function to print the array
static void print_min(int[] arr, int size)
{
int low = minimum(arr, size);
int high = maximum(arr, size);
// using the fact that
// s^2 + (s+3)^2 = (s+1)^2 + (s+2)^2 + 4.
for (int i = 0; i < size; i += 4) {
// Making the difference +4
// for the odd indices
if (i % 8 == 0) {
arr[i] = low;
arr[i + 2] = low + 3;
arr[i + 1] = low + 1;
arr[i + 3] = low + 2;
}
// Making the difference -4 for
// odd indices +4 - 4 = 0 (balanced)
else {
arr[i] = low + 2;
arr[i + 2] = low + 1;
arr[i + 1] = low + 3;
arr[i + 3] = low;
}
low += 4;
}
// Printing the array
for (int i = 0; i < size; i++) {
Console.Write(arr[i] + " ");
}
}
// Driver code
public static void Main()
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
int N = arr.Length;
// Function call
print_min(arr, N);
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript code to implement the approach
const INT_MIN = -2147483647 - 1;
const INT_MAX = 2147483647;
// Function to find
// maximum element of the array
const maximum = (arr, size) => {
let ma = INT_MIN;
for (let i = 0; i < size; i++) {
ma = Math.max(ma, arr[i]);
}
return ma;
}
// Function to find
// minimum element of the array
const minimum = (arr, size) => {
let mi = INT_MAX;
for (let i = 0; i < size; i++) {
mi = Math.min(mi, arr[i]);
}
return mi;
}
// Function to print the array
const print_min = (arr, size) => {
let low = minimum(arr, size);
let high = maximum(arr, size);
// using the fact that
// s^2 + (s+3)^2 = (s+1)^2 + (s+2)^2 + 4.
for (let i = 0; i < size; i += 4) {
// Making the difference +4
// for the odd indices
if (i % 8 == 0) {
arr[i] = low;
arr[i + 2] = low + 3;
arr[i + 1] = low + 1;
arr[i + 3] = low + 2;
}
// Making the difference -4 for
// odd indices +4 - 4 = 0 (balanced)
else {
arr[i] = low + 2;
arr[i + 2] = low + 1;
arr[i + 1] = low + 3;
arr[i + 3] = low;
}
low += 4;
}
// Printing the array
for (let i = 0; i < size; i++) {
document.write(`${arr[i]} `);
}
}
// Driver code
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
let N = arr.length;
// Function call
print_min(arr, N);
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Another Approach:
- Divide the array into groups of size 8. (a)Since the given array has a length that is a multiple of 8, we can divide it into N/8 groups, where N is the length of the array.
- Arrange elements in each group as derived from the observation. (a)We can use the mathematical observation mentioned in the problem statement:
For any positive integer S, ( S )2 + ( S+3 )2 – 4 = ( S+1 )2 + ( S+2 )2
(b)We can use this formula to derive a sequence of numbers for each group of 8 elements that will keep the difference of sum of squares at odd and even indices zero.
(c)The sequence of each group can be like: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
(d)We can initialize S to be the minimum value in the array and then increment it by 4 for each group to get the above sequence.
- Return the rearranged array. (a)After arranging each group as described in step 2, we can return the rearranged array.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the minimum element in the array
int findMin(int arr[], int size) {
int minElement = INT_MAX;
for (int i = 0; i < size; i++) {
minElement = min(minElement, arr[i]);
}
return minElement;
}
// Function to rearrange the elements in each group
void rearrangeGroup(int arr[], int startValue) {
// Using the formula: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
arr[0] = startValue;
arr[1] = startValue + 1;
arr[2] = startValue + 3;
arr[3] = startValue + 2;
arr[4] = startValue + 6;
arr[5] = startValue + 7;
arr[6] = startValue + 5;
arr[7] = startValue + 4;
}
// Function to rearrange the array
void rearrangeArray(int arr[], int size) {
int minElement = findMin(arr, size);
for (int i = 0; i < size; i += 8) {
if (i % 16 == 0) {
// For odd-indexed sum of squares > even-indexed sum of squares
rearrangeGroup(&arr[i], minElement);
} else {
// For even-indexed sum of squares > odd-indexed sum of squares
rearrangeGroup(&arr[i], minElement + 2);
}
minElement += 8;
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
// Driver code
int main() {
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int size = sizeof(arr) / sizeof(arr[0]);
// Rearrange the array
rearrangeArray(arr, size);
// Print the rearranged array
printArray(arr, size);
return 0;
}
Java
// Java Code to implement the approach
import java.util.*;
public class GFG {
// Function to find the minimum element in the array
public static int findMin(int[] arr, int size) {
int minElement = Integer.MAX_VALUE;
for (int i = 0; i < size; i++) {
minElement = Math.min(minElement, arr[i]);
}
return minElement;
}
// Function to rearrange the elements in each group
public static void rearrangeGroup(int[] arr, int startValue) {
// Using the formula: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
arr[0] = startValue;
arr[1] = startValue + 1;
arr[2] = startValue + 3;
arr[3] = startValue + 2;
arr[4] = startValue + 6;
arr[5] = startValue + 7;
arr[6] = startValue + 5;
arr[7] = startValue + 4;
}
// Function to rearrange the array
public static void rearrangeArray(int[] arr, int size) {
int minElement = findMin(arr, size);
for (int i = 0; i < size; i += 8) {
if (i % 16 == 0) {
// For odd-indexed sum of squares > even-indexed sum of squares
rearrangeGroup(arr, minElement);
} else {
// For even-indexed sum of squares > odd-indexed sum of squares
rearrangeGroup(arr, minElement + 2);
}
minElement += 8;
}
}
// Function to print the array
public static void printArray(int[] arr, int size) {
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// Driver code
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
int size = arr.length;
// Rearrange the array
rearrangeArray(arr, size);
// Print the rearranged array
printArray(arr, size);
}
}
Python3
# Python3 Code to implement the approach
import sys
# Function to find the minimum element in the array
def findMin(arr, size):
minElement = sys.maxsize
for i in range(size):
minElement = min(minElement, arr[i])
return minElement
# Function to rearrange the elements in each group
def rearrangeGroup(arr, startValue):
# Using the formula: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
new_arr = [startValue, startValue + 1, startValue + 3, startValue +
2, startValue + 6, startValue + 7, startValue + 5, startValue + 4]
return new_arr
# Function to rearrange the array
def rearrangeArray(arr, size):
minElement = findMin(arr, size)
for i in range(0, size, 8):
if i % 16 == 0:
# For odd-indexed sum of squares > even-indexed sum of squares
new_arr = rearrangeGroup(arr[i:i+8], minElement)
else:
# For even-indexed sum of squares > odd-indexed sum of squares
new_arr = rearrangeGroup(arr[i:i+8], minElement + 2)
arr[i:i+8] = new_arr
minElement += 8
# Function to print the array
def printArray(arr, size):
for i in range(size):
print(arr[i], end=" ")
print()
# Driver code
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6, 7, 8]
size = len(arr)
# Rearrange the array
rearrangeArray(arr, size)
# Print the rearranged array
printArray(arr, size)
C#
using System;
class GFG
{
// Function to find the minimum element in the array
static int FindMin(int[] arr, int size) {
int minElement = int.MaxValue;
for (int i = 0; i < size; i++) {
minElement = Math.Min(minElement, arr[i]);
}
return minElement;
}
// Function to rearrange the elements in each group
static void RearrangeGroup(int[] arr, int startValue) {
// Using the formula: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
arr[0] = startValue;
arr[1] = startValue + 1;
arr[2] = startValue + 3;
arr[3] = startValue + 2;
arr[4] = startValue + 6;
arr[5] = startValue + 7;
arr[6] = startValue + 5;
arr[7] = startValue + 4;
}
// Function to rearrange the array
static void RearrangeArray(int[] arr, int size) {
int minElement = FindMin(arr, size);
for (int i = 0; i < size; i += 8) {
if (i % 16 == 0) {
// For odd-indexed sum of squares > even-indexed sum of squares
RearrangeGroup(arr, minElement);
} else {
// For even-indexed sum of squares > odd-indexed sum of squares
RearrangeGroup(arr, minElement + 2);
}
minElement += 8;
}
}
// Function to print the array
static void PrintArray(int[] arr, int size) {
for (int i = 0; i < size; i++) {
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
// Driver code
static void Main(string[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
int size = arr.Length;
// Rearrange the array
RearrangeArray(arr, size);
// Print the rearranged array
PrintArray(arr, size);
}
}
JavaScript
// JavaScript Code to implement the approach
// Function to find the minimum element in the array
function findMin(arr) {
let minElement = Infinity;
for (let i = 0; i < arr.length; i++) {
minElement = Math.min(minElement, arr[i]);
}
return minElement;
}
// Function to rearrange the elements in each group
function rearrangeGroup(arr, startValue) {
// Using the formula: S, S+1, S+3, S+2, S+6, S+7, S+5, S+4
arr[0] = startValue;
arr[1] = startValue + 1;
arr[2] = startValue + 3;
arr[3] = startValue + 2;
arr[4] = startValue + 6;
arr[5] = startValue + 7;
arr[6] = startValue + 5;
arr[7] = startValue + 4;
}
// Function to rearrange the array
function rearrangeArray(arr) {
let minElement = findMin(arr);
for (let i = 0; i < arr.length; i += 8) {
if (i % 16 === 0) {
// For odd-indexed sum of squares > even-indexed sum of squares
rearrangeGroup(arr, minElement);
} else {
// For even-indexed sum of squares > odd-indexed sum of squares
rearrangeGroup(arr, minElement + 2);
}
minElement += 8;
}
}
// Function to print the array
function printArray(arr) {
console.log(arr.join(' '));
}
// Driver code
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
// Rearrange the array
rearrangeArray(arr);
// Print the rearranged array
printArray(arr);
Time Complexity: O(N), where N is the size of the array
Auxiliary Space: O(1)
Similar Reads
Minimize sum of absolute differences of same-indexed elements of two given arrays by at most one replacement
Given two arrays A[] and B[] of size N each, the task is to find the minimum possible sum of absolute difference of same indexed elements of the two arrays, i.e. sum of |A[i] - B[i]| for all i such that 0 ? i < N by replacing at most one element in A[] with another element of A[]. Examples: Input
10 min read
Maximize difference between sum of even and odd-indexed elements of a subsequence
Given an array arr[] consisting of N positive integers, the task is to find the maximum possible difference between the sum of even and odd-indexed elements of a subsequence from the given array. Examples: Input: arr[] = { 3, 2, 1, 4, 5, 2, 1, 7, 8, 9 } Output: 15 Explanation: Considering the subseq
7 min read
Maximize difference between odd and even indexed array elements by shift operations
Given an array arr[] of size N, the task is to maximize the absolute difference between the sum of even indexed elements and the sum of odd indexed elements by left shift or right shift of array elements any number of times. Examples: Input: arr[] = {332, 421, 215, 584, 232}Output: 658Explanation: C
9 min read
Maximize difference between sum of even and odd-indexed elements of a subsequence | Set 2
Given an array arr[] consisting of N positive integers, the task is to find the maximum value of the difference between the sum of elements at even and odd indices for any subsequence of the array. Note: The value of N is always greater than 1. Examples: Input: arr[] = { 3, 2, 1, 4, 5, 2, 1, 7, 8, 9
11 min read
Maximum difference between sum of even and odd indexed elements of a Subarray
Given an array nums[] of size N, the task is to find the maximum difference between the sum of even and odd indexed elements of a subarray. Examples: Input: nums[] = {1, 2, 3, 4, -5}Output: 9Explanation: If we select the subarray {4, -5} the sum of even indexed elements is 4 and odd indexed element
11 min read
Reverse a subarray to maximize sum of even-indexed elements of given array
Given an array arr[], the task is to maximize the sum of even-indexed elements by reversing a subarray and print the maximum sum obtained. Examples: Input: arr[] = {1, 2, 1, 2, 1} Output: 5 Explanation: Sum of initial even-indexed elements = a[0] + a[2] + a[4] = 1 + 1 + 1 = 3 Reversing subarray {1,
9 min read
Minimize sum of squares of adjacent elements difference
Given an Array arr[] or N elements, the task is to minimize the sum of squares of difference of adjacent elements by adding one element at any position of the array. Examples: Input: N = 4, arr = [4, 7, 1, 4]Output: 36Explanation: The sum of squares of difference of adjacent element before inserting
7 min read
Maximize the difference of sum of elements at even indices and odd indices by shifting an odd sized subarray to end of given Array.
Given an array arr[] of size N, the task is to maximize the difference of the sum of elements at even indices and elements at odd indices by shifting any subarray of odd length to the end of the array. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}Output: 3Explanation: Initially sum of elements at even
13 min read
Minimize increments required to make differences between all pairs of array elements even
Given an array, arr[] consisting of N integers, the task is to minimize the number of increments of array elements required to make all differences pairs of array elements even. Examples: Input: arr[] = {4, 1, 2}Output: 1Explanation: Operation 1: Increment arr[1] by 1. The array arr[] modifies to {4
5 min read
Rearrange an array to minimize sum of product of consecutive pair elements
We are given an array of even size, we have to sort the array in such a way that the sum of product of alternate elements is minimum also we have to find that minimum sum. Examples: Input : arr[] = {9, 2, 8, 4, 5, 7, 6, 0} Output : Minimum sum of the product of consecutive pair elements: 74 Sorted a
7 min read