Minimum steps required to rearrange given array to a power sequence of 2
Last Updated :
05 May, 2021
Given an array arr[] consisting of N positive integers, the task is to find the minimum steps required to make the given array of integers into a sequence of powers of 2 by the following operations:
- Reorder the given array. It doesn’t count as a step.
- For each step, select any index i from the array and change arr[i] to arr[i] ? 1 or arr[i] + 1.
A sequence is called power sequence of 2, if for every ith index (0 ?i ? N ? 1),
arr[i] = 2i , where N is length of the given array.
Examples:
Input: arr[] = { 1, 8, 2, 10, 6 }
Output: 8
Explanation:
Reorder the array arr[] to { 1, 2, 6, 8, 10 }
Step 1: Decrement arr[2] to 5
Step 2: Decrement arr[2] to 4
Step 3 – 8: Increment arr[4] by 1. Final value of arr[4] becomes 16.
Therefore, arr[] = {1, 2, 4, 8, 16}
Hence, the minimum number of steps required to obtain the power sequence of 2 is 8.
Input: arr[] = { 1, 3, 4 }
Output: 1
Approach: To solve the given problem, the idea is to sort the array in ascending order and for every ith index of the sorted array, calculate the absolute difference between arr[i] and 2i. The sum of the absolute differences gives us the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minsteps( int arr[], int n)
{
sort(arr, arr + n);
int ans = 0;
for ( int i = 0; i < n; i++) {
ans += abs (arr[i] - pow (2, i));
}
return ans;
}
int main()
{
int arr[] = { 1, 8, 2, 10, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << minsteps(arr, n) << endl;
return 0;
}
|
Java
import java.util.*;
import java.lang.Math;
class GFG {
static int minsteps( int arr[], int n)
{
Arrays.sort(arr);
int ans = 0 ;
for ( int i = 0 ; i < n; i++) {
ans += Math.abs(arr[i] - Math.pow( 2 , i));
}
return ans;
}
public static void main(String[] args)
{
int arr[] = { 1 , 8 , 2 , 10 , 6 };
int n = arr.length;
System.out.println(minsteps(arr, n));
}
}
|
Python3
def minsteps(arr, n):
arr.sort()
ans = 0
for i in range (n):
ans + = abs (arr[i] - pow ( 2 , i))
return ans
arr = [ 1 , 8 , 2 , 10 , 6 ]
n = len (arr)
print (minsteps(arr, n))
|
C#
using System;
class GFG {
static int minsteps( int [] arr, int n)
{
Array.Sort(arr);
int ans = 0;
for ( int i = 0; i < n; i++) {
ans += Math.Abs(arr[i]
- ( int )(Math.Pow(2, i)));
}
return ans;
}
public static void Main()
{
int [] arr = { 1, 8, 2, 10, 6 };
int n = arr.Length;
Console.WriteLine(minsteps(arr, n));
}
}
|
Javascript
<script>
function minsteps(arr, n)
{
arr.sort((a,b)=>a-b)
var ans = 0;
for ( var i = 0; i < n; i++) {
ans += Math.abs(arr[i] - Math.pow(2, i));
}
return ans;
}
var arr = [ 1, 8, 2, 10, 6 ];
var n = arr.length;
document.write( minsteps(arr, n));
</script>
|
Time Complexity: O(NlogN)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...