最小化递增操作以使 Array 不递减
给定一个包含n 个整数的数组arr[] 。修改数组,使每个元素至少与前一个元素一样大。这可以通过将任何元素的值增加1来完成。任务是找到使数组不递减所需的最小移动次数。
例子:
Input: n = 5, arr[] = {8, 9, 2, 7, 7}
Output: 11
Explanation: The array should be modified to 8 9 9 9 9, this can be done by 11 moves(7 + 2 + 2).
Input: n = 10, arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
Output: 0
Explanation: The array is already non decreasing.
方法:思路是遍历数组,在当前元素小于前一个元素的任意一点,将当前元素作为前一个元素,并增加计数。请按照以下步骤解决问题:
- 将变量count初始化为0以存储结果。
- 使用变量i遍历范围[0, n)并执行以下任务:
- 如果arr[i]小于arr[i-1]则将arr[i]的值设置为arr[i-1]并将count的值增加arr[i]-arr[i-1]。
- 执行上述步骤后,打印count的值作为答案。
下面是上述方法的实现。
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the minimum
// value of count
long long countMoves(long int arr[], int n)
{
// Variable to store the answer
long int count = 0;
// Traverse the array
for (int i = 0; i < n; i++) {
if (i > 0) {
// Make the changes
if (arr[i] < arr[i - 1]) {
count += (arr[i - 1] - arr[i]);
arr[i] = arr[i - 1];
}
}
}
// Return the answer
return count;
}
// Driver Code
int main()
{
int n = 5;
long int arr[] = { 8, 9, 2, 7, 7 };
cout << countMoves(arr, n);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to find the minimum
// value of count
static long countMoves(int arr[], int n)
{
// Variable to store the answer
int count = 0;
// Traverse the array
for (int i = 0; i < n; i++) {
if (i > 0) {
// Make the changes
if (arr[i] < arr[i - 1]) {
count += (arr[i - 1] - arr[i]);
arr[i] = arr[i - 1];
}
}
}
// Return the answer
return count;
}
// Driver Code
public static void main(String[] args)
{
int n = 5;
int arr[] = { 8, 9, 2, 7, 7 };
System.out.print(countMoves(arr, n));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python code for the above approach
# Function to find the minimum
# value of count
def countMoves(arr, n):
# Variable to store the answer
count = 0
# Traverse the array
for i in range(n):
if (i > 0):
# Make the changes
if (arr[i] < arr[i - 1]):
count += (arr[i - 1] - arr[i])
arr[i] = arr[i - 1]
# Return the answer
return count
# Driver Code
n = 5
arr = [8, 9, 2, 7, 7]
print(countMoves(arr, n))
# This code is contributed by gfgking
C#
// C# code to implement above approach
using System;
class GFG
{
// Function to find the minimum
// value of count
static long countMoves(int []arr, int n)
{
// Variable to store the answer
int count = 0;
// Traverse the array
for (int i = 0; i < n; i++) {
if (i > 0) {
// Make the changes
if (arr[i] < arr[i - 1]) {
count += (arr[i - 1] - arr[i]);
arr[i] = arr[i - 1];
}
}
}
// Return the answer
return count;
}
// Driver code
public static void Main()
{
int n = 5;
int []arr = { 8, 9, 2, 7, 7 };
Console.Write(countMoves(arr, n));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
11
时间复杂度: O(N)
辅助空间: O(1)