📌  相关文章
📜  将数组的所有元素减少为零所需的最小步骤

📅  最后修改于: 2021-10-26 05:51:52             🧑  作者: Mango

给定一个正整数数组arr[] ,任务是找到将所有元素减少到0的最小步骤。在单个步骤中,可以同时将-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


Javascript


输出:
4

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程