Related Articles

Related Articles

Costs required to move all 1s to each index of a given Binary Array
  • Difficulty Level : Medium
  • Last Updated : 26 Oct, 2020

Given a binary array, in which, moving an element from index i to index j requires abs(i – j) cost. The task is to find the cost to move all 1s to each index of the given array.

Examples:

Input: arr[] = {0, 1, 0, 1}
Output: 4 2 2 2
Explanation: 
Moving elements from index 1, index 3 to index 0 requires abs(0 – 1) + abs(0 – 3) = 4.
Moving elements from index 1, index 3 to index 1 requires abs(1 – 1) + abs(1 – 3) = 2.
Moving elements from index 1, index 2 to index 2 requires abs(2 – 1) + abs(2 – 3) = 2.
Moving elements from index 1, index 2 to index 3 requires abs(3 – 1) + abs(3 – 3) = 2.
Therefore, the required output is 4 2 2 2.

Input: arr[] = {1, 1, 1}
Output: 3 2 3

 

Naive Approach: The simplest approach to solve this problem is to traverse the given array and for each array element of the given array, print the cost to move all 1s of the given array to the current index.



Below are the implementations of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the cost
// to move all 1s to each index
void costMove1s(int arr[], int N)
{
    // Traverse the array.
    for (int i = 0; i < N; i++) {
         
        // Stores cost to move
        // all 1s at current index
        int cost = 0;
         
         
        // Calculate cost to move
        // all 1s at current index
        for (int j = 0; j < N;
                          j++) {
                               
            // If current element
            // of the array is 1.
            if (arr[j] == 1) {
                 
                // Update cost
                cost += abs(i - j);
            }
        }
        cout<<cost<<" ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 0, 1, 0, 1};
    int N = sizeof(arr) / sizeof(arr[0]);
     
    costMove1s(arr, N);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.io.*;
 
class GFG{
 
// Function to print the cost
// to move all 1s to each index
static void costMove1s(int[] arr, int N)
{
     
    // Traverse the array.
    for(int i = 0; i < N; i++)
    {
         
        // Stores cost to move
        // all 1s at current index
        int cost = 0;
 
        // Calculate cost to move
        // all 1s at current index
        for(int j = 0; j < N; j++)
        {
             
            // If current element
            // of the array is 1.
            if (arr[j] == 1)
            {
                 
                // Update cost
                cost += Math.abs(i - j);
            }
        }
        System.out.print(cost + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 0, 1, 0, 1 };
    int N = arr.length;
 
    costMove1s(arr, N);
}
}
 
// This code is contributed by akhilsaini

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Pyhton3 program to implement
# the above approach
 
# Function to print the cost
# to move all 1s to each index
def costMove1s(arr, N):
     
    # Traverse the array.
    for i in range(0, N):
         
        # Stores cost to move
        # all 1s at current index
        cost = 0
 
        # Calculate cost to move
        # all 1s at current index
        for j in range(0, N):
             
            # If current element
            # of the array is 1.
            if (arr[j] == 1):
 
                # Update cost
                cost = cost + abs(i - j)
 
        print(cost, end = " ")
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 0, 1, 0, 1 ]
    N = len(arr)
 
    costMove1s(arr, N)
 
# This code is contributed by akhilsaini

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to print the cost
// to move all 1s to each index
static void costMove1s(int[] arr, int N)
{
     
    // Traverse the array.
    for(int i = 0; i < N; i++)
    {
         
        // Stores cost to move
        // all 1s at current index
        int cost = 0;
 
        // Calculate cost to move
        // all 1s at current index
        for(int j = 0; j < N; j++)
        {
             
            // If current element
            // of the array is 1.
            if (arr[j] == 1)
            {
                 
                // Update cost
                cost += Math.Abs(i - j);
            }
        }
        Console.Write(cost + " ");
    }
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 0, 1, 0, 1 };
    int N = arr.Length;
 
    costMove1s(arr, N);
}
}
 
// This code is contributed by akhilsaini

chevron_right


Output: 

4 2 2 2








 

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to traverse the given array and find the cost to move all 1s from the left side and right side of each index of the given array using prefix sum technique. Follow the steps below to solve the problem:

  • Initialize an array, say cost[] to store the cost to move all 1s at each index of the given array.
  • Initialize two variables, say costLeft, costRight to store the cost to move all 1s from the left side and right side of each index respectively.
  • Traverse the given array from left to right and increment the value of costLeft by the number of 1s on the left side and the value of result[i] by costLeft ..
  • Traverse the given array from right to left and increment the value of costRight by the number of 1s on the right side and the value of result[i] by costRight .
  • Finally, print cost[] array.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the cost
