Minimum steps required to reduce all the elements of the array to zero
Last Updated :
19 Mar, 2022
Given an array arr[] of positive integers, the task is to find the minimum steps to reduce all the elements to 0. In a single step, -1 can be added to all the non-zero elements of the array at the same time.
Examples:
Input: arr[] = {1, 5, 6}
Output: 6
Operation 1: arr[] = {0, 4, 5}
Operation 2: arr[] = {0, 3, 4}
Operation 3: arr[] = {0, 2, 3}
Operation 4: arr[] = {0, 1, 2}
Operation 5: arr[] = {0, 0, 1}
Operation 6: arr[] = {0, 0, 0}
Input: arr[] = {1, 1}
Output: 1
Naive approach: A simple approach is to first sort the array then starting from the minimum element, count the number of steps required to reduce it to 0. This count will then be reduced from the next array element as all the elements will be updated at the same time.
Efficient approach: It can be observed that the minimum number of steps will always be equal to the maximum element from the array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minSteps( int arr[], int n)
{
int maxVal = *max_element(arr, arr + n);
return maxVal;
}
int main()
{
int arr[] = { 1, 2, 4 };
int n = sizeof (arr) / sizeof ( int );
cout << minSteps(arr, n);
return 0;
}
|
Java
class GFG
{
static int getMax( int inputArray [])
{
int maxValue = inputArray[ 0 ];
for ( int i = 1 ; i < inputArray.length; i++)
{
if (inputArray[i] > maxValue)
{
maxValue = inputArray[i];
}
}
return maxValue;
}
static int minSteps( int arr[], int n)
{
int maxVal = getMax(arr);
return maxVal;
}
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 4 };
int n = arr.length;
System.out.println(minSteps(arr, n));
}
}
|
Python3
def minSteps(arr, n):
maxVal = max (arr)
return maxVal
arr = [ 1 , 2 , 4 ]
n = len (arr)
print (minSteps(arr, n))
|
C#
using System;
class GFG
{
static int getMax( int []inputArray)
{
int maxValue = inputArray[0];
for ( int i = 1; i < inputArray.Length; i++)
{
if (inputArray[i] > maxValue)
{
maxValue = inputArray[i];
}
}
return maxValue;
}
static int minSteps( int []arr, int n)
{
int maxVal = getMax(arr);
return maxVal;
}
public static void Main(String []args)
{
int []arr = { 1, 2, 4 };
int n = arr.Length;
Console.WriteLine(minSteps(arr, n));
}
}
|
Javascript
<script>
function minSteps(arr, n)
{
let maxVal = Math.max(...arr);
return maxVal;
}
let arr = [ 1, 2, 4 ];
let n = arr.length;
document.write(minSteps(arr, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...