Minimum number of steps required to obtain the given Array by the given operations

Given an array arr[] of N positive integers, the task is to find the minimum number of operations required of the following types to obtain the array arr[] from an array of zeroes only.
- Select any index i and increment all the elements at the indices [i, N – 1] by 1.
- Select any index i and decrease all the elements at the indices [i, N – 1] by 1.
Examples:Â
Â
Input: arr[]={1,1,2,2,1}Â
Output: 3Â
Explanation:Â
Initially arr[] = {0,0,0,0,0}Â
Step 1: arr[]={1,1,1,1,1}(Operation 1 on index 0)Â
Step 2: arr[]={1,1,2,2,2}(Operation 1 on index 2)Â
Step 3: arr[]={1,1,2,2,1}(Operation 2 on index 4)
Input: arr[]={1,2,3,4}Â
Output: 4Â
Naive Approach: The simplest approach is to convert each element of the array result array, brr[] to arr[] by performing one of the above operations over the indices [i, N – 1] and increase the count of each operation performed.Â
Algorithm
1. Start by naming function min_operations that takes a list arr as input.
2. Then Create a new list brr with the same length as arr, filled with zeros.
3. Initialize a variable count to 0.
4. Loop over each element of arr using an index variable i:
a. Loop until the corresponding element of brr is equal to the corresponding element of arr:
i. If the current element of brr is less than the corresponding element of arr:
1. Loop over each element of brr starting from the current index i:
a. Increment each element of brr until it matches the corresponding element of arr.
2. Increment the count variable for each increment operation.
ii. If the current element of brr is greater than the corresponding element of arr:
1. Loop over each element of brr starting from the current index i:
a. Decrement each element of brr until it matches the corresponding element of arr.
2. Increment the count variable for each decrement operation.
5. Return the final count value.
C++
#include <iostream>#include <vector>Â
using namespace std;Â
int min_operations(vector<int>& arr){    // Create a new vector brr with the same    // length as arr, filled with zeros    vector<int> brr(arr.size(), 0);    // Initialize a variable count to 0    int count = 0;    // Loop over each element of arr    // using an index variable i    for (int i = 0; i < arr.size(); i++) {        // Loop until the corresponding element of brr        // is equal to the corresponding element of arr        while (brr[i] != arr[i]) {            // If the current element of brr is less            // than the corresponding element of arr            if (brr[i] < arr[i]) {                // Loop over each element of brr starting                // from the current index i                for (int j = i; j < arr.size(); j++) {                    // Increment each element of brr until                    // it                    // matches the corresponding element of                    // arr                    brr[j]++;                }                // Increment the count variable for each                // increment operation                count++;            }            // If the current element of brr is greater            // than the corresponding element of arr            else {                // Loop over each element of brr starting                // from the current index i                for (int j = i; j < arr.size(); j++) {                    // Decrement each element of brr until                    // it matches the corresponding element                    // of arr                    brr[j]--;                }                // Increment the count variable for each                // decrement operation                count++;            }        }    }    // Return the final count value    return count;}Â
int main(){Â Â Â Â vector<int> arr{ 1, 2, 3, 4 };Â Â Â Â cout << min_operations(arr) << endl; // Output: 4Â Â Â Â return 0;} |
Java
import java.io.*;Â
class GFG {  static int min_operations(int arr[]){    int length=arr.length;    /* Create a new array brr with the same      length as arr.*/    int []brr=new int[length];    // Initialize a variable count to 0    int count = 0;    // Loop over each element of arr using an index variable i    for (int i = 0; i < length; i++) {        /* Loop until the corresponding element of brr           is equal to the corresponding element of arr.*/        while (brr[i] != arr[i]) {            // If the current element of brr is less            // than the corresponding element of arr            if (brr[i] < arr[i]) {                // Loop over each element of brr starting                // from the current index i                for (int j = i; j < length; j++) {                    /* Increment each element of brr until it                     matches the corresponding element of arr*/                    brr[j]++;                }                // Increment the count variable for each increment operation                count++;            }            /* If the current element of brr is greater             than the corresponding element of arr*/            else {                /* Loop over each element of brr starting                 from the current index i*/                for (int j = i; j < length; j++) {                    /* Decrement each element of brr until                       it matches the corresponding element                       of arr*/                    brr[j]--;                }                // Increment the count variable for each decrement operation                count++;            }        }    }    // Return the final count value    return count;}  //Driver Code    public static void main (String[] args) {        int []arr=new int[]{1, 2, 3, 4};        //Function call        int minOperations= min_operations(arr); // Output: 4        System.out.println(minOperations);    }} |
Python
def min_operations(arr):    # Create a new list brr with the    # same length as arr, filled with zeros    brr = [0] * len(arr)    # Initialize a variable count to 0    count = 0    # Loop over each element of arr using an index variable i    for i in range(len(arr)):        # Loop until the corresponding element        # of brr is equal to the corresponding        # element of arr        while brr[i] != arr[i]:            # If the current element of brr is            # less than the            # corresponding element of arr            if brr[i] < arr[i]:                # Loop over each element of brr starting                # from the current index i                for j in range(i, len(arr)):                    # Increment each element of brr until it                    # matches the corresponding element of arr                    brr[j] += 1                # Increment the count variable for                # each increment operation                count += 1            # If the current element of brr is            # greater than the corresponding element of arr            else:                # Loop over each element of brr starting                # from the current index i                for j in range(i, len(arr)):                    # Decrement each element of brr until                    # it matches the corresponding element of arr                    brr[j] -= 1                # Increment the count variable for                # each decrement operation                count += 1    # Return the final count value    return countÂ
Â
# Example usage:arr = [1, 2, 3, 4]print(min_operations(arr))Â # Output: 4 |
C#
using System;using System.Collections.Generic;Â
class MainClass {  static int MinOperations(List<int> arr) {    // Create a new list brr with the same length as arr, filled with zeros    List<int> brr = new List<int>(new int[arr.Count]);    // Initialize a variable count to 0    int count = 0;    // Loop over each element of arr using an index variable i    for (int i = 0; i < arr.Count; i++) {      // Loop until the corresponding element of brr       // is equal to the corresponding element of arr      while (brr[i] != arr[i]) {        // If the current element of brr is less than the         // corresponding element of arr        if (brr[i] < arr[i]) {          // Loop over each element of brr starting from the current index i          for (int j = i; j < arr.Count; j++) {            // Increment each element of brr until it matches             // the corresponding element of arr            brr[j]++;          }          // Increment the count variable for each increment operation          count++;        }        // If the current element of brr is greater than the corresponding         // element of arr        else {          // Loop over each element of brr starting from the current index i          for (int j = i; j < arr.Count; j++) {            // Decrement each element of brr until it matches the             // corresponding element of arr            brr[j]--;          }          // Increment the count variable for each decrement operation          count++;        }      }    }    // Return the final count value    return count;  }Â
  public static void Main(string[] args) {    List<int> arr = new List<int>{ 1, 2, 3, 4 };    Console.WriteLine(MinOperations(arr)); // Output: 4  }} |
Javascript
function min_operations(arr){    // Create a new vector brr with the same    // length as arr, filled with zeros    let brr = new Array(arr.length).fill(0);    // Initialize a variable count to 0    let count = 0;    // Loop over each element of arr    // using an index variable i    for (let i = 0; i < arr.length; i++) {        // Loop until the corresponding element of brr        // is equal to the corresponding element of arr        while (brr[i] != arr[i]) {            // If the current element of brr is less            // than the corresponding element of arr            if (brr[i] < arr[i]) {                // Loop over each element of brr starting                // from the current index i                for (let j = i; j < arr.length; j++) {                    // Increment each element of brr until                    // it                    // matches the corresponding element of                    // arr                    brr[j]++;                }                // Increment the count variable for each                // increment operation                count++;            }            // If the current element of brr is greater            // than the corresponding element of arr            else {                // Loop over each element of brr starting                // from the current index i                for (let j = i; j < arr.length; j++) {                    // Decrement each element of brr until                    // it matches the corresponding element                    // of arr                    brr[j]--;                }                // Increment the count variable for each                // decrement operation                count++;            }        }    }    // Return the final count value    return count;}Â
let arr = [ 1, 2, 3, 4 ];console.log(min_operations(arr)); // Output: 4 |
4
Time Complexity: O(N2)Â
Auxiliary Space: O(1)
Â
Efficient Approach: The above approach can be optimized using Greedy Approach. Follow the steps below to solve the problem: Â
- For the 0th index, convert the number 0 to arr[0]. Therefore, the number of steps required will always be a[0]. Hence, add arr[0] to the answer.
- For all the other indices, the common greedy observation is to use the increase or the decrease operation by abs(a[i]-a[i-1]) times.
- The intuition behind this approach is, if the number is less than a[i-1], then increase everything from ((i-1).. n-1) by a[i], and then decrease (a[i-1] – a[i]) to get a[i].
- If a[i] > a[i-1], the approach is to use the increase operation from ((i-1)..n-1) by a[i-1], and for the remaining value, we increase it by (a[i]-a[i-1]) operations from (i..(n-1)).
- Therefore, traverse the array and for every element after the first, add the absolute difference of consecutive pairs to the answer.
- Finally, print the answer.
Below is the implementation of the above approach:
C++
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to calculate the minimum// steps to obtain the desired arrayint min_operation(int a[], int n){    // Initialize variable    int ans = 0;Â
    // Iterate over the array arr[]    for (int i = 0; i < n; i++) {Â
        // Check if i > 0        if (i > 0)Â
            // Update the answer            ans += abs(a[i] - a[i - 1]);Â
        else            ans += abs(a[i]);    }Â
    // Return the result    return ans;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 1, 2, 3, 4 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â
    cout << min_operation(arr, n);Â
    return 0;} |
Java
// Java Program to implement// the above approachimport java.util.*;class GFG{Â
// Function to calculate the minimum// steps to obtain the desired arraystatic int min_operation(int a[], int n){    // Initialize variable    int ans = 0;Â
    // Iterate over the array arr[]    for (int i = 0; i < n; i++)    {Â
        // Check if i > 0        if (i > 0)Â
            // Update the answer            ans += Math.abs(a[i] - a[i - 1]);Â
        else            ans += Math.abs(a[i]);    }Â
    // Return the result    return ans;}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â int arr[] = { 1, 2, 3, 4 };Â Â Â Â int n = arr.length;Â
    System.out.print(min_operation(arr, n));}}Â
// This code is contributed by gauravrajput1 |
Python3
# Python3 program to implement# the above approachÂ
# Function to calculate the minimum# steps to obtain the desired arraydef min_operation(a, n):Â
    # Initialize variable    ans = 0Â
    # Iterate over the array arr[]    for i in range(n):Â
        # Check if i > 0        if (i > 0):Â
            # Update the answer            ans += abs(a[i] - a[i - 1])        else:            ans += abs(a[i])Â
    # Return the result    return ansÂ
# Driver Codeif __name__ == "__main__":Â
    arr = [ 1, 2, 3, 4 ]    n = len(arr)Â
    print(min_operation(arr, n))Â
# This code is contributed by chitranayal |
C#
// C# Program to implement// the above approachusing System;class GFG{Â
// Function to calculate the minimum// steps to obtain the desired arraystatic int min_operation(int []a, int n){    // Initialize variable    int ans = 0;Â
    // Iterate over the array []arr    for (int i = 0; i < n; i++)    {Â
        // Check if i > 0        if (i > 0)Â
            // Update the answer            ans += Math.Abs(a[i] - a[i - 1]);Â
        else            ans += Math.Abs(a[i]);    }Â
    // Return the result    return ans;}Â
// Driver Codepublic static void Main(String[] args){Â Â Â Â int []arr = { 1, 2, 3, 4 };Â Â Â Â int n = arr.Length;Â
    Console.Write(min_operation(arr, n));}}Â
// This code is contributed by Amit Katiyar |
Javascript
<script>// javascript Program to implement// the above approachÂ
    // Function to calculate the minimum    // steps to obtain the desired array    function min_operation(a , n) {        // Initialize variable        var ans = 0;Â
        // Iterate over the array arr        for (i = 0; i < n; i++) {Â
            // Check if i > 0            if (i > 0)Â
                // Update the answer                ans += Math.abs(a[i] - a[i - 1]);Â
            else                ans += Math.abs(a[i]);        }Â
        // Return the result        return ans;    }Â
    // Driver Code             var arr = [ 1, 2, 3, 4 ];        var n = arr.length;Â
        document.write(min_operation(arr, n));Â
// This code contributed by Rajput-Ji</script> |
4
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