// to move all 1s to each index
void costMove1s(int arr[], int N)
{
     
    // cost[i] Stores cost to move
    // all 1s at index i
    int cost[N] = { 0 };
     
    // Stores count of 1s on
    // the left side of index i
    int cntLeft = 0;
     
    // Stores cost to move all 1s
    // from the left side of index i
    // to index i
    int costLeft = 0;
     
    // Traverse the array from
    // left to right.
    for (int i = 0; i < N; i++) {
         
        // Update cost to move
        // all 1s from left side
        // of index i to index i
        costLeft += cntLeft;
         
         
        // Update cost[i] to cntLeft
        cost[i] += costLeft;
         
        // If current element is 1.
        if (arr[i] == 1) {
            cntLeft++;
        }
    }
     
    // Stores count of 1s on
    // the right side of index i
    int cntRight = 0;
     
     
    // Stores cost to move all 1s
    // from the right of index i
    // to index i
    int costRight = 0;
     
    // Traverse the array from
    // right to left.
    for (int i = N - 1; i >= 0;
                          i--) {
         
        // Update cost to move
        // all 1s from right side
        // of index i to index i
        costRight += cntRight;
         
        // Update cost[i]
        // to costRight
        cost[i] += costRight;
         
        // If current element
        // is 1.
        if (arr[i] == 1) {
            cntRight++;
        }
    }
     
    // Print cost to move all 1s
    for(int i = 0; i< N; i++) {
        cout<<cost[i]<<" ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 0, 1, 0, 1};
    int N = sizeof(arr) / sizeof(arr[0]);
    costMove1s(arr, N);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.io.*;
 
class GFG{
   
// Function to print the cost
// to move all 1s to each index
static void costMove1s(int arr[], int N)
{
     
    // cost[i] Stores cost to move
    // all 1s at index i
    int cost[] = new int[N];
 
    // Stores count of 1s on
    // the left side of index i
    int cntLeft = 0;
 
    // Stores cost to move all 1s
    // from the left side of index i
    // to index i
    int costLeft = 0;
 
    // Traverse the array from
    // left to right.
    for(int i = 0; i < N; i++)
    {
         
        // Update cost to move
        // all 1s from left side
        // of index i to index i
        costLeft += cntLeft;
 
        // Update cost[i] to cntLeft
        cost[i] += costLeft;
 
        // If current element is 1.
        if (arr[i] == 1)
        {
            cntLeft++;
        }
    }
 
    // Stores count of 1s on
    // the right side of index i
    int cntRight = 0;
 
    // Stores cost to move all 1s
    // from the right of index i
    // to index i
    int costRight = 0;
 
    // Traverse the array from
    // right to left.
    for(int i = N - 1; i >= 0; i--)
    {
         
        // Update cost to move
        // all 1s from right side
        // of index i to index i
        costRight += cntRight;
         
        // Update cost[i]
        // to costRight
        cost[i] += costRight;
 
        // If current element
        // is 1.
        if (arr[i] == 1)
        {
            cntRight++;
        }
    }
 
    // Print cost to move all 1s
    for(int i = 0; i < N; i++)
    {
        System.out.print(cost[i] + " ");
    }
}
 
// Driver Code
public static void main (String[] args)
{
    int arr[] = { 0, 1, 0, 1 };
    int N = arr.length;
     
    // Function Call
    costMove1s(arr, N);
}
}
 
// This code is contributed by math_lover

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to prthe cost
# to move all 1s to each index
def costMove1s(arr, N):
     
    # cost[i] Stores cost to move
    # all 1s at index i
    cost = [0] * N
     
    # Stores count of 1s on
    # the left side of index i
    cntLeft = 0
 
    # Stores cost to move all 1s
    # from the left side of index i
    # to index i
    costLeft = 0
 
    # Traverse the array from
    # left to right.
    for i in range(N):
 
        # Update cost to move
        # all 1s from left side
        # of index i to index i
        costLeft += cntLeft
 
        # Update cost[i] to cntLeft
        cost[i] += costLeft
 
        # If current element is 1.
        if (arr[i] == 1):
            cntLeft += 1
 
    # Stores count of 1s on
    # the right side of index i
    cntRight = 0
 
    # Stores cost to move all 1s
    # from the right of index i
    # to index i
    costRight = 0
 
    # Traverse the array from
    # right to left.
    for i in range(N - 1, -1, -1):
         
        # Update cost to move
        # all 1s from right side
        # of index i to index i
        costRight += cntRight
         
        # Update cost[i]
        # to costRight
        cost[i] += costRight
 
        # If current element
        # is 1.
        if (arr[i] == 1):
            cntRight += 1
 
    # Print cost to move all 1s
    for i in range(N):
        print(cost[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 0, 1, 0, 1 ]
    N = len(arr)
     
    costMove1s(arr, N)
 
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
 
class GFG{
   
// Function to print the cost
// to move all 1s to each index
static void costMove1s(int []arr, int N)
{
     
    // cost[i] Stores cost to move
    // all 1s at index i
    int []cost = new int[N];
 
    // Stores count of 1s on
    // the left side of index i
    int cntLeft = 0;
 
    // Stores cost to move all 1s
    // from the left side of index i
    // to index i
    int costLeft = 0;
 
    // Traverse the array from
    // left to right.
    for(int i = 0; i < N; i++)
    {
         
        // Update cost to move
        // all 1s from left side
        // of index i to index i
        costLeft += cntLeft;
 
        // Update cost[i] to cntLeft
        cost[i] += costLeft;
 
        // If current element is 1.
        if (arr[i] == 1)
        {
            cntLeft++;
        }
    }
 
    // Stores count of 1s on
    // the right side of index i
    int cntRight = 0;
 
    // Stores cost to move all 1s
    // from the right of index i
    // to index i
    int costRight = 0;
 
    // Traverse the array from
    // right to left.
    for(int i = N - 1; i >= 0; i--)
    {
         
        // Update cost to move
        // all 1s from right side
        // of index i to index i
        costRight += cntRight;
 
        // Update cost[i]
        // to costRight
        cost[i] += costRight;
 
        // If current element
        // is 1.
        if (arr[i] == 1)
        {
            cntRight++;
        }
    }
 
    // Print cost to move all 1s
    for(int i = 0; i < N; i++)
    {
        Console.Write(cost[i] + " ");
    }
}
 
// Driver Code
public static void Main (String[] args)
{
    int []arr = { 0, 1, 0, 1 };
    int N = arr.Length;
     
    // Function Call
    costMove1s(arr, N);
}
}
 
// This code is contributed by math_lover

chevron_right


Output: 

4 2 2 2








 

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :