给定一个数组 arr[],任务是通过重复将数组元素减 1,从给定数组中获得一个具有最大和的非减数组。
解释:
Input: arr[] = {1, 5, 2, 3, 4}
Output: 12
Explanation: Modify the given array to {1, 2, 2, 3, 4} by reducing 5 to 2 to obtain maximum sum possible from a non-decreasing array.
Input: arr[] = {1, 2, 5, 9, -3}
Output: -15
处理方法:按照以下步骤解决问题:
- 反向遍历数组。
- 比较每对相邻元素以检查数组是否非递减,即检查是否a[i – 1] ≤ a[i]。
- 如果发现为假,则分配a[i – 1] = a[i] 。
- 完成上述步骤后, p[rin t 修改后的数组的总和。
下面是上述方法的实现:
C++
// C++ program for the
// above approach
#include
using namespace std;
int maximumSum(vector a,
int n)
{
//Traverse the array in
// reverse
for (int i = n - 1; i >= 0; i--)
{
//If a[i] is decreasing
if (!(a[i - 1] <= a[i]))
a[i - 1] = a[i];
}
int sum = 0;
for(int i : a) sum += i;
//Return sum of the array
return sum;
}
//Driver code
int main()
{
//Given array arr[]
vector arr = {1, 5, 2, 3, 4};
int N = arr.size();
cout << (maximumSum(arr, N));
}
// This code is contributed by Mohit Kumar 29
Java
// Java program for the
// above approach
import java.util.*;
class GFG{
static int maximumSum(int[] a,
int n)
{
//Traverse the array in
// reverse
for (int i = n - 1; i > 0; i--)
{
//If a[i] is decreasing
if (!(a[i - 1] <= a[i]))
a[i - 1] = a[i];
}
int sum = 0;
for(int i : a) sum += i;
//Return sum of the array
return sum;
}
//Driver code
public static void main(String[] args)
{
//Given array arr[]
int[] arr = {1, 5, 2, 3, 4};
int N = arr.length;
System.out.print(maximumSum(arr, N));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program for the
# above approach
def maximumSum(a, n):
# Traverse the array in reverse
for i in range(n-1, 0, -1):
# If a[i] is decreasing
if not a[i-1] <= a[i]:
a[i-1] = a[i]
# Return sum of the array
return sum(a)
# Driver Code
if __name__ == '__main__':
arr = [1, 5, 2, 3, 4]
N = len(arr)
print(maximumSum(arr, N))
C#
// C# program for the
// above approach
using System;
class GFG{
static int maximumSum(int[] a, int n)
{
// Traverse the array in
// reverse
for(int i = n - 1; i > 0; i--)
{
// If a[i] is decreasing
if (!(a[i - 1] <= a[i]))
a[i - 1] = a[i];
}
int sum = 0;
foreach(int i in a) sum += i;
// Return sum of the array
return sum;
}
// Driver code
public static void Main(String[] args)
{
// Given array []arr
int[] arr = { 1, 5, 2, 3, 4 };
int N = arr.Length;
Console.Write(maximumSum(arr, N));
}
}
// This code is contributed by shikhasingrajput
输出:
12
时间复杂度: O(N)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live