Maximum sum possible by making given array non-decreasing
Given an array arr[], the task is to obtain a non-decreasing array with the maximum sum from the given array by repeatedly decrementing array elements by 1.
Explanation:
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
Approach: Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maximumSum(vector< int > a,
int n)
{
for ( int i = n - 1; i >= 0; i--)
{
if (!(a[i - 1] <= a[i]))
a[i - 1] = a[i];
}
int sum = 0;
for ( int i : a) sum += i;
return sum;
}
int main()
{
vector< int > arr = {1, 5, 2, 3, 4};
int N = arr.size();
cout << (maximumSum(arr, N));
}
|
Java
import java.util.*;
class GFG{
static int maximumSum( int [] a,
int n)
{
for ( int i = n - 1 ; i > 0 ; i--)
{
if (!(a[i - 1 ] <= a[i]))
a[i - 1 ] = a[i];
}
int sum = 0 ;
for ( int i : a) sum += i;
return sum;
}
public static void main(String[] args)
{
int [] arr = { 1 , 5 , 2 , 3 , 4 };
int N = arr.length;
System.out.print(maximumSum(arr, N));
}
}
|
Python3
def maximumSum(a, n):
for i in range (n - 1 , 0 , - 1 ):
if not a[i - 1 ] < = a[i]:
a[i - 1 ] = a[i]
return sum (a)
if __name__ = = '__main__' :
arr = [ 1 , 5 , 2 , 3 , 4 ]
N = len (arr)
print (maximumSum(arr, N))
|
C#
using System;
class GFG{
static int maximumSum( int [] a, int n)
{
for ( int i = n - 1; i > 0; i--)
{
if (!(a[i - 1] <= a[i]))
a[i - 1] = a[i];
}
int sum = 0;
foreach ( int i in a) sum += i;
return sum;
}
public static void Main(String[] args)
{
int [] arr = { 1, 5, 2, 3, 4 };
int N = arr.Length;
Console.Write(maximumSum(arr, N));
}
}
|
Javascript
<script>
function maximumSum(a,n)
{
for (let i = n - 1; i > 0; i--)
{
if (!(a[i - 1] <= a[i]))
a[i - 1] = a[i];
}
let sum = 0;
for (let i=0;i< a.length;i++) sum += a[i];
return sum;
}
let arr=[1, 5, 2, 3, 4];
let N = arr.length;
document.write(maximumSum(arr, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
23 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...