📌  相关文章
📜  通过重新排列数组来最大化给定数组的总和,使得相邻元素之间的差异最多为 1

📅  最后修改于: 2021-09-03 03:29:55             🧑  作者: Mango

给定一个由N 个正整数组成的数组arr[] ,任务是最大化数组元素的总和,使得数组的第一个元素为1且数组相邻元素之间的差值最多为 1以下操作:

  • 以任何方式重新排列数组元素。
  • 将任何元素减少到至少为1 的任何数字。

例子:

朴素的方法:最简单的方法是对给定数组进行排序,然后在排序后的数组中遍历并减少不满足给定条件的元素。

时间复杂度: O(N * log N),其中 N 是给定数组的大小。
辅助空间: O(N)

高效的方法:这个想法是使用哈希概念来存储给定数组元素的频率。请按照以下步骤解决问题:

  • 创建一个大小为(N+1)的辅助数组count[]来存储arr[i] 的频率。
  • 将频率存储在count[] 中,如果arr[i]大于N,则增加count[N]
  • sizeans初始化为0 ,分别存储先前选择的整数和最大可能总和。
  • 使用变量K遍历给定的数组count[]数组并执行以下操作:
    • 为每个K迭代 while 循环,直到count[K] > 0size < K
    • 在 while 循环中将size增加1并按size增加ans并将count[K]减少1
    • 在 while 循环结束后用K*count[K]增加ans
  • 完成上述步骤后,将ans的值打印为最大可能和。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find maximum possible
// sum after changing the array elements
// as per the given constraints
long maxSum(int a[], int n)
{
     
    // Stores the frequency of
    // elements in given array
    int count[n + 1] = {0};
 
    // Update frequncy
    for(int i = 0; i < n; i++)
        count[min(a[i], n)]++;
 
    // Stores the previously
    // selected integer
    int size = 0;
 
    // Stores the maximum possible sum
    long ans = 0;
 
    // Traverse over array count[]
    for(int k = 1; k <= n; k++)
    {
         
        // Run loop for each k
        while (count[k] > 0 && size < k)
        {
            size++;
            ans += size;
            count[k]--;
        }
 
        // Update ans
        ans += k * count[k];
    }
 
    // Return maximum possible sum
    return ans;
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 3, 5, 1 };
 
    // Size of array
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << (maxSum(arr, n));
    return 0;
}
 
// This code is contributed by akhilsaini


Java
// Java program for the above approach
 
import java.util.*;
 
class GFG {
 
    // Function to find maximum possible
    // sum after changing the array elements
    // as per the given constraints
    static long maxSum(int[] a)
    {
        // Length of given array
        int n = a.length;
 
        // Stores the frequency of
        // elements in given array
        int[] count = new int[n + 1];
 
        // Update frequncy
        for (int x : a)
            count[Math.min(x, n)]++;
 
        // stores the previously
        // selected integer
        int size = 0;
 
        // Stores the maximum possible sum
        long ans = 0;
 
        // Traverse over array count[]
        for (int k = 1; k <= n; k++) {
 
            // Run loop for each k
            while (count[k] > 0 && size < k) {
                size++;
                ans += size;
                count[k]--;
            }
 
            // Update ans
            ans += k * count[k];
        }
 
        // Return maximum possible sum
        return ans;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 3, 5, 1 };
 
        // Function Call
        System.out.println(maxSum(arr));
    }
}


Python3
# Python3 program for the above approach
 
# Function to find maximum possible
# sum after changing the array elements
# as per the given constraints
def maxSum(a, n):
 
    # Stores the frequency of
    # elements in given array
    count = [0] * (n + 1)
 
    # Update frequncy
    for i in range(0, n):
        count[min(a[i], n)] += 1
 
    # stores the previously
    # selected integer
    size = 0
 
    # Stores the maximum possible sum
    ans = 0
 
    # Traverse over array count[]
    for k in range(1, n + 1):
         
        # Run loop for each k
        while (count[k] > 0 and size < k):
            size += 1
            ans += size
            count[k] -= 1
 
        # Update ans
        ans += k * count[k]
 
    # Return maximum possible sum
    return ans
 
# Driver Code
if __name__ == '__main__':
 
    # Given array arr[]
    arr = [ 3, 5, 1 ]
 
    # Size of array
    n = len(arr)
 
    # Function Call
    print(maxSum(arr, n))
 
# This code is contributed by akhilsaini


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to find maximum possible
// sum after changing the array elements
// as per the given constraints
static long maxSum(int[] a)
{
     
    // Length of given array
    int n = a.Length;
 
    // Stores the frequency of
    // elements in given array
    int[] count = new int[n + 1];
 
    // Update frequncy
    for(int i = 0; i < n; i++)
        count[Math.Min(a[i], n)]++;
 
    // stores the previously
    // selected integer
    int size = 0;
 
    // Stores the maximum possible sum
    long ans = 0;
 
    // Traverse over array count[]
    for(int k = 1; k <= n; k++)
    {
         
        // Run loop for each k
        while (count[k] > 0 && size < k)
        {
            size++;
            ans += size;
            count[k]--;
        }
 
        // Update ans
        ans += k * count[k];
    }
 
    // Return maximum possible sum
    return ans;
}
 
// Driver Code
public static void Main()
{
     
    // Given array arr[]
    int[] arr = { 3, 5, 1 };
 
    // Function call
    Console.Write(maxSum(arr));
}
}
 
// This code is contributed by akhilsaini


Javascript


输出:
6

时间复杂度: O(N),其中 N 是给定数组的大小。
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live