[算法]按照要求保留数组元素使得和最大

按照要求保留数组元素使得和最大

题目地址
题目地址

题目描述

Description
Given an array of N numbers, we need to maximize the sum of selected numbers. At each step, you need to select a number Ai, delete one occurrence of Ai-1 (if exists) and Ai each from the array. Repeat these steps until the array gets empty. The problem is to maximize the sum of selected numbers.

Input
The first line of the input contains T denoting the number of the test cases. For each test case, the first line contains an integer n denoting the size of the array. Next line contains n space separated integers denoting the elements of the array.

Constraints:1<=T<=100,1<=n<=50,1<=A[i]<=20

Note: Numbers need to be selected from maximum to minimum.

Output
For each test case, the output is an integer displaying the maximum sum of selected numbers.

Sample Input 1

2
3
1 2 3
6
1 2 2 2 3 4

Sample Output 1

4
10

Explanation
#Testcase 1:
At first step we select 3, so 3 and 2 are deleted from the sequence leaving us with 1. Then we select 1 from the sequence and delete it. So the sum of selected numbers is 1+3 = 4.
#Testcase 2:
We select 4, so 4 and 3 are deleted leaving us with {1,2,2,2}. Then we select 2, so 2 & 1 are deleted. We are left with{2,2}. We select 2 in next two steps, thus the sum is 4+2+2+2=10.

题目解析
  1. 就是每次从数组中删掉一个最大的元素,然后如果有比这个元素小1的就一并删除
  2. 将每次删除的最大的元素累和,输出

ps:这题很迷,难在读题,不知道要考的地方到底在哪里

代码实现(python)
if __name__ == '__main__':
    for _ in range(int(input())):
        n = int(input())
        arr = [int(a) for a in input().split()]
        arr.sort()
        sum = 0
        while len(arr) > 0:
            tar = arr[-1]  # 选取最后一个也就是最大的元素
            sum += tar
            arr.remove(tar)  # 删除这个元素
            if tar - 1 in arr:  # 要找比当前小1的,因为数组已经有序了,可以直接倒序搜索
                arr.remove(tar - 1)  # 如果有就删除
        print(sum)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值