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)
{
vector< int > brr(arr.size(), 0);
int count = 0;
for ( int i = 0; i < arr.size(); i++) {
while (brr[i] != arr[i]) {
if (brr[i] < arr[i]) {
for ( int j = i; j < arr.size(); j++) {
brr[j]++;
}
count++;
}
else {
for ( int j = i; j < arr.size(); j++) {
brr[j]--;
}
count++;
}
}
}
return count;
}
int main()
{
vector< int > arr{ 1, 2, 3, 4 };
cout << min_operations(arr) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static int min_operations( int arr[])
{
int length=arr.length;
int []brr= new int [length];
int count = 0 ;
for ( int i = 0 ; i < length; i++) {
while (brr[i] != arr[i]) {
if (brr[i] < arr[i]) {
for ( int j = i; j < length; j++) {
brr[j]++;
}
count++;
}
else {
for ( int j = i; j < length; j++) {
brr[j]--;
}
count++;
}
}
}
return count;
}
public static void main (String[] args) {
int []arr= new int []{ 1 , 2 , 3 , 4 };
int minOperations= min_operations(arr);
System.out.println(minOperations);
}
}
|
Python
def min_operations(arr):
brr = [ 0 ] * len (arr)
count = 0
for i in range ( len (arr)):
while brr[i] ! = arr[i]:
if brr[i] < arr[i]:
for j in range (i, len (arr)):
brr[j] + = 1
count + = 1
else :
for j in range (i, len (arr)):
brr[j] - = 1
count + = 1
return count
arr = [ 1 , 2 , 3 , 4 ]
print (min_operations(arr))
|
C#
using System;
using System.Collections.Generic;
class MainClass {
static int MinOperations(List< int > arr) {
List< int > brr = new List< int >( new int [arr.Count]);
int count = 0;
for ( int i = 0; i < arr.Count; i++) {
while (brr[i] != arr[i]) {
if (brr[i] < arr[i]) {
for ( int j = i; j < arr.Count; j++) {
brr[j]++;
}
count++;
}
else {
for ( int j = i; j < arr.Count; j++) {
brr[j]--;
}
count++;
}
}
}
return count;
}
public static void Main( string [] args) {
List< int > arr = new List< int >{ 1, 2, 3, 4 };
Console.WriteLine(MinOperations(arr));
}
}
|
Javascript
function min_operations(arr)
{
let brr = new Array(arr.length).fill(0);
let count = 0;
for (let i = 0; i < arr.length; i++) {
while (brr[i] != arr[i]) {
if (brr[i] < arr[i]) {
for (let j = i; j < arr.length; j++) {
brr[j]++;
}
count++;
}
else {
for (let j = i; j < arr.length; j++) {
brr[j]--;
}
count++;
}
}
}
return count;
}
let arr = [ 1, 2, 3, 4 ];
console.log(min_operations(arr));
|
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++
#include <bits/stdc++.h>
using namespace std;
int min_operation( int a[], int n)
{
int ans = 0;
for ( int i = 0; i < n; i++) {
if (i > 0)
ans += abs (a[i] - a[i - 1]);
else
ans += abs (a[i]);
}
return ans;
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << min_operation(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int min_operation( int a[], int n)
{
int ans = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (i > 0 )
ans += Math.abs(a[i] - a[i - 1 ]);
else
ans += Math.abs(a[i]);
}
return ans;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 };
int n = arr.length;
System.out.print(min_operation(arr, n));
}
}
|
Python3
def min_operation(a, n):
ans = 0
for i in range (n):
if (i > 0 ):
ans + = abs (a[i] - a[i - 1 ])
else :
ans + = abs (a[i])
return ans
if __name__ = = "__main__" :
arr = [ 1 , 2 , 3 , 4 ]
n = len (arr)
print (min_operation(arr, n))
|
C#
using System;
class GFG{
static int min_operation( int []a, int n)
{
int ans = 0;
for ( int i = 0; i < n; i++)
{
if (i > 0)
ans += Math.Abs(a[i] - a[i - 1]);
else
ans += Math.Abs(a[i]);
}
return ans;
}
public static void Main(String[] args)
{
int []arr = { 1, 2, 3, 4 };
int n = arr.Length;
Console.Write(min_operation(arr, n));
}
}
|
Javascript
<script>
function min_operation(a , n) {
var ans = 0;
for (i = 0; i < n; i++) {
if (i > 0)
ans += Math.abs(a[i] - a[i - 1]);
else
ans += Math.abs(a[i]);
}
return ans;
}
var arr = [ 1, 2, 3, 4 ];
var n = arr.length;
document.write(min_operation(arr, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!