📌  相关文章
📜  最大化数组中选定数字的总和以使其为空

📅  最后修改于: 2021-04-23 17:24:26             🧑  作者: Mango

给定一个由N个数字组成的数组,我们需要最大化所选数字的总和。在每一步骤中,您需要选择一个数字A i ,删除一个数字,并删除数组中所有出现的A i -1A i +1 (如果存在)。重复这些步骤,直到数组变空。问题是要最大化所选数字的总和。
注意:如果数组中存在A i +1和A i -1元素,而不是A i + 1和A i-1,我们必须删除所有出现的元素。
例子:

Input : a[] = {1, 2, 3} 
Output : 4
Explanation: At first step we select 1, so 1 and 
2 are deleted from the sequence leaving us with 3. 
Then we select 3 from the sequence and delete it.
So the sum of selected numbers is 1+3 = 4. 


Input : a[] =  {1, 2, 2, 2, 3, 4}
Output : 10 
Explanation : Select one of the 2's from the array, so 
2, 2-1, 2+1 will be deleted and we are left with {2, 2, 4}, 
since 1 and 3 are deleted. Select 2 in next two steps, 
and then select 4 in the last step.
We get a sum of 2+2+2+4=10 which is the maximum possible. 

我们的目标是最大化所选数字的总和。这个想法是预先计算数组a []中所有数字x的出现。

方法:

  • 计算数组中的MAX值。
  • 创建一个大小为MAX的数组,并在其中存储每个元素的出现。
  • 由于我们要最大化答案,因此我们将从MAX值开始迭代到0。
  • 如果i元素的发生是大于0,然后将其添加到我们的答案减1的i-1元素的出现,以及1,因为我们把它添加到我们的答案也减少了第i的发生。
  • 我们没有降低i + 1元素的发生,因为我们已经从年底开始使i + 1已处理。
  • 第i元素可能多次出现,这就是为什么不减少i以便停留在同一元素上的原因。

下面是上述想法的实现:

C++
// CPP program to Maximize the sum of selected
// numbers by deleting three consecutive numbers.
#include 
using namespace std;
 
// function to maximize the sum of selected numbers
int maximizeSum(int arr[], int n) {
 
      // Largest element in the array
    int mx = -1;
    for(int i = 0; i < n; i++)
    {
        mx = max(mx, arr[i]);
    }   
     
    // An array to count the occurence of each element
    int freq[mx + 1];
     
    memset(freq, 0, sizeof(freq));
     
    for(int i = 0; i < n; i++)
    {
        freq[arr[i]]++;
    }
     
    // ans to store the result
    int ans = 0, i=mx;
     
    // Using the above mentioned approach
    while(i>0){
         
        // if occurence is greater than 0
        if(freq[i] > 0){
            // add it to ans
            ans += i;
             
            // decrease i-1th element by 1
            freq[i-1]--;
             
            // decrease ith element by 1
            freq[i]--;
        }else{
            // decrease i
            i--;
        }       
    }
     
    return ans;
}
 
// Driver code
int main()
{
  int a[] = {1, 2, 3};
  int n = sizeof(a) / sizeof(a[0]);
  cout << maximizeSum(a, n);
  return 0;
}


Java
// Java implementation of the approach
import java.util.*;
import java.math.*;
 
class GFG
{
      // Function to maximise the sum of selected nummbers
      //by deleting occurences of Ai-1 and Ai+1
    public static int getMaximumSum (int arr[]) {
         
        // Number of elements in the array
        int n = arr.length;
         
        // Largest element in the array
        int max = -1;
        for(int i = 0; i < n; i++)
        {
            max = Math.max(max, arr[i]);
        }
         
        // An array to count the occurence of each element
        int []freq = new int[max + 1];
         
        for(int i = 0; i < n; i++)
        {
            freq[arr[i]]++;
        }
         
        // ans to store the result
        int ans = 0, i=max;
         
        // Using the above mentioned approach
        while(i>0){
             
            // if occurence is greater than 0
            if(freq[i] > 0){
                // add it to ans
                ans += i;
                 
                // decrease i-1th element by 1
                freq[i-1]--;
                 
                // decrease ith element by 1
                freq[i]--;
            }else{               
                // decrease i
                i--;
            }           
        }
         
        return ans;
    }
 
      // Driver code
      public static void main(String[] args)
      {
          int []a = {1, 2, 3};
 
          System.out.println(getMaximumSum(a));
      }
}


Python3
# Python3 program to Maximize the sum of selected
# numbers by deleting three consecutive numbers.
 
# function to maximize the sum of
# selected numbers
def maximizeSum(a, n) :
 
        # maximum in the sequence
    maximum = max(a)
     
    # stores the occurrences of the numbers
    ans = dict.fromkeys(range(0, n + 1), 0)
 
    # marks the occurrence of every
    # number in the sequence
    for i in range(n) :
        ans[a[i]] += 1
         
    # ans to store the result
    result = 0
    i = maximum
     
    # Using the above mentioned approach
    while i > 0:
         
        # if occurence is greater than 0
        if ans[i] > 0:
            # add it to ans
            result += i;
             
            # decrease i-1th element by 1
            ans[i-1] -= 1;
             
            # decrease ith element by 1
            ans[i] -= 1;
        else:          
            # decrease i
            i -= 1;
     
    return result;
 
# Driver code
if __name__ == "__main__" :
 
    a = [1, 2, 3]
    n = len(a)
    print(maximizeSum(a, n))
 
# This code is contributed by Ryuga


C#
// C# implementation of the approach
using System;
using System.Linq;
 
class GFG
{
 
// Function to maximise the sum of selected nummbers
//by deleting occurences of Ai-1 and Ai+1
static int getMaximumSum(int []arr)
{
    // Number of elements in the array
    int n = arr.Length;
 
    // Largest element in the array
    int max = arr.Max();
 
    // An array to count the occurence of each element
    int []freq = new int[max + 1];
 
    for(int j = 0; j < n; j++)
    {
      freq[arr[j]]++;
    }
 
    // ans to store the result
    int ans = 0, i=max;
 
    // Using the above mentioned approach
    while(i>0){
 
      // if occurence is greater than 0
      if(freq[i] > 0){
        // add it to ans
        ans += i;
 
        // decrease i-1th element by 1
        freq[i-1]--;
 
        // decrease ith element by 1
        freq[i]--;
      }else{               
        // decrease i
        i--;
      }           
    }
 
    return ans;
}
 
// Driver code
public static void Main(string[] args)
{
    int []a = {1, 2, 3};
 
    Console.Write(getMaximumSum(a));
}
}
 
// This code is contributed by rock_cool


输出:

4

时间复杂度:时间复杂度将为(A max + 元素中出现率最高的arr),因为如果频率大于1,则我们将对该元素进行多次处理。

-其中A max是数组A []中存在的最大元素。

空间复杂度: O(A max ),其中A max是数组A []中存在的最大元素。