Minimum number of steps required to obtain the given Array by the given operations
Last Updated :
28 Aug, 2023
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
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 array
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 += abs(a[i] - a[i - 1]);
else
ans += abs(a[i]);
}
// Return the result
return ans;
}
// Driver Code
int 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 approach
import java.util.*;
class GFG{
// Function to calculate the minimum
// steps to obtain the desired array
static 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 Code
public 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 array
def 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 Code
if __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 approach
using System;
class GFG{
// Function to calculate the minimum
// steps to obtain the desired array
static 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 Code
public 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>
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Minimum operations of given type required to empty given array Given an array arr[] of size N, the task is to find the total count of operations required to remove all the array elements such that if the first element of the array is the smallest element, then remove that element, otherwise move the first element to the end of the array. Examples: Input: A[] =
14 min read
Minimum count of elements required to obtain the given Array by repeated mirror operations Given an array arr[] consisting of N integers, the task is to find the array K[] of minimum possible length such that after performing multiple mirror operations on K[], the given array arr[] can be obtained. Mirror Operation: Appending all the array elements to the original array in reverse order.
7 min read
Minimum Steps to obtain N from 1 by the given operations Given an integer N, the task is to find the minimum number of operations needed to obtain the number N starting from 1. Below are the operations: Add 1 to the current number.Multiply the current number by 2.Multiply the current number by 3. Print the minimum number of operations required and the cor
15+ min read
Minimum steps required to reach the end of Array with a given capacity Given an array arr[] of size n. You will have to traverse the array from left to right deducting each element of the array from the initial capacity, such that your initial capacity should never go below 0. In case, the current capacity is less than the current element, we can traverse back to the s
15 min read
Print lexicographically smallest array by reduce K to 0 in minimum number of operations Given an array arr[] and an integer K, the task is to reduce the value of K to 0 by performing the following operations. One operation is defined as choosing 2 indices i, j and subtracting the minimum of arr[i] and K ( i.e., X = min(arr[i], K) from arr[i] ( i.e., arr[i] = arr[i] - X) and adding the
7 min read
Make the array elements equal by performing given operations minimum number of times Given an array arr[] of size N, the task is to make all the array elements equal by performing following operations minimum number of times: Increase all array elements of any suffix array by 1.Decrease all the elements of any suffix array by 1.Replace any array element y another. Examples: Input: a
7 min read