📌  相关文章
📜  通过使给定数组不递减来实现最大和

📅  最后修改于: 2021-09-06 06:44:15             🧑  作者: Mango

给定一个数组 arr[],任务是通过重复将数组元素减 1,从给定数组中获得一个具有最大和的非减数组。

解释:

处理方法:按照以下步骤解决问题:

  • 反向遍历数组。
  • 比较每对相邻元素以检查数组是否非递减,即检查是否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