给定一个由N个整数组成的数组arr [] ,任务是找到使数组不递减所需的最少操作数,其中,每个操作都涉及将给定数组中非递减子数组的所有元素增加1 。
例子:
Input: arr[] = {1, 3, 1, 2, 4}
Output: 2
Explanation:
Operation 1: Incrementing arr[2] modifies array to {1, 3, 2, 2, 4}
Operation 2: Incrementing subarray {arr[2], arr[3]} modifies array to {1, 3, 3, 3, 4}
Therefore, the final array is non-decreasing.
Input: arr[] = {1, 3, 5, 10}
Output: 0
Explanation: The array is already non-decreasing.
方法:请按照以下步骤解决问题:
- 如果该数组已经是一个非递减数组,则无需进行任何更改。
- 否则,对于0≤i
任何索引i ,如果arr [i]> arr [i + 1] ,则将差值添加到ans 。 - 最后打印答的答案。
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to return to the minimum
// number of operations required to
// make the array non-decreasing
int getMinOps(int arr[], int n)
{
// Stores the count of operations
int ans = 0;
for(int i = 0; i < n - 1; i++)
{
// If arr[i] > arr[i + 1], add
// arr[i] - arr[i + 1] to the answer
// Otherwise, add 0
ans += max(arr[i] - arr[i + 1], 0);
}
return ans;
}
// Driver Code
int main()
{
int arr[] = { 1, 3, 1, 2, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << (getMinOps(arr, n));
}
// This code is contributed by PrinciRaj1992
Java
// Java Program to implement the
// above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to return to the minimum
// number of operations required to
// make the array non-decreasing
public static int getMinOps(int[] arr)
{
// Stores the count of operations
int ans = 0;
for (int i = 0; i < arr.length - 1; i++) {
// If arr[i] > arr[i + 1], add
// arr[i] - arr[i + 1] to the answer
// Otherwise, add 0
ans += Math.max(arr[i] - arr[i + 1], 0);
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 1, 3, 1, 2, 4 };
System.out.println(getMinOps(arr));
}
}
Python3
# Python3 program to implement
# the above approach
# Function to return to the minimum
# number of operations required to
# make the array non-decreasing
def getMinOps(arr):
# Stores the count of operations
ans = 0
for i in range(len(arr) - 1):
# If arr[i] > arr[i + 1], add
# arr[i] - arr[i + 1] to the answer
# Otherwise, add 0
ans += max(arr[i] - arr[i + 1], 0)
return ans
# Driver Code
# Given array arr[]
arr = [ 1, 3, 1, 2, 4 ]
# Function call
print(getMinOps(arr))
# This code is contributed by Shivam Singh
C#
// C# Program to implement the
// above approach
using System;
class GFG
{
// Function to return to the minimum
// number of operations required to
// make the array non-decreasing
public static int getMinOps(int[] arr)
{
// Stores the count of operations
int ans = 0;
for (int i = 0; i < arr.Length - 1; i++)
{
// If arr[i] > arr[i + 1], add
// arr[i] - arr[i + 1] to the answer
// Otherwise, add 0
ans += Math.Max(arr[i] - arr[i + 1], 0);
}
return ans;
}
// Driver Code
public static void Main(String[] args)
{
int[] arr = { 1, 3, 1, 2, 4 };
Console.WriteLine(getMinOps(arr));
}
}
// This code is contributed by Amit Katiyar
输出:
2
时间复杂度: O(N)
辅助空间: O(1)