Open In App

Optimal Array

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a sorted array A[] of length N. For each i(0 ≤ i ≤ n-1), you have to make all the elements of the array from index 0 to i equal, using the minimum number of operations. In one operation you either increase or decrease the array element by 1. the task is to return a list that contains the minimum number of operations for each i, to accomplish the above task.

Note:

  • 0-based indexing.
  • For each index, you need to consider the same array which was given to you at the start.

Examples:

Input: N = 4, A[] = {1, 6, 9, 12}
Output: 0 5 8 14

Input: N = 7, A[] ={1, 1, 1, 7, 7, 10, 19}
Output: 0 0 0 6 12 21 33
Explanation: Possible operations could be:
{1}->{1}
{1, 1}->{1, 1}
{1, 1, 1}->{1, 1, 1}
{1, 1, 1, 7}->{1, 1, 1, 1}
{1, 1, 1, 7, 7}->{1, 1, 1, 1, 1}
{1, 1, 1, 7, 7, 10}->{5, 5, 5, 5, 5, 5}
{1, 1, 1, 7, 7, 10, 19}->{7, 7, 7, 7, 7, 7, 7}

Approach: This can be solved by the following idea:

We basically apply the concept of median here as there will be less operation required in changing all elements into their median but here we need to focus on one point if we take the median for odd n/2 and even n/2 + n/2+ 1 average then we will require two loops and we run out of the time (TLE) so we will take median as n/2 and subtract it from every value and then all it and it will be our answer or we can say that just add (i-1)th element operation with a value of i index subtracting medium from it.

Steps involved in the implementation of the code:

  • Initialize an array of the long type which will store the value of the minimum operation required and name it “ans”.
  • Set the 0th index value of ans = 0 because any value is equal to itself.
  • Take an integer variable let’s name it  “res”  initialize it with 1 and use it as the reference index of ans.
  • Start the for loop and inside it set the condition ans[res] = ans[i-1]+(a[i]-a[i/2]) which means the operation required to change all values from 0th to i-1 index + value of ith index – median value and assign this value in ans.
  • Increment “res” by 1 to go to the next index of ans and store its value in the next iteration.

Below is the code of the above approach:

C++14




#include <iostream>
#include <vector>
using namespace std;
 
// Function to find minimum number of operations required to
// make all elements equal
vector<long long> optimalArray(int n, int a[])
{
    // Vector to store minimum operation
    vector<long long> ans(n);
 
    // Set minimum operation of array with 1 element as 0
    ans[0] = 0;
 
    // Create a variable for reference index of ans vector
    int res = 1;
 
    for (int i = 1; i < n; i++) {
        // Operation required for i-1th element + value of
        // ith index - median
        ans[res] = ans[i - 1] + (a[i] - a[i / 2]);
        res++;
    }
 
    return ans;
}
 
// Function to print a vector
void printArray(vector<long long> arr, int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
 
    cout << endl;
}
 
// Driver code
int main()
{
    int n = 4;
    int a[] = { 1, 6, 9, 12 };
 
    // Function call
    vector<long long> ans = optimalArray(n, a);
    printArray(ans, n);
 
    return 0;
}


Java




// Java code for the above approach:
import java.io.*;
 
class GFG {
 
    // Function to find minimum number of
    // operations required to make
    // all elements equal
    static public long[] optimalArray(int n, int a[])
    {
 
        // Array to store minimum
        // operation
        long ans[] = new long[n];
 
        // Set minimum operation of array
        // with 1 element as 0
        ans[0] = 0;
 
        // Create a variable for reference
        // index of ans array
        int res = 1;
 
        for (int i = 1; i < n; i++) {
 
            // operation required for i-1th
            // element + value of ith
            // index - median
            ans[res] = ans[i - 1] + (a[i] - a[i / 2]);
            res++;
        }
        return ans;
    }
 
    // Function to print an array
    static void printArray(long 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 n = 4;
        int[] a = { 1, 6, 9, 12 };
 
        // Function call
        long[] ans = optimalArray(n, a);
        printArray(ans, n);
    }
}


Python3




# Python code for the above approach:
 
# Function to find minimum number of
# operations required to make
# all elements equal
 
 
def optimalArray(n, a):
 
    # Array to store minimum
    # operation
    ans = [0] * n
 
    # Set minimum operation of array
    # with 1 element as 0
    ans[0] = 0
 
    # Create a variable for reference
    # index of ans array
    res = 1
 
    for i in range(1, n):
 
        # operation required for i-1th
        # element + value of ith
        # index - median
        ans[res] = ans[i - 1] + (a[i] - a[i // 2])
        res += 1
 
    return ans
 
# Function to print an array
 
 
def printArray(arr, size):
    for i in range(size):
        print(arr[i], end=' ')
    print()
 
 
# Driver code
n = 4
a = [1, 6, 9, 12]
 
# Function call
ans = optimalArray(n, a)
printArray(ans, n)
 
# This code is contributed by prasad264


Javascript




// Function to find minimum number of operations required to make
// all elements equal
function optimalArray(n, a)
{
 
  // Vector to store minimum operation
  const ans = new Array(n);
 
  // Set minimum operation of array with 1 element as 0
  ans[0] = 0;
 
  // Create a variable for reference index of ans vector
  let res = 1;
 
  for (let i = 1; i < n; i++) {
    // Operation required for i-1th element + value of ith index - median
    ans[res] = ans[i - 1] + (a[i] - a[Math.floor(i / 2)]);
    res++;
  }
 
  return ans;
}
 
// Function to print a vector
function printArray(arr, size) {
  for (let i = 0; i < size; i++)
    process.stdout.write(arr[i] + " ");
}
 
// Driver code
const n = 4;
const a = [1, 6, 9, 12];
 
// Function call
const ans = optimalArray(n, a);
printArray(ans, n);


C#




using System;
using System.Collections.Generic;
 
public class Program {
    // Function to find minimum number of operations
    // required to make all elements equal
    static List<long> OptimalArray(int n, int[] a)
    {
        // List to store minimum operation
        List<long> ans = new List<long>(n);
 
        // Set minimum operation of array with 1 element as
        // 0
        ans.Add(0);
 
        // Create a variable for reference index of ans
        // vector
        int res = 1;
 
        for (int i = 1; i < n; i++) {
            // Operation required for i-1th element + value
            // of ith index - median
            ans.Add(ans[i - 1] + (a[i] - a[i / 2]));
            res++;
        }
 
        return ans;
    }
 
    // Function to print a list
    static void PrintArray(List<long> arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");
 
        Console.WriteLine();
    }
 
    // Driver code
    static void Main()
    {
        int n = 4;
        int[] a = { 1, 6, 9, 12 };
 
        // Function call
        List<long> ans = OptimalArray(n, a);
        PrintArray(ans, n);
    }
}


Output

0 5 8 14 

Time Complexity: O(n), where n is the size of the array ‘a’, because the code contains a single for-loop that iterates n-1 times. Therefore, the time complexity is linear in terms of the input size.
Auxiliary Space:  O(n), because it creates a vector ‘ans’ of size n to store the minimum operations required to make all elements equal. Therefore, the space complexity is also linear in terms of the input size.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads