Open In App

Costs required to move all 1s to each index of a given Binary Array

Last Updated : 04 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 3 to index 2 requires abs(2 – 1) + abs(2 – 3) = 2.
Moving elements from index 1, index 3 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++




// 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);
}


Java




// 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


Python3




# Python3 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


C#




// 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


Javascript




<script>
// JavaScript program to implement
// the above approach
 
 
// Function to print the cost
// to move all 1s to each index
function costMove1s(arr, N)
{
    // Traverse the array.
    for (let i = 0; i < N; i++) {
         
        // Stores cost to move
        // all 1s at current index
        let cost = 0;
         
         
        // Calculate cost to move
        // all 1s at current index
        for (let j = 0; j < N;
                        j++) {
                             
            // If current element
            // of the array is 1.
            if (arr[j] == 1) {
                 
                // Update cost
                cost += Math.abs(i - j);
            }
        }
        document.write(cost + " ");
    }
}
 
// Driver Code
 
    let arr = [ 0, 1, 0, 1];
    let N = arr.length;
     
    costMove1s(arr, N);
 
 
//This code is contributed by Mayank Tyagi
</script>


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++14




// 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);
}


Java




// 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


Python3




# Python3 program to implement
# the above approach
 
# Function to print the 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


C#




// 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


Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to print the cost
// to move all 1s to each index
function costMove1s(arr, N)
{
     
    // cost[i] Stores cost to move
    // all 1s at index i
    var cost = Array(N).fill(0);
     
    // Stores count of 1s on
    // the left side of index i
    var cntLeft = 0;
     
    // Stores cost to move all 1s
    // from the left side of index i
    // to index i
    var costLeft = 0;
     
    // Traverse the array from
    // left to right.
    for(var 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
    var cntRight = 0;
     
    // Stores cost to move all 1s
    // from the right of index i
    // to index i
    var costRight = 0;
     
    // Traverse the array from
    // right to left.
    for(var 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(var i = 0; i< N; i++)
    {
        document.write(cost[i] + " ");
    }
}
 
// Driver Code
var arr = [ 0, 1, 0, 1 ];
var N = arr.length;
 
costMove1s(arr, N);
 
// This code is contributed by rutvik_56
 
</script>


Output: 

4 2 2 2

 

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads