给定一个正整数数组arr [] ,任务是找到使所有元素均减为0的最小步骤。在单个步骤中,可以将-1同时添加到数组的所有非零元素中。
例子:
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
天真的方法:一种简单的方法是先对数组进行排序,然后从最小元素开始,计算将其减少到0所需的步骤数。然后,从下一个数组元素开始减少此计数,因为所有元素都将在更新同时。
高效的方法:可以观察到,最小步数将始终等于数组中的最大元素。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the minimum steps
// required to reduce all the elements to 0
int minSteps(int arr[], int n)
{
// Maximum element from the array
int maxVal = *max_element(arr, arr + n);
return maxVal;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 4 };
int n = sizeof(arr) / sizeof(int);
cout << minSteps(arr, n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// method to get maximum number from array elements
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;
}
// Function to return the minimum steps
// required to reduce all the elements to 0
static int minSteps(int arr[], int n)
{
// Maximum element from the array
int maxVal = getMax(arr);
return maxVal;
}
// Driver code
public static void main (String[] args)
{
int arr[] = { 1, 2, 4 };
int n = arr.length;
System.out.println(minSteps(arr, n));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function to return the minimum steps
# required to reduce all the elements to 0
def minSteps(arr, n):
# Maximum element from the array
maxVal = max(arr)
return maxVal
# Driver code
arr = [1, 2, 4]
n = len(arr)
print(minSteps(arr, n))
# This code is contributed by Mohit Kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// method to get maximum number from array elements
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;
}
// Function to return the minimum steps
// required to reduce all the elements to 0
static int minSteps(int []arr, int n)
{
// Maximum element from the array
int maxVal = getMax(arr);
return maxVal;
}
// Driver code
public static void Main(String []args)
{
int []arr = { 1, 2, 4 };
int n = arr.Length;
Console.WriteLine(minSteps(arr, n));
}
}
// This code is contributed by Arnab Kundu
输出:
4